问:
How do I get the index of the common integer element from two separate lists and plug it to another list?

I have 3 lists.

```<code>A_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

```<code>Q_act = [2, 3]
</code>```

```<code>dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]
</code>```

All lists are integers.

What I am trying to do is to compare Q_act with A_set then obtain the indices of the numbers that match from A_set.

(Example:
Q_act has the elements [2,3]
it is located in indices [1,2] from A_set)

Afterwards, I will use those indices to obtain the corresponding value in dur and store this in a list called p_dur_Q_act.

(Example: using the result from the previous example, [1,2]

The values in the dur list corresponding to the indices [1,2] should be stored in another list called p_dur_Q_act

i.e. [4,5] should be the values stored in the list p_dur_Q_act)

So, how do I get the index of the common integer element (which is [1,2]) from two separate lists and plug it to another list?

So far here are the code(s) I used:

This one, I wrote because it returns the index. But not [4,5].

```<code>p_Q = set(Q_act).intersection(A_set)
    p_dur_Q_act = [i + 1 for i, x in enumerate(p_Q)]
    print(p_dur_Q_act)
</code>```

I also tried this but I receive an error TypeError: argument of type 'int' is not iterable

```<code> p_dur_Q_act = [i + 1 for i, x in enumerate(Q_act) if any(elem in x for elem in A_set)]
    print(p_dur_Q_act)
</code>```

答:
Another option is to use the enumerate iterator to generate every index, and then select only the ones you want:

```<code>a_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
q_act = [2, 3]
dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]

p_dur_q_act = [i for i,v in enumerate(a_set) if v in q_act]

print([dur[p] for p in p_dur_q_act if p in dur]) # [4, 5]
</code>```

This is more efficient than repeatedly calling index if the number of matches is large, because the number of calls is proportional to the number of matches, but the duration of calls is proportional to the length of a_set.  The enumerate approach can be made even more efficient by turning q_act into a set, since in scales better with sets than lists.  At these scales, though, there will be no observable difference.

You don't need to map these to index values, though.  You can get the same result if you use zip to map a_set to dur and then select the d values whose a values are in q_act.

```<code>a_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
q_act = {2, 3}
dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]

p_dur_q_act = [d for a, d in zip(a_set, dur) if a in q_act]
</code>```

Body:
I have 3 lists.

A_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Q_act = [2, 3]

dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]

All lists are integers.

What I am trying to do is to compare Q_act with A_set then obtain the indices of the numbers that match from A_set.

(Example:
Q_act has the elements [2,3]
it is located in indices [1,2] from A_set)

Afterwards, I will use those indices to obtain the corresponding value in dur and store this in a list called p_dur_Q_act.

(Example: using the result from the previous example, [1,2]

The values in the dur list corresponding to the indices [1,2] should be stored in another list called p_dur_Q_act

i.e. [4,5] should be the values stored in the list p_dur_Q_act)

So, how do I get the index of the common integer element (which is [1,2]) from two separate lists and plug it to another list?

So far here are the code(s) I used:

This one, I wrote because it returns the index. But not [4,5].

p_Q = set(Q_act).intersection(A_set)
    p_dur_Q_act = [i + 1 for i, x in enumerate(p_Q)]
    print(p_dur_Q_act)

I also tried this but I receive an error TypeError: argument of type 'int' is not iterable

 p_dur_Q_act = [i + 1 for i, x in enumerate(Q_act) if any(elem in x for elem in A_set)]
    print(p_dur_Q_act)

Body:
Another option is to use the enumerate iterator to generate every index, and then select only the ones you want:

a_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
q_act = [2, 3]
dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]

p_dur_q_act = [i for i,v in enumerate(a_set) if v in q_act]

print([dur[p] for p in p_dur_q_act if p in dur]) # [4, 5]

This is more efficient than repeatedly calling index if the number of matches is large, because the number of calls is proportional to the number of matches, but the duration of calls is proportional to the length of a_set.  The enumerate approach can be made even more efficient by turning q_act into a set, since in scales better with sets than lists.  At these scales, though, there will be no observable difference.

You don't need to map these to index values, though.  You can get the same result if you use zip to map a_set to dur and then select the d values whose a values are in q_act.

a_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
q_act = {2, 3}
dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]

p_dur_q_act = [d for a, d in zip(a_set, dur) if a in q_act]


来源: stackexchange

问:
Spark submit fails in k8s Cluster
I am trying to submit the Spark application to minikube k8s cluster (Spark Version used : 2.4.3) using below command:

```<code>spark-submit \
--master <K8S_MASTER> \
--deploy-mode cluster \
--conf spark.executor.instances=2 \
--conf spark.kubernetes.container.image=<my docker image> \
--conf spark.kubernetes.driver.pod.name=spark-py-driver \
--conf spark.executor.memory=2g \
--conf spark.driver.memory=2g \
local:///home/proj/app/run.py <arguments>
</code>```

Please note that the python script run.py exists in my docker image in the same path
Once I do the Spark submit, the Spark job starts and the driver job gets killed. i could see only the below logs in the Driver pod

[FATAL tini (6)] exec driver-py failed: No such file or directory

I have verified the execution of pyspark job by doing a docker run on the docker image and is able to see that the above python code gets executed.

These are the events for the failed driver pod

Events:

```<code>  Type     Reason       Age   From               Message
  ----     ------       ----  ----               -------
  Normal   Scheduled    52m   default-scheduler  Successfully assigned ***-develop/run-py-1590847453453-driver to minikube
  Warning  FailedMount  52m   kubelet, minikube  MountVolume.SetUp failed for volume "spark-conf-volume" : configmap "run-py-1590847453453-driver-conf-map" not found
  Normal   Pulled       52m   kubelet, minikube  Container image "******************:latest" already present on machine
  Normal   Created      52m   kubelet, minikube  Created container spark-kubernetes-driver
  Normal   Started      52m   kubelet, minikube  Started container spark-kubernetes-driver
</code>```

答:
I am using one of the base images from my org.  But issue regarding the mount is only a Warning and the pod got successfully assigned after that.</p>

```<code>FROM <project_repo>/<proj>/${SPARK_ALPINE_BUILD}
ENV SPARK_OPTS --driver-java-options=-Dlog4j.logLevel=info
ENV SPARK_MASTER "spark://spark-master:7077"

ADD https://repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar $SPARK_HOME/jars
ADD https://repo1.maven.org/maven2/com/datastax/spark/spark-cassandra-connector_2.11/2.3.2/spark-cassandra-connector_2.11-2.3.2.jar $SPARK_HOME/jars
USER root

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

WORKDIR /home/<proj>/app
# copy files
COPY src/configs ./configs
COPY src/dependencies ./dependencies
COPY src/jobs ./jobs
COPY src/run.py ./run.py
COPY run.sh ./run.sh
COPY src/requirements.txt .

# install packages here
RUN set -e; \
  pip install --no-cache-dir -r requirements.txt;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Spark submit fails in k8s Cluster

Body:
I am trying to submit the Spark application to minikube k8s cluster (Spark Version used : 2.4.3) using below command:

spark-submit \
--master <K8S_MASTER> \
--deploy-mode cluster \
--conf spark.executor.instances=2 \
--conf spark.kubernetes.container.image=<my docker image> \
--conf spark.kubernetes.driver.pod.name=spark-py-driver \
--conf spark.executor.memory=2g \
--conf spark.driver.memory=2g \
local:///home/proj/app/run.py <arguments>

Please note that the python script run.py exists in my docker image in the same path
Once I do the Spark submit, the Spark job starts and the driver job gets killed. i could see only the below logs in the Driver pod

[FATAL tini (6)] exec driver-py failed: No such file or directory

I have verified the execution of pyspark job by doing a docker run on the docker image and is able to see that the above python code gets executed.

These are the events for the failed driver pod

Events:

  Type     Reason       Age   From               Message
  ----     ------       ----  ----               -------
  Normal   Scheduled    52m   default-scheduler  Successfully assigned ***-develop/run-py-1590847453453-driver to minikube
  Warning  FailedMount  52m   kubelet, minikube  MountVolume.SetUp failed for volume "spark-conf-volume" : configmap "run-py-1590847453453-driver-conf-map" not found
  Normal   Pulled       52m   kubelet, minikube  Container image "******************:latest" already present on machine
  Normal   Created      52m   kubelet, minikube  Created container spark-kubernetes-driver
  Normal   Started      52m   kubelet, minikube  Started container spark-kubernetes-driver

Body:
I am using one of the base images from my org.  But issue regarding the mount is only a Warning and the pod got successfully assigned after that.

FROM <project_repo>/<proj>/${SPARK_ALPINE_BUILD}
ENV SPARK_OPTS --driver-java-options=-Dlog4j.logLevel=info
ENV SPARK_MASTER "spark://spark-master:7077"

ADD https://repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar $SPARK_HOME/jars
ADD https://repo1.maven.org/maven2/com/datastax/spark/spark-cassandra-connector_2.11/2.3.2/spark-cassandra-connector_2.11-2.3.2.jar $SPARK_HOME/jars
USER root

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

WORKDIR /home/<proj>/app
# copy files
COPY src/configs ./configs
COPY src/dependencies ./dependencies
COPY src/jobs ./jobs
COPY src/run.py ./run.py
COPY run.sh ./run.sh
COPY src/requirements.txt .

# install packages here
RUN set -e; \
  pip install --no-cache-dir -r requirements.txt;


问:
are AutoIt string variables binary safe? can i store binary data there?
(SO won't let me post without a body even though the entire question is in the title)

are AutoIt string variables binary safe? can i safely store binary data in them? (unlike, say, Python or JavaScript string variables)

答:
testing suggest that yes, autoit string variables are binary safe, if you do

```<code>$test="";
for $i = 0 To 255
   $test = $test & Chr($i);
Next
ConsoleWrite(StringLen($test));
</code>```

the string will contain every byte, however some builtin functions are not binary safe, for example ConsoleWrite() will stop writing on the first null byte, so adding ConsoleWrite($test); will print absolutely nothing. i have requested a fix for that here https://www.autoitscript.com/trac/autoit/ticket/3764 , but in the meantime, here is a binary-safe implementation of ConsoleWrite:

```<code>; binary safe ConsoleWrite()  ( AutoIt's builtin ConsoleWrite() is not binary safe, it chokes if you try to write a null byte to stdout)
Func ConsoleWriteBinarySafe( Const ByRef $str)
   Local $bytesWritten=0;
   Local $stdoutHandle=_WinAPI_GetStdHandle(1);
   Local $tBuffer = DllStructCreate("byte[" & StringLen($str) & "]");
   DllStructSetData($tBuffer, 1, $str);
   _WinAPI_WriteFile ( $stdoutHandle, $tBuffer, StringLen($str), $bytesWritten);
   return $bytesWritten;
EndFunc
</code>```

Body:
testing suggest that yes, autoit string variables are binary safe, if you do

$test="";
for $i = 0 To 255
   $test = $test & Chr($i);
Next
ConsoleWrite(StringLen($test));

the string will contain every byte, however some builtin functions are not binary safe, for example ConsoleWrite() will stop writing on the first null byte, so adding ConsoleWrite($test); will print absolutely nothing. i have requested a fix for that here https://www.autoitscript.com/trac/autoit/ticket/3764 , but in the meantime, here is a binary-safe implementation of ConsoleWrite:

; binary safe ConsoleWrite()  ( AutoIt's builtin ConsoleWrite() is not binary safe, it chokes if you try to write a null byte to stdout)
Func ConsoleWriteBinarySafe( Const ByRef $str)
   Local $bytesWritten=0;
   Local $stdoutHandle=_WinAPI_GetStdHandle(1);
   Local $tBuffer = DllStructCreate("byte[" & StringLen($str) & "]");
   DllStructSetData($tBuffer, 1, $str);
   _WinAPI_WriteFile ( $stdoutHandle, $tBuffer, StringLen($str), $bytesWritten);
   return $bytesWritten;
EndFunc


问:
ModuleNotFoundError: No module named 'flask_sqlalchemy.orm'
In the CS50's Web Programming with Python and JavaScript 2018 course i got ModuleNotFoundError: No module named 'flask_sqlalchemy.orm' error. I tried to import scoped_session, sessionmaker. Any solution please?</p>

答: from sqlalchemy.orm import scoped_session, sessionmaker</p>


问:
check if number is in given range?
Given a number and a dictionary with min and max properties, return True if the number lies within the given range (inclusive).

Examples

```<code>is_in_range(4, { "min": 0, "max": 5 }) ➞ True
is_in_range(1, { "min": 4, "max": 5 }) ➞ False
</code>```

The below code is working for the int values of a number to be searched and dictionary values, but not for float values.

Examples

```<code>is_in_range(1.8, { "min": 1.25, "max": 1.75 }) ➞ False
</code>```

So far what I tried:

def is_in_range(n, r):
    for i in range(r['min'],r['max']+1):
        if i<=n:
            return True
        else:
            return False

    print(is_in_range(4, { "min": 6, "max": 10 }))
```

答:
You can try

```<code> def is_in_range(n, r):
     return r['min'] <= n <= r['max']

 print(is_in_range(4, { "min": 0, "max": 5 }))
 print(is_in_range(1, { "min": 4, "max": 5 }))
</code>```

Output

```<code>True
False
</code>```

Title: check if number is in given range?

Body:
Given a number and a dictionary with min and max properties, return True if the number lies within the given range (inclusive).

Examples

is_in_range(4, { "min": 0, "max": 5 }) ➞ True
is_in_range(1, { "min": 4, "max": 5 }) ➞ False

The below code is working for the int values of a number to be searched and dictionary values, but not for float values.

Examples

is_in_range(1.8, { "min": 1.25, "max": 1.75 }) ➞ False

So far what I tried:

def is_in_range(n, r):
    for i in range(r['min'],r['max']+1):
        if i<=n:
            return True
        else:
            return False

    print(is_in_range(4, { "min": 6, "max": 10 }))

Body:
You can try

 def is_in_range(n, r):
     return r['min'] <= n <= r['max']

 print(is_in_range(4, { "min": 0, "max": 5 }))
 print(is_in_range(1, { "min": 4, "max": 5 }))

Output

True
False


问:
Ping is not working on spine leaf topology on mininet
I am new in mininet and I want to know while I create spin leaf  DataCenter topology and visualiz the topology using RYU controller the ping is not working.
The Topology:

```<code>                       ____[S1]
[L1], [L2], [L3]------|
                      |----[S2]
</code>```

3 hosts are attached to each Leaf switch, and each leaf is connected to both Spine Switches. The hosts doesn't ping on each other.

答:
Probably you have some loop in the topo, so make sure to use RYU with STP protocol

The STP protocol can take some minutes (depends on the topology).
This is how I run Ryu with STP (I am using the python3 and OpenFlow 1.3, if you use a different version the path can be different)

```<code>ryu-manager /usr/lib/python3/dist-packages/ryu/app/simple_switch_stp_13.py --verbose
</code>```

Body:
I am new in mininet and I want to know while I create spin leaf  DataCenter topology and visualiz the topology using RYU controller the ping is not working.
The Topology:

                       ____[S1]
[L1], [L2], [L3]------|
                      |----[S2]

3 hosts are attached to each Leaf switch, and each leaf is connected to both Spine Switches. The hosts doesn't ping on each other.

Body:
Probably you have some loop in the topo, so make sure to use RYU with STP protocol

The STP protocol can take some minutes (depends on the topology).
This is how I run Ryu with STP (I am using the python3 and OpenFlow 1.3, if you use a different version the path can be different)

ryu-manager /usr/lib/python3/dist-packages/ryu/app/simple_switch_stp_13.py --verbose


问:
Undefined method 'task' using Rake 0.9.0
I just updated Rake to the latest version (0.9.0.beta.4) and the rake command ends up with the following error message:

```<code>rake aborted!
undefined method `task' for #<Anelis::Application:0x9223b6c>
</code>```

Here is the trace:

```<code>undefined method `task' for #<Anelis::Application:0x97ef80c>
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/application.rb:214:in `initialize_tasks'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/application.rb:139:in `load_tasks'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/application.rb:77:in `method_missing'
/home/amokrane/Documents/prog/web/learning_rails/anelis/Rakefile:7:in `load_string'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/environment.rb:28:in `eval'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/environment.rb:28:in `load_string'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/environment.rb:16:in `load_rakefile'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:495:in `raw_load_rakefile'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:78:in `block in load_rakefile'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:129:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:77:in `load_rakefile'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:61:in `block in run'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:129:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:59:in `run'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/bin/rake:31:in `<top (required)>'
/usr/local/rvm/gems/ruby-1.9.2-p136/bin/rake:19:in `load'
/usr/local/rvm/gems/ruby-1.9.2-p136/bin/rake:19:in `<main>'
</code>```

Anyone experienced the same issue? What could possibly be wrong? Note that I am running Rails 3.0.3, you may also be interested in the content of my Gemfile:

```<code>source 'http://rubygems.org'
gem 'rails', '3.0.3'
gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'mysql2'
gem 'legacy_data'
gem 'resources_controller', :git => 'git://github.com/ianwhite/resources_controller'
gem 'will_paginate', '3.0.pre' # pagination
gem 'jquery-rails', '>= 0.2.6'
gem "rmagick" # sudo aptitude install libmagick9-dev
gem "paperclip", "~> 2.3"
gem "nested_form", :git => "git://github.com/madebydna/nested_form.git"
gem "meta_search"
gem "hirb"
gem "devise"
gem "rails_admin", :git => "git://github.com/sferik/rails_admin.git"
</code>```

How can I fix this problem?

答: Rake 0.9.1 has just been released which reverses the change that caused this error but adds a deprecation warning: https://github.com/jimweirich/rake/commit/44aec3ceac085740bce0c385bccd65fc4d1d911c</p>

ContentLicense: CC BY-SA 3.0

Body:
I just updated Rake to the latest version (0.9.0.beta.4) and the rake command ends up with the following error message:

rake aborted!
undefined method `task' for #<Anelis::Application:0x9223b6c>

Here is the trace:

undefined method `task' for #<Anelis::Application:0x97ef80c>
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/application.rb:214:in `initialize_tasks'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/application.rb:139:in `load_tasks'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/application.rb:77:in `method_missing'
/home/amokrane/Documents/prog/web/learning_rails/anelis/Rakefile:7:in `load_string'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/environment.rb:28:in `eval'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/environment.rb:28:in `load_string'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/environment.rb:16:in `load_rakefile'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:495:in `raw_load_rakefile'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:78:in `block in load_rakefile'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:129:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:77:in `load_rakefile'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:61:in `block in run'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:129:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/lib/rake/application.rb:59:in `run'
/usr/local/rvm/gems/ruby-1.9.2-p136/gems/rake-0.9.0.beta.4/bin/rake:31:in `<top (required)>'
/usr/local/rvm/gems/ruby-1.9.2-p136/bin/rake:19:in `load'
/usr/local/rvm/gems/ruby-1.9.2-p136/bin/rake:19:in `'

Anyone experienced the same issue? What could possibly be wrong? Note that I am running Rails 3.0.3, you may also be interested in the content of my Gemfile:

source 'http://rubygems.org'
gem 'rails', '3.0.3'
gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'mysql2'
gem 'legacy_data'
gem 'resources_controller', :git => 'git://github.com/ianwhite/resources_controller'
gem 'will_paginate', '3.0.pre' # pagination
gem 'jquery-rails', '>= 0.2.6'
gem "rmagick" # sudo aptitude install libmagick9-dev
gem "paperclip", "~> 2.3"
gem "nested_form", :git => "git://github.com/madebydna/nested_form.git"
gem "meta_search"
gem "hirb"
gem "devise"
gem "rails_admin", :git => "git://github.com/sferik/rails_admin.git"

How can I fix this problem?


问:
Multiprocess Python: Working code of a tutorial doesn't work when I try it
I am watching the tutorial https://www.youtube.com/watch?v=fKl2JW_qrso (shown at 8.18 min) about multiprocessing. I am running the code copied from there:

```<code>import multiprocessing
import time
import os

start = time.perf_counter()

def do_something():

    print("sleeping 1 sec...")
    time.sleep(1)

    print("done sleeping...")

p1 = multiprocessing.Process(target=do_something)
p2 = multiprocessing.Process(target=do_something)

p1.start()
p2.start()

finish = time.perf_counter()

print("finished in " + str(round((finish-start),2))   + " seconds(s)")

os.system("pause")
</code>```

But when I run it on my computer I have the following error message (but the same code works on the tutorial):

An attempt has been made to start a new process before the
          current process has finished its bootstrapping phase. This probably means that you are not using fork to start your
          child processes and you have forgotten to use the proper idiom
          in the main module:
              if name == 'main':
                  freeze_support()
                  ...
          The "freeze_support()" line can be omitted if the program
          is not going to be frozen to produce an executable.

答:
Thanks for all your comments. Finally it works.
So basically in windows it needs to be written in a slightly different way:</p>

```<code>import multiprocessing
import time
import os

start = time.perf_counter()

def do_something():

    print("sleeping 1 sec...")
    time.sleep(1)

    print("done sleeping...")

if  __name__ == "__main__":
    p1 = multiprocessing.Process(target=do_something)
    p2 = multiprocessing.Process(target=do_something)

    p1.start()
    p2.start()

    p1.join()
    p2.join()

    finish = time.perf_counter()

    print("finished in " + str(round((finish-start),2))   + " seconds(s)")

    os.system("pause")
</code>```

Body:
I am watching the tutorial https://www.youtube.com/watch?v=fKl2JW_qrso (shown at 8.18 min) about multiprocessing. I am running the code copied from there:

import multiprocessing
import time
import os

start = time.perf_counter()

def do_something():

    print("sleeping 1 sec...")
    time.sleep(1)

    print("done sleeping...")

p1 = multiprocessing.Process(target=do_something)
p2 = multiprocessing.Process(target=do_something)

p1.start()
p2.start()

finish = time.perf_counter()

print("finished in " + str(round((finish-start),2))   + " seconds(s)")

os.system("pause")

But when I run it on my computer I have the following error message (but the same code works on the tutorial):

An attempt has been made to start a new process before the
          current process has finished its bootstrapping phase. This probably means that you are not using fork to start your
          child processes and you have forgotten to use the proper idiom
          in the main module:
              if name == 'main':
                  freeze_support()
                  ...
          The "freeze_support()" line can be omitted if the program
          is not going to be frozen to produce an executable.

Body:
Thanks for all your comments. Finally it works.
So basically in windows it needs to be written in a slightly different way:

import multiprocessing
import time
import os

start = time.perf_counter()

def do_something():

    print("sleeping 1 sec...")
    time.sleep(1)

    print("done sleeping...")

if  __name__ == "__main__":
    p1 = multiprocessing.Process(target=do_something)
    p2 = multiprocessing.Process(target=do_something)

    p1.start()
    p2.start()

    p1.join()
    p2.join()

    finish = time.perf_counter()

    print("finished in " + str(round((finish-start),2))   + " seconds(s)")

    os.system("pause")


问:
No matching distribution found for lal
I was trying to install module lal using pip in wsl. However, error messages popped out:

```<code>Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement lal (from versions: none)
ERROR: No matching distribution found for lal
</code>```

PS I am using python 2.7.17

答:
As discussed in the comments, the issue was that the original poster was trying to install lalsuite using pip install lal which isn't the right command. So, the solution is to use the right command which is:

```<code>pip install lalsuite
</code>```

Title: No matching distribution found for lal

Body:
I was trying to install module lal using pip in wsl. However, error messages popped out:

Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement lal (from versions: none)
ERROR: No matching distribution found for lal

PS I am using python 2.7.17

Body:
As discussed in the comments, the issue was that the original poster was trying to install lalsuite using pip install lal which isn't the right command. So, the solution is to use the right command which is:

pip install lalsuite


问:
function of `with` in `concurrent.futures`
The code below executes as expected by returning the total finish time as almost zero because it doesn't wait for the threads to finish every job.

```<code>import concurrent.futures
import time

start = time.perf_counter()

def do_something(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    return f'Done Sleeping...{seconds}'

executor= concurrent.futures.ThreadPoolExecutor()
secs = [10, 4, 3, 2, 1]

fs = [executor.submit(do_something, sec) for sec in secs]

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')
</code>```

But with the with command it does wait:

```<code>with concurrent.futures.ThreadPoolExecutor() as executor:
    secs = [10, 4, 3, 2, 1]

    fs = [executor.submit(do_something, sec) for sec in secs]
</code>```

Why? What is the reason that with has this behavior with multithreading?

答:
concurrent.futures is not well documented. When you create an executor it must be shutdown to terminate its threads or processes. That code will signal the threads to exit by pushing a None command to them and then wait for them to complete. In your first case, had you added executor.shutdown() you'd see the delay. It was there anyway - the program still took 10 seconds to exit.

The executor can be used as a context manager (it as __enter__ and __exit__ methods). When it exits the "with" block, __exit__ is called and it in turn does the shutdown call for you.

Body:
The code below executes as expected by returning the total finish time as almost zero because it doesn't wait for the threads to finish every job.

import concurrent.futures
import time

start = time.perf_counter()

def do_something(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    return f'Done Sleeping...{seconds}'

executor= concurrent.futures.ThreadPoolExecutor()
secs = [10, 4, 3, 2, 1]

fs = [executor.submit(do_something, sec) for sec in secs]

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')

But with the with command it does wait:

with concurrent.futures.ThreadPoolExecutor() as executor:
    secs = [10, 4, 3, 2, 1]

    fs = [executor.submit(do_something, sec) for sec in secs]

Why? What is the reason that with has this behavior with multithreading?


问:
Search string in between HTML tags and replace
Newbie here.   I have an HTML source code and would like to look for string in between header tags

,

till

 and then convert the text to lower case except acronyms or abbreviations (these are all capitals in 2 or more characters).   And make sure that all country names in between use proper case.

As an example: It will find
HR Policies and Procedures for Hiring - argentina LTD

It will convert it to:
HR policies and procedures for hiring - Argentina LTD

I've tried a user defined function for Excel VBA found online: CapIt(A2). It uses Search, Split and Join.   I'm not able to put them together to come up with the result.   Would appreciate very much your help.  Thank you.

Code I saw online as initial reference:

```<code>Function Capit(s As String)
Dim v As Variant, j As Long

v = Split(s, " ") ' separates the words
For j = LBound(v) To UBound(v)
     If StrComp(v(j), UCase(v(j)), vbBinaryCompare) <> 0 Then v(j) = StrConv(v(j), vbProperCase)
Next j

Capit = Join(v, " ") ' joins the words

End Function

'Added this code below, can we use the results to lowercase the string and exclude the output in this function

Function FindAcronyms(yourWord As String)
Dim I As Integer
Dim ctr As Integer

FindAcronyms = Null
For I = 1 To Len(yourWord)
    If Asc(Mid(yourWord, I, 1)) <= 90 And _
       Asc(Mid(yourWord, I, 1)) >= 65 Then
       If ctr > 0 Then
          FindAcronyms = FindAcronyms & Mid(yourWord, I - 1, 1)
       End If
       ctr = ctr + 1
    Else
       If ctr > 1 Then
          FindAcronyms = FindAcronyms & Mid(yourWord, I - 1, 1) & ", "
       End If
       ctr = 0
    End If
Next

If ctr > 1 Then
   FindAcronyms = FindAcronyms & Mid(yourWord, I - 1, 1)
End If

If Right(FindAcronyms, 2) = ", " Then
   FindAcronyms = Left(FindAcronyms, Len(FindAcronyms) - 2)
End If

End Function

'the final look would be something like this

Sub TitleChange()
'define array
myarray = Range("A1:A100")
' Define the pattern
Dim pattern As String: pattern = "<h*>*</h*>" 'looks for the header tags
Dim f As Variant

    For Each f In myarray
        If f Like pattern = True Then Capital (f) 'changes all string to lower case except countries (to retain proper case) and acronyms (to retain uppercase)
    Next f

End Sub
</code>```

答:
You can include the countries in an array</p>

```<code>Sub Test()
    Debug.Print Capital("HR Policies and Procedures for Hiring - argentina LTD")
End Sub

Function Capital(ByVal s As String)
    Dim a, v As Variant, j As Long
    a = Array("Argentina", "Egypt", "Enland")
    v = Split(s, " ")
    For j = LBound(v) To UBound(v)
        If StrComp(v(j), UCase(v(j)), vbBinaryCompare) <> 0 Then v(j) = StrConv(v(j), vbLowerCase)
        If Not IsError(Application.Match(v(j), a, 0)) Then v(j) = StrConv(v(j), vbProperCase)
    Next j
    Capital = Join(v, " ")
End Function
</code>```

Body:
Newbie here.   I have an HTML source code and would like to look for string in between header tags

,

till

 and then convert the text to lower case except acronyms or abbreviations (these are all capitals in 2 or more characters).   And make sure that all country names in between use proper case.

As an example: It will find
HR Policies and Procedures for Hiring - argentina LTD

It will convert it to:
HR policies and procedures for hiring - Argentina LTD

I've tried a user defined function for Excel VBA found online: CapIt(A2). It uses Search, Split and Join.   I'm not able to put them together to come up with the result.   Would appreciate very much your help.  Thank you.

Code I saw online as initial reference:

Function Capit(s As String)
Dim v As Variant, j As Long

v = Split(s, " ") ' separates the words
For j = LBound(v) To UBound(v)
     If StrComp(v(j), UCase(v(j)), vbBinaryCompare) <> 0 Then v(j) = StrConv(v(j), vbProperCase)
Next j

Capit = Join(v, " ") ' joins the words

End Function

'Added this code below, can we use the results to lowercase the string and exclude the output in this function

Function FindAcronyms(yourWord As String)
Dim I As Integer
Dim ctr As Integer

FindAcronyms = Null
For I = 1 To Len(yourWord)
    If Asc(Mid(yourWord, I, 1)) <= 90 And _
       Asc(Mid(yourWord, I, 1)) >= 65 Then
       If ctr > 0 Then
          FindAcronyms = FindAcronyms & Mid(yourWord, I - 1, 1)
       End If
       ctr = ctr + 1
    Else
       If ctr > 1 Then
          FindAcronyms = FindAcronyms & Mid(yourWord, I - 1, 1) & ", "
       End If
       ctr = 0
    End If
Next

If ctr > 1 Then
   FindAcronyms = FindAcronyms & Mid(yourWord, I - 1, 1)
End If

If Right(FindAcronyms, 2) = ", " Then
   FindAcronyms = Left(FindAcronyms, Len(FindAcronyms) - 2)
End If

End Function

'the final look would be something like this

Sub TitleChange()
'define array
myarray = Range("A1:A100")
' Define the pattern
Dim pattern As String: pattern = "<h*>*</h*>" 'looks for the header tags
Dim f As Variant

    For Each f In myarray
        If f Like pattern = True Then Capital (f) 'changes all string to lower case except countries (to retain proper case) and acronyms (to retain uppercase)
    Next f

End Sub

Body:
You can include the countries in an array

Sub Test()
    Debug.Print Capital("HR Policies and Procedures for Hiring - argentina LTD")
End Sub

Function Capital(ByVal s As String)
    Dim a, v As Variant, j As Long
    a = Array("Argentina", "Egypt", "Enland")
    v = Split(s, " ")
    For j = LBound(v) To UBound(v)
        If StrComp(v(j), UCase(v(j)), vbBinaryCompare) <> 0 Then v(j) = StrConv(v(j), vbLowerCase)
        If Not IsError(Application.Match(v(j), a, 0)) Then v(j) = StrConv(v(j), vbProperCase)
    Next j
    Capital = Join(v, " ")
End Function


问:
Has anyone come accross the term 'friendly user testing' in software dev?
Reading a document and the term is in the context "...after several weeks of friendly user testing ..."? </p>

答:
A friendly user test (FUT) is a user test of software carried out by people outside the development team, but known to the organization that performs the test.

A FUT is a person agreeing to test and detect bugs in an application or software in a version being deployed (not finalized) and before generalization. The voluntary user of the new service agrees to collect valuable information from developers. The inconveniences generated are transformed into active participation in the resolution of the faults encountered.

ContentLicense: CC BY-SA 2.5


问:
Why my function secondMethod is not a function TypeError: (...).secondMethod is not a function
I am try to make a chainable instance for a personal project, and I try this simple example with some modifications, but I got a error:

```<code>TypeError: chainableInstance.firstMethod(...).secondMethod is not a function
    at Object.<anonymous> (/Users/rodger/Developer/Projects/Personal/unknown/src/teste.js:48:33)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
</code>```

And my code is this:

```<code>  otherMethod(a) {
    return (this.a = a.replace('!e', 'e'));
  }
}
class Another extends Other {
  constructor() {
    super();
  }

  anotherMethod(a) {
    console.log('This is anohter method');
    return (this.a = a.replace('!d', 'd !e'));
  }

  otherMethod() {
    return super.otherMethod(this.a);
  }
}

class ChainAble extends Another {
  constructor() {
    super();
  }

  firstMethod() {
    return (this.a = 'a !b');
  }

  secondMethod() {
    return this.a.replace('!b', 'b !c');
  }

  thirdMethod() {
    return this.a.replace('!c', 'c !d');
  }
  anotherMethod() {
    return super.anotherMethod(this.a);
  }
}

const chainableInstance = new ChainAble();
chainableInstance.firstMethod().secondMethod().thirdMethod().anotherMethod();

console.log(chainableInstance);
</code>```

I just not undestand why my secondMethod is It is considered "not a function", have someone to see what I am wrong in this stuff?

答: It's because firstMethod returns the string 'a !b' (the result of assignment). You need to return directly this from any methods that need to be chainable

Body:
I am try to make a chainable instance for a personal project, and I try this simple example with some modifications, but I got a error:

TypeError: chainableInstance.firstMethod(...).secondMethod is not a function
    at Object.<anonymous> (/Users/rodger/Developer/Projects/Personal/unknown/src/teste.js:48:33)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

And my code is this:

  otherMethod(a) {
    return (this.a = a.replace('!e', 'e'));
  }
}
class Another extends Other {
  constructor() {
    super();
  }

  anotherMethod(a) {
    console.log('This is anohter method');
    return (this.a = a.replace('!d', 'd !e'));
  }

  otherMethod() {
    return super.otherMethod(this.a);
  }
}

class ChainAble extends Another {
  constructor() {
    super();
  }

  firstMethod() {
    return (this.a = 'a !b');
  }

  secondMethod() {
    return this.a.replace('!b', 'b !c');
  }

  thirdMethod() {
    return this.a.replace('!c', 'c !d');
  }
  anotherMethod() {
    return super.anotherMethod(this.a);
  }
}

const chainableInstance = new ChainAble();
chainableInstance.firstMethod().secondMethod().thirdMethod().anotherMethod();

console.log(chainableInstance);

I just not undestand why my secondMethod is It is considered "not a function", have someone to see what I am wrong in this stuff?


问:
Defining for loop iterator before the for loop?
Recently I'd been criticized for structuring my for loops like so:

```<code>var i:MovieClip;
for each(i in array)
{
    // be awesome
}
</code>```

Or,

```<code>var i:uint = 0;
for(i; i<10; i++)
{
    // be more awesome
}
</code>```

This reads better for me personally, yet I'm being attacked for it. Is there any difference?

答:
trutheality's answer is the best consideration in most languages, and a great response considering that this question wasn't tagged actionscript-3 until later.

However Actionscript uses variable hoisting where variables defined anywhere in the function are scoped to that function rather than its inner most block. This blog post describes it well, and it's mentioned in the docs on variable scope. Due to hoisting, there is no difference in Actionscript between defining the variables before or inside the loop.

To show how crazy this can get, you can even define the variable after the loop:

```<code>for (i = 0; i < 5; i++) {
  trace(i);
}
var i:int;
</code>```

Body:
Recently I'd been criticized for structuring my for loops like so:

var i:MovieClip;
for each(i in array)
{
    // be awesome
}

Or,

var i:uint = 0;
for(i; i<10; i++)
{
    // be more awesome
}

This reads better for me personally, yet I'm being attacked for it. Is there any difference?

Body:
trutheality's answer is the best consideration in most languages, and a great response considering that this question wasn't tagged actionscript-3 until later.

However Actionscript uses variable hoisting where variables defined anywhere in the function are scoped to that function rather than its inner most block. This blog post describes it well, and it's mentioned in the docs on variable scope. Due to hoisting, there is no difference in Actionscript between defining the variables before or inside the loop.

To show how crazy this can get, you can even define the variable after the loop:

for (i = 0; i < 5; i++) {
  trace(i);
}
var i:int;


问:
JAVA Method returns unexpected value
I am a very new java programmer, the below code is my first attempt at my own project.  I'm certain the code is a mess, please forgive me.

In the below code the user is prompted to enter 5 values between 1 and 50.
I am placing the input values into an int[].
I want to verify that the numbers are in range so I pass the value to a method.
MY ISSUE:
If the value is in range it gets returned then the for loop increments to repeat - Good Behavior
If an invalid value is entered the check is done, error message is displayed and the user is prompted to reenter a proper value.
If one invalid entry is made and a proper value is entered on the second attempt, a correct value is returned - Good Behavior
If two invalid entries are made the second invalid entry somehow gets passed back to the for loop and gets added to array - BAD Behavior

I am certain there is something simple I am missing.

```<code>public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("you get 5 elements between 01 & 50:");
    int a[] = new int[5];
    System.out.println("\nEnter all the elements:");
    for(int i = 0; i < 5;)
    {
        int b = in.nextInt();
        a[i] = checkNum(b);
        i++;
    }
    System.out.println("Numbers:" + Arrays.toString(a));
    in.close();
}

static int checkNum(int z) {
    Scanner s = new Scanner(System.in);
    if (z>0 && z<51) {
        return z;
    } else {
        System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
        int qz = s.nextInt();
        z = qz;
        checkNum(qz);
    }
    return z;
}
</code>```

答:
The problem resides in your checkNum(), you are using recursion here, I don't think you know this (if you do that's great).

You need to return the checkNum(qz) value, I have simplified your logic a bit.

```<code>static int checkNum(int z) {
    if (z<1 || z>50) // check for false value
    {
        System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
        Scanner s = new Scanner(System.in);
        return checkNum(s.nextInt());
    }
    return z;
}
</code>```

Title: JAVA Method returns unexpected value

Body:
I am a very new java programmer, the below code is my first attempt at my own project.  I'm certain the code is a mess, please forgive me.

In the below code the user is prompted to enter 5 values between 1 and 50.
I am placing the input values into an int[].
I want to verify that the numbers are in range so I pass the value to a method.
MY ISSUE:
If the value is in range it gets returned then the for loop increments to repeat - Good Behavior
If an invalid value is entered the check is done, error message is displayed and the user is prompted to reenter a proper value.
If one invalid entry is made and a proper value is entered on the second attempt, a correct value is returned - Good Behavior
If two invalid entries are made the second invalid entry somehow gets passed back to the for loop and gets added to array - BAD Behavior

I am certain there is something simple I am missing.

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("you get 5 elements between 01 & 50:");
    int a[] = new int[5];
    System.out.println("\nEnter all the elements:");
    for(int i = 0; i < 5;)
    {
        int b = in.nextInt();
        a[i] = checkNum(b);
        i++;
    }
    System.out.println("Numbers:" + Arrays.toString(a));
    in.close();
}

static int checkNum(int z) {
    Scanner s = new Scanner(System.in);
    if (z>0 && z<51) {
        return z;
    } else {
        System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
        int qz = s.nextInt();
        z = qz;
        checkNum(qz);
    }
    return z;
}

Body:
The problem resides in your checkNum(), you are using recursion here, I don't think you know this (if you do that's great).

You need to return the checkNum(qz) value, I have simplified your logic a bit.

static int checkNum(int z) {
    if (z<1 || z>50) // check for false value
    {
        System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
        Scanner s = new Scanner(System.in);
        return checkNum(s.nextInt());
    }
    return z;
}


问:
Append value to line in input file based on column number
I have a function append_val_to_line which appends the $append_val to the line in Input.txt and writes it back. I want to insert 45 at column 1 and it should and since its length is two values, it should at it at column 1 and column 0. But my code below is adding it at column 2 and column 3.

I am not sure why it is so. Can someone help me achieve the goal mentioned above?

My working solution is below but it does not add the 45 at column 0 and 1. I want a generic solution as I can insert the value at any column and the value should be added starting at column N to column N-1 ... N-2 based on the length of the append_val.

As you can see in the sample input before and sample input after the call to append_val_to_line function, the value 45 is added at column 1 and column 2 but I wanted to the from column 0 and end on column 1 as the value 45 is of length two. But my code adds it starting at column 2 and 3 instead.

Space is also a valid column number but I will not be adding any values in those spaces in a line.

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

function append_val_to_line{
    sed -i 's/\(.\{'$1'\}\)/\1'$2'/' "input.txt"
}

column_num=1
append_val=45

append_vals_to_line "$column_num" "$append_val"
</code>```

Input.txt BEFORE call to function append_vals_to_line

```<code>1200    5600   775000   34555
</code>```

Input.txt AFTER call to function append_vals_to_line

```<code>145200    5600   775000   34555
</code>```

Note 45 has been added at column 2 and 3.

答:
Since OP told OP wants to start character's position from 0 and I believe rather than column its character's position number which we are talking about here, so based on that and shown samples following may help then.

```<code>awk -v after="0" -v value="45" '{print substr($0,1,after+1) value substr($0,after+2)}' Input_file
</code>```

Non one liner form of above:

```<code>awk -v after="0" -v value="45" '
{
  print substr($0,1,after+1) value substr($0,after+2)
}
'  Input_file
</code>```

Explanation: Adding detailed explanation for above one.

```<code>awk -v after="0" -v value="45" '                          ##Start awk prorgam from heer and setting after variable to 0 a per OP and value to 45.
{
  print substr($0,1,after+1) value substr($0,after+2)     ##Printing sub-string from 1 to till after+1 value since OP wants to insert value to 2nd character so printing 1st character here. Then I a printing value here, then printing rest of the current Line.
}
'  Input_file                                             ##Mentioning Input_file name here.
</code>```

Body:
I have a function append_val_to_line which appends the $append_val to the line in Input.txt and writes it back. I want to insert 45 at column 1 and it should and since its length is two values, it should at it at column 1 and column 0. But my code below is adding it at column 2 and column 3.

I am not sure why it is so. Can someone help me achieve the goal mentioned above?

My working solution is below but it does not add the 45 at column 0 and 1. I want a generic solution as I can insert the value at any column and the value should be added starting at column N to column N-1 ... N-2 based on the length of the append_val.

As you can see in the sample input before and sample input after the call to append_val_to_line function, the value 45 is added at column 1 and column 2 but I wanted to the from column 0 and end on column 1 as the value 45 is of length two. But my code adds it starting at column 2 and 3 instead.

Space is also a valid column number but I will not be adding any values in those spaces in a line.

#! /bin/bash

function append_val_to_line{
    sed -i 's/\(.\{'$1'\}\)/\1'$2'/' "input.txt"
}

column_num=1
append_val=45

append_vals_to_line "$column_num" "$append_val"

Input.txt BEFORE call to function append_vals_to_line

1200    5600   775000   34555

Input.txt AFTER call to function append_vals_to_line

145200    5600   775000   34555

Note 45 has been added at column 2 and 3.

Body:
Since OP told OP wants to start character's position from 0 and I believe rather than column its character's position number which we are talking about here, so based on that and shown samples following may help then.

awk -v after="0" -v value="45" '{print substr($0,1,after+1) value substr($0,after+2)}' Input_file

Non one liner form of above:

awk -v after="0" -v value="45" '
{
  print substr($0,1,after+1) value substr($0,after+2)
}
'  Input_file

Explanation: Adding detailed explanation for above one.

awk -v after="0" -v value="45" '                          ##Start awk prorgam from heer and setting after variable to 0 a per OP and value to 45.
{
  print substr($0,1,after+1) value substr($0,after+2)     ##Printing sub-string from 1 to till after+1 value since OP wants to insert value to 2nd character so printing 1st character here. Then I a printing value here, then printing rest of the current Line.
}
'  Input_file                                             ##Mentioning Input_file name here.


问:
Is it possible to get json values as list from array of json in Postgres?
I use Postgresql 10 and suppose, that I have the following table:

```<code>CREATE TABLE test_table(id int8 NOT NULL, data jsonb);
</code>```

And inserted such values:

```<code>insert into test_table(id, data)
values (1, '{"external": [{"internal_1": "value_1", "internal_2": "some_value"}]}'),
       (2, '{"external": [{"internal_1": "value_2", "internal_2": "another_value"}]}'),
       (3, '{"external": [{"internal_1": "value_1", "internal_2": "other_value"}]}');
</code>```

The table after all:

```<code>id|                                data                                     |
--|-------------------------------------------------------------------------|
1 |{"external": [{"internal_1": "value_1", "internal_2": "some_value"}]}    |
2 |{"external": [{"internal_1": "value_2", "internal_2": "another_value"}]} |
3 |{"external": [{"internal_1": "value_1", "internal_2": "other_value"}]}   |
</code>```

The problem is that I need to have all internal values as an array

I tried the following query:

```<code>select data -> 'external'
from test_table;
</code>```

and the result is:

```<code>?column?                                                         |
-----------------------------------------------------------------|
[{"internal_1": "value_1", "internal_2": "some_value"}]          |
[{"internal_1": "value_2", "internal_2": "another_value"}]       |
[{"internal_1": "value_1", "internal_2": "other_value"}]         |
</code>```

But finally I need to have internal values as text array for each table row. Something like that:

```<code>?column?                       |
-------------------------------|
[value_1, some_value]          |
[value_2, another_value]       |
[value_1, other_value]         |
</code>```

Is it possible to write such query using postgres json functions and operators?

UPD!!
Number of internal keys could be different (internal_1, ..., internal_n) and we don’t know in advance names of keys (in my case they are: internal_1 and internal_2)

答:
The following query should to what you want:

```<code>select json_build_array(data#>>'{external,0, internal_1}', data#>>'{external,0, internal_2}')
from test_table;
</code>```

The idea is to use the json_build_array function to create an array and them you need to select each element that will be part of it, a convenient way to do it is by using the #>'{json_path}' so you select the elements using a json path.

Source: https://www.postgresql.org/docs/10/functions-json.html

SQLFiddle to test it: http://sqlfiddle.com/#!17/5c4d2/19

Body:
I use Postgresql 10 and suppose, that I have the following table:

CREATE TABLE test_table(id int8 NOT NULL, data jsonb);

And inserted such values:

insert into test_table(id, data)
values (1, '{"external": [{"internal_1": "value_1", "internal_2": "some_value"}]}'),
       (2, '{"external": [{"internal_1": "value_2", "internal_2": "another_value"}]}'),
       (3, '{"external": [{"internal_1": "value_1", "internal_2": "other_value"}]}');

The table after all:

id|                                data                                     |
--|-------------------------------------------------------------------------|
1 |{"external": [{"internal_1": "value_1", "internal_2": "some_value"}]}    |
2 |{"external": [{"internal_1": "value_2", "internal_2": "another_value"}]} |
3 |{"external": [{"internal_1": "value_1", "internal_2": "other_value"}]}   |

The problem is that I need to have all internal values as an array

I tried the following query:

select data -> 'external'
from test_table;

and the result is:

?column?                                                         |
-----------------------------------------------------------------|
[{"internal_1": "value_1", "internal_2": "some_value"}]          |
[{"internal_1": "value_2", "internal_2": "another_value"}]       |
[{"internal_1": "value_1", "internal_2": "other_value"}]         |

But finally I need to have internal values as text array for each table row. Something like that:

?column?                       |
-------------------------------|
[value_1, some_value]          |
[value_2, another_value]       |
[value_1, other_value]         |

Is it possible to write such query using postgres json functions and operators?

UPD!!
Number of internal keys could be different (internal_1, ..., internal_n) and we don’t know in advance names of keys (in my case they are: internal_1 and internal_2)

Body:
The following query should to what you want:

select json_build_array(data#>>'{external,0, internal_1}', data#>>'{external,0, internal_2}')
from test_table;

The idea is to use the json_build_array function to create an array and them you need to select each element that will be part of it, a convenient way to do it is by using the #>'{json_path}' so you select the elements using a json path.

Source: https://www.postgresql.org/docs/10/functions-json.html

SQLFiddle to test it: http://sqlfiddle.com/#!17/5c4d2/19


问:
The sum of integers
I would like to print the sum of all integers from a to b containing both. So far I have stopped at this:

```<code>import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int j = b-a;
        int total = 0;
        for(int i = 0; i<=j ; i++){
            total+=i;
        }
        System.out.println(total);
    }
}
</code>```

What I am doing wrong?

答:
Is this what you want?

```<code>    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int total = 0;
        for(int i = a; i<=b ; i++){
            total+=i;
        }
        System.out.println(total);
    }
</code>```

Of course this works only if a < b

Title: The sum of integers

Body:
I would like to print the sum of all integers from a to b containing both. So far I have stopped at this:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int j = b-a;
        int total = 0;
        for(int i = 0; i<=j ; i++){
            total+=i;
        }
        System.out.println(total);
    }
}

What I am doing wrong?

Body:
Is this what you want?

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int total = 0;
        for(int i = a; i<=b ; i++){
            total+=i;
        }
        System.out.println(total);
    }

Of course this works only if a < b


问:
Laravel complex Eloquent Relationship
I am developing chatting using Laravel

model ChattingRoom has these attribute :

```<code>$table->uuid('room_uuid');
$table->integer('user_id');
</code>```

There are items like

```<code>room_uuid, user_id
r1, 1
r1, 2
r2, 1
r2, 2
r2, 3
r3, 2
r3, 3
</code>```

room r1 has user 1,2.

room r2 has user 1,2,3.

room r3 has user 2,3.

i want to get room_uuid that has user 1 and 2.
Also I want to get room_uuid that has user 1,2,3.

I made query as following

```<code>with step0 as (
select room_uuid,0 as cnt
from chatting_rooms
where user_id = 1),
 step1 as (
     select room_uuid, 0 as cnt
     from chatting_rooms
     where user_id = 2
 ),
step2 as (
    select room_uuid, count(room_uuid) as cnt from chatting_rooms group by room_uuid having cnt =2
)
select step0.room_uuid
from step0,
    step1,
    step2
where step0.room_uuid = step1.room_uuid and step2.room_uuid = step0.room_uuid;
</code>```

I want to use ChattingRoom model as following

ChattingRoom::getRoomUuid([1,2])

then it returns r1

ChattingRoom::getRoomUuid([1,2,3])

then it returns r2

Thanks

答:
you can use whereIn ...
$values=[1,2]'

```<code>    $room_uuid1=ChattingRoom::whereIn('user_id',$values)
->groupBy('chatting_rooms.user_id')
    ->having(DB::raw('count(*)'), '=', count($values))
->select('room_uuid')->get();
</code>```

more details about whereIn in:

https://laravel.com/docs/7.x/queries#where-clauses

also:

https://stackoverflow.com/a/45592687/10573560

Title: Laravel complex Eloquent Relationship

Body:
I am developing chatting using Laravel

model ChattingRoom has these attribute :

$table->uuid('room_uuid');
$table->integer('user_id');

There are items like

room_uuid, user_id
r1, 1
r1, 2
r2, 1
r2, 2
r2, 3
r3, 2
r3, 3

room r1 has user 1,2.

room r2 has user 1,2,3.

room r3 has user 2,3.

i want to get room_uuid that has user 1 and 2.
Also I want to get room_uuid that has user 1,2,3.

I made query as following

with step0 as (
select room_uuid,0 as cnt
from chatting_rooms
where user_id = 1),
 step1 as (
     select room_uuid, 0 as cnt
     from chatting_rooms
     where user_id = 2
 ),
step2 as (
    select room_uuid, count(room_uuid) as cnt from chatting_rooms group by room_uuid having cnt =2
)
select step0.room_uuid
from step0,
    step1,
    step2
where step0.room_uuid = step1.room_uuid and step2.room_uuid = step0.room_uuid;

I want to use ChattingRoom model as following

ChattingRoom::getRoomUuid([1,2])

then it returns r1

ChattingRoom::getRoomUuid([1,2,3])

then it returns r2

Thanks

Body:
you can use whereIn ...
$values=[1,2]'

    $room_uuid1=ChattingRoom::whereIn('user_id',$values)
->groupBy('chatting_rooms.user_id')
    ->having(DB::raw('count(*)'), '=', count($values))
->select('room_uuid')->get();

more details about whereIn in:

https://laravel.com/docs/7.x/queries#where-clauses

also:

https://stackoverflow.com/a/45592687/10573560


问:
Clarification regarding BraTS dataset
I downloaded the BraTS dataset for my summer project.

The dataset consisted of nii.gz files which I was able to open using nibabel library in Python.
I used the following code:

```<code>import os
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plat
examplefile=os.path.join("mydatapath","BraTS19_2013_5_1_flair.nii.gz")
img=nib.load(examplefile)
print(img)
</code>```

this gave me the following output:

```<code><class 'nibabel.nifti1.Nifti1Image'>
data shape (240, 240, 155)
affine:
[[ -1.   0.   0.  -0.]
 [  0.  -1.   0. 239.]
 [  0.   0.   1.   0.]
 [  0.   0.   0.   1.]]
metadata:
<class 'nibabel.nifti1.Nifti1Header'> object, endian='<'
sizeof_hdr      : 348
data_type       : b''
db_name         : b''
extents         : 0
session_error   : 0
regular         : b'r'
dim_info        : 0
dim             : [  3 240 240 155   1   1   1   1]
intent_p1       : 0.0
intent_p2       : 0.0
intent_p3       : 0.0
intent_code     : none
datatype        : int16
bitpix          : 16
slice_start     : 0
pixdim          : [1. 1. 1. 1. 0. 0. 0. 0.]
vox_offset      : 0.0
scl_slope       : nan
scl_inter       : nan
slice_end       : 0
slice_code      : unknown
xyzt_units      : 2
cal_max         : 0.0
cal_min         : 0.0
slice_duration  : 0.0
toffset         : 0.0
glmax           : 0
glmin           : 0
descrip         : b''
aux_file        : b''
qform_code      : aligned
sform_code      : scanner
quatern_b       : 0.0
quatern_c       : 0.0
quatern_d       : 1.0
qoffset_x       : -0.0
qoffset_y       : 239.0
qoffset_z       : 0.0
srow_x          : [-1.  0.  0. -0.]
srow_y          : [  0.  -1.   0. 239.]
srow_z          : [0. 0. 1. 0.]
intent_name     : b''
magic           : b'n+1'
</code>```

Can someone please walk me through this.
I know it's a lot of data if someone could just tell me how to get the image from this data it would be wonderful.

Thank You.

答:
Have you looked at nibabel's documentation? It's excellent and has the answer to your question. https://nipy.org/nibabel/gettingstarted.html

In your question, you are looking at the header of the Nifti file. Use the following to get the image data as a numpy array.

```<code>import nibabel as nib
img = nib.load("image.nii.gz")
data = img.get_fdata()
</code>```

Title: Clarification regarding BraTS dataset

Body:
I downloaded the BraTS dataset for my summer project.

The dataset consisted of nii.gz files which I was able to open using nibabel library in Python.
I used the following code:

import os
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plat
examplefile=os.path.join("mydatapath","BraTS19_2013_5_1_flair.nii.gz")
img=nib.load(examplefile)
print(img)

this gave me the following output:

<class 'nibabel.nifti1.Nifti1Image'>
data shape (240, 240, 155)
affine:
[[ -1.   0.   0.  -0.]
 [  0.  -1.   0. 239.]
 [  0.   0.   1.   0.]
 [  0.   0.   0.   1.]]
metadata:
<class 'nibabel.nifti1.Nifti1Header'> object, endian='<'
sizeof_hdr      : 348
data_type       : b''
db_name         : b''
extents         : 0
session_error   : 0
regular         : b'r'
dim_info        : 0
dim             : [  3 240 240 155   1   1   1   1]
intent_p1       : 0.0
intent_p2       : 0.0
intent_p3       : 0.0
intent_code     : none
datatype        : int16
bitpix          : 16
slice_start     : 0
pixdim          : [1. 1. 1. 1. 0. 0. 0. 0.]
vox_offset      : 0.0
scl_slope       : nan
scl_inter       : nan
slice_end       : 0
slice_code      : unknown
xyzt_units      : 2
cal_max         : 0.0
cal_min         : 0.0
slice_duration  : 0.0
toffset         : 0.0
glmax           : 0
glmin           : 0
descrip         : b''
aux_file        : b''
qform_code      : aligned
sform_code      : scanner
quatern_b       : 0.0
quatern_c       : 0.0
quatern_d       : 1.0
qoffset_x       : -0.0
qoffset_y       : 239.0
qoffset_z       : 0.0
srow_x          : [-1.  0.  0. -0.]
srow_y          : [  0.  -1.   0. 239.]
srow_z          : [0. 0. 1. 0.]
intent_name     : b''
magic           : b'n+1'

Can someone please walk me through this.
I know it's a lot of data if someone could just tell me how to get the image from this data it would be wonderful.

Thank You.

Body:
Have you looked at nibabel's documentation? It's excellent and has the answer to your question. https://nipy.org/nibabel/gettingstarted.html

In your question, you are looking at the header of the Nifti file. Use the following to get the image data as a numpy array.

import nibabel as nib
img = nib.load("image.nii.gz")
data = img.get_fdata()


问:
Deleting last linked list
I can't seem to get rid of an extra linked list. I know there are many ways to do it, but i just want to a simple way of freeing it because it was created as an extra in my loop. here's the code:</p>

```<code>    current = first = malloc (sizeof (NODE));
    while( fscanf( fin, "%s", current -> seq) != EOF) {
            for (i = 0; i < 300; i++){
                    if (current->seq[i] == 'a')
                            current->seq[i] = 'A';
                    else if (current->seq[i] == 't')
                            current->seq[i] = 'T';
                    else if(current->seq[i] == 'g')
                            current->seq[i] = 'G';
                    else if(current->seq[i] == 'c')
                            current->seq[i] = 'C';
            }
            if ( (current -> next = malloc ( sizeof(NODE) ) ) == NULL){
                    fprintf(fout, "Out of memory\nCan't add more DNA sequences\n");
                    return EXIT_FAILURE;
            }
            current = current -> next;
    }
</code>```

答:
One way is to never create the extra node in the first place.  Read from the file into a temp variable, and don't create the next node until you know you need it.</p>

```<code>NODE* first;
NODE** ppCurrent = &first;

while( fscanf( fin, "%s", temp) != EOF)
{
    if ((*ppCurrent = malloc(sizeof(NODE))) == NULL)
    {
        fprintf(fout, "Out of memory\nCan't add more DNA sequences\n");
        return EXIT_FAILURE;
    }

    for (i = 0; i < 300; i++)
        temp[i] = toupper(temp[i]);

    (*ppCurrent)->seq = temp;
    ppCurrent = &((*ppCurrent)->next);
}
</code>```

Title: Deleting last linked list

Body:
I can't seem to get rid of an extra linked list. I know there are many ways to do it, but i just want to a simple way of freeing it because it was created as an extra in my loop. here's the code:

    current = first = malloc (sizeof (NODE));
    while( fscanf( fin, "%s", current -> seq) != EOF) {
            for (i = 0; i < 300; i++){
                    if (current->seq[i] == 'a')
                            current->seq[i] = 'A';
                    else if (current->seq[i] == 't')
                            current->seq[i] = 'T';
                    else if(current->seq[i] == 'g')
                            current->seq[i] = 'G';
                    else if(current->seq[i] == 'c')
                            current->seq[i] = 'C';
            }
            if ( (current -> next = malloc ( sizeof(NODE) ) ) == NULL){
                    fprintf(fout, "Out of memory\nCan't add more DNA sequences\n");
                    return EXIT_FAILURE;
            }
            current = current -> next;
    }

Body:
One way is to never create the extra node in the first place.  Read from the file into a temp variable, and don't create the next node until you know you need it.

NODE* first;
NODE** ppCurrent = &first;

while( fscanf( fin, "%s", temp) != EOF)
{
    if ((*ppCurrent = malloc(sizeof(NODE))) == NULL)
    {
        fprintf(fout, "Out of memory\nCan't add more DNA sequences\n");
        return EXIT_FAILURE;
    }

    for (i = 0; i < 300; i++)
        temp[i] = toupper(temp[i]);

    (*ppCurrent)->seq = temp;
    ppCurrent = &((*ppCurrent)->next);
}


问:
Not making a table in Laravel 7
I have tried different ways to solve this problem, but none of them have solved the problem.This part of the code is for building a relationship in Laravel, but this code works in Laravel 5 but is error-prone in Laravel 7.

Error:
SQLSTATE[HY000]: General error: 1005 Can't create table shoplaravel.role_user (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table role_user add constraint role_user_role_id_foreign foreign key (role_id) references roles (id) on delete cascade on update cascade)

```<code>    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });
    Schema::create('permissions', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });

    Schema::create('role_user', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id');
        $table->unsignedBigInteger('user_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->primary(['role_id', 'user_id']);
    });
    Schema::create('permission_role', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id');
        $table->unsignedBigInteger('permission_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('permission_id')
            ->references('id')
            ->on('permissions')
            ->onDelete('cascade')
            ->onUpdate('cascade');
        $table->primary(['permission_id', 'role_id']);
    });
</code>```

答:
Remove BigInteger and use only unsignedInteger

```<code>Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });
    Schema::create('permissions', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });

    Schema::create('role_user', function (Blueprint $table) {
        $table->unsignedInteger('role_id');
        $table->unsignedInteger('user_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->primary(['role_id', 'user_id']);
    });
    Schema::create('permission_role', function (Blueprint $table) {
        $table->unsignedInteger('role_id');
        $table->unsignedInteger('permission_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('permission_id')
            ->references('id')
            ->on('permissions')
            ->onDelete('cascade')
            ->onUpdate('cascade');
        $table->primary(['permission_id', 'role_id']);
    });
</code>```

Title: Not making a table in Laravel 7

Body:
I have tried different ways to solve this problem, but none of them have solved the problem.This part of the code is for building a relationship in Laravel, but this code works in Laravel 5 but is error-prone in Laravel 7.

Error:
SQLSTATE[HY000]: General error: 1005 Can't create table shoplaravel.role_user (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table role_user add constraint role_user_role_id_foreign foreign key (role_id) references roles (id) on delete cascade on update cascade)

    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });
    Schema::create('permissions', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });

    Schema::create('role_user', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id');
        $table->unsignedBigInteger('user_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->primary(['role_id', 'user_id']);
    });
    Schema::create('permission_role', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id');
        $table->unsignedBigInteger('permission_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('permission_id')
            ->references('id')
            ->on('permissions')
            ->onDelete('cascade')
            ->onUpdate('cascade');
        $table->primary(['permission_id', 'role_id']);
    });

Body:
Remove BigInteger and use only unsignedInteger

Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });
    Schema::create('permissions', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });

    Schema::create('role_user', function (Blueprint $table) {
        $table->unsignedInteger('role_id');
        $table->unsignedInteger('user_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->primary(['role_id', 'user_id']);
    });
    Schema::create('permission_role', function (Blueprint $table) {
        $table->unsignedInteger('role_id');
        $table->unsignedInteger('permission_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('permission_id')
            ->references('id')
            ->on('permissions')
            ->onDelete('cascade')
            ->onUpdate('cascade');
        $table->primary(['permission_id', 'role_id']);
    });


问:
terraform copy/upload files to aws ec2 instance
We have cronjob and shell script which we want to copy or upload to aws ec2 instance while creating instance using terraform.

we tried

file provisioner :
but its not wokring , and read this option does not work with all terraform version

```<code>      provisioner "file" {
        source      = "abc.sh"
        destination = "/home/ec2-user/basic2.sh"
      }
</code>```

tried data template file option

```<code>    data "template_file" "userdata_line" {
      template = <<EOF
    #!/bin/bash
    mkdir /home/ec2-user/files2
    cd /home/ec2-user/files2
    sudo touch basic2.sh
    sudo chmod 777 basic2.sh
    base64 basic.sh |base64 -d >basic2.sh
    EOF
    }
</code>```

tried all option but none of them working.

could u please help or advise .

I am new to terraform so struggling on this from long time.

答:
When starting from an AMI that has cloud-init installed (which is common in many official Linux distri), we can use cloud-init's write_files module to place arbitrary files into the filesystem, as long as they are small enough to fit within the constraints of the user_data argument along with all of the other cloud-init data.

As with all cloud-init modules, we configure write_files using cloud-init's YAML-based configuration format, which begins with the special marker string #cloud-config on a line of its own, followed by a YAML data structure. Because JSON is a subset of YAML, we can use Terraform's jsonencode to produce a valid value[1].

```<code>locals {
  cloud_config_config = <<-END
    #cloud-config
    ${jsonencode({
      write_files = [
        {
          path        = "/etc/example.txt"
          permissions = "0644"
          owner       = "root:root"
          encoding    = "b64"
          content     = filebase64("${path.module}/example.txt")
        },
      ]
    })}
  END
}
</code>```

The write_files module can accept data in base64 format when we set encoding = "b64", so we use that in conjunction with Terraform's filebase64 function to include the contents of an external file. Other approaches are possible here, such as producing a string dynamically using Terraform templates and using base64encode to encode it as the file contents.

If you can express everything you want cloud-init to do in a single configuration file like the above then you can assign local.cloud_config_config directly as your instance user_data, and cloud-config will should recognize and process it on system boot:

```<code>  user_data = local.cloud_config_config
</code>```

If you instead need to combine creating the file with some other actions, like running a shell script, you can use cloud-init's multipart archive format to encode multiple "files" for cloud-init to process. Terraform has a cloudinit provider that contains a data source for easily constructing a multipart archive for cloud-init:

```<code>data "cloudinit_config" "example" {
  gzip          = false
  base64_encode = false

  part {
    content_type = "text/cloud-config"
    filename     = "cloud-config.yaml"
    content      = local.cloud_config_config
  }

  part {
    content_type = "text/x-shellscript"
    filename     = "example.sh"
    content  = <<-EOF
      #!/bin/bash
      echo "Hello World"
    EOT
  }
}
</code>```

This data source will produce a single string at cloudinit_config.example.rendered which is a multipart archive suitable for use as user_data for cloud-init:

```<code>  user_data = data.cloudinit_config.example.rendered
</code>```

EC2 imposes a maximum user-data size of 64 kilobytes, so all of the encoded data together must fit within that limit. If you need to place a large file that comes close to or exceeds that limit, it would probably be best to use an intermediate other system to transfer that file, such as having Terraform write the file into an Amazon S3 bucket and having the software in your instance retrieve that data using instance profile credentials. That shouldn't be necessary for small data files used for system configuration, though.

It's important to note that from the perspective of Terraform and EC2 the content of user_data is just an arbitrary string. Any issues in processing the string must be debugged within the target operating system itself, by reading the cloud-init logs to see how it interpreted the configuration and what happened when it tried to take those actions.

[1]: We could also potentially use yamlencode, but at the time I write this that function has a warning that its exact formatting may change in future Terraform versions, and that's undesirable for user_data because it would cause the instance to be replaced. If you are reading this in the future and that warning is no longer present in the yamldecode docs, consider using yamlencode instead.

Body:
We have cronjob and shell script which we want to copy or upload to aws ec2 instance while creating instance using terraform.

we tried

file provisioner :
but its not wokring , and read this option does not work with all terraform version

      provisioner "file" {
        source      = "abc.sh"
        destination = "/home/ec2-user/basic2.sh"
      }

tried data template file option

    data "template_file" "userdata_line" {
      template = <<EOF
    #!/bin/bash
    mkdir /home/ec2-user/files2
    cd /home/ec2-user/files2
    sudo touch basic2.sh
    sudo chmod 777 basic2.sh
    base64 basic.sh |base64 -d >basic2.sh
    EOF
    }

tried all option but none of them working.

could u please help or advise .

I am new to terraform so struggling on this from long time.

Body:
When starting from an AMI that has cloud-init installed (which is common in many official Linux distri), we can use cloud-init's write_files module to place arbitrary files into the filesystem, as long as they are small enough to fit within the constraints of the user_data argument along with all of the other cloud-init data.

As with all cloud-init modules, we configure write_files using cloud-init's YAML-based configuration format, which begins with the special marker string #cloud-config on a line of its own, followed by a YAML data structure. Because JSON is a subset of YAML, we can use Terraform's jsonencode to produce a valid value[1].

locals {
  cloud_config_config = <<-END
    #cloud-config
    ${jsonencode({
      write_files = [
        {
          path        = "/etc/example.txt"
          permissions = "0644"
          owner       = "root:root"
          encoding    = "b64"
          content     = filebase64("${path.module}/example.txt")
        },
      ]
    })}
  END
}

The write_files module can accept data in base64 format when we set encoding = "b64", so we use that in conjunction with Terraform's filebase64 function to include the contents of an external file. Other approaches are possible here, such as producing a string dynamically using Terraform templates and using base64encode to encode it as the file contents.

If you can express everything you want cloud-init to do in a single configuration file like the above then you can assign local.cloud_config_config directly as your instance user_data, and cloud-config will should recognize and process it on system boot:

  user_data = local.cloud_config_config

If you instead need to combine creating the file with some other actions, like running a shell script, you can use cloud-init's multipart archive format to encode multiple "files" for cloud-init to process. Terraform has a cloudinit provider that contains a data source for easily constructing a multipart archive for cloud-init:

data "cloudinit_config" "example" {
  gzip          = false
  base64_encode = false

  part {
    content_type = "text/cloud-config"
    filename     = "cloud-config.yaml"
    content      = local.cloud_config_config
  }

  part {
    content_type = "text/x-shellscript"
    filename     = "example.sh"
    content  = <<-EOF
      #!/bin/bash
      echo "Hello World"
    EOT
  }
}

This data source will produce a single string at cloudinit_config.example.rendered which is a multipart archive suitable for use as user_data for cloud-init:

  user_data = data.cloudinit_config.example.rendered

EC2 imposes a maximum user-data size of 64 kilobytes, so all of the encoded data together must fit within that limit. If you need to place a large file that comes close to or exceeds that limit, it would probably be best to use an intermediate other system to transfer that file, such as having Terraform write the file into an Amazon S3 bucket and having the software in your instance retrieve that data using instance profile credentials. That shouldn't be necessary for small data files used for system configuration, though.

It's important to note that from the perspective of Terraform and EC2 the content of user_data is just an arbitrary string. Any issues in processing the string must be debugged within the target operating system itself, by reading the cloud-init logs to see how it interpreted the configuration and what happened when it tried to take those actions.

[1]: We could also potentially use yamlencode, but at the time I write this that function has a warning that its exact formatting may change in future Terraform versions, and that's undesirable for user_data because it would cause the instance to be replaced. If you are reading this in the future and that warning is no longer present in the yamldecode docs, consider using yamlencode instead.


问:
Reason and suggestion for: TypeError: not all arguments converted during string formatting
Why this error is occurring and how can I fix it?
I am trying to write this code as a practice in codewars.

```<code>def iq_test(numbers):
    splitted_num=numbers.split()
    list_numbers= list(splitted_num)#splitted string was already a list
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    return (odds.index[0, 1] if len(odds)<len(evens) else evens[0, 1])

numbers= ("2 4 7 8 10")
print(iq_test(numbers))
</code>```

ERROR:

```<code>Traceback (most recent call last):
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 13, in <module>
    print(iq_test(numbers))
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in iq_test
    odds = [x for x in list_numbers if x%2!=0]
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in <listcomp>
    odds = [x for x in list_numbers if x%2!=0]
TypeError: not all arguments converted during string formatting
</code>```

This is the question:

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number. Question: ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

答:
This should work, just add a line in the function that convert list of string number to list of intergers:</p>

```<code>def iq_test(numbers):
    splitted_num=numbers.split()
    list_numbers = map(int, splitted_num)
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    return (odds if len(odds)<len(evens) else evens)

numbers = ("2 4 7 8 10")
print(iq_test(numbers))
</code>```

Body:
Why this error is occurring and how can I fix it?
I am trying to write this code as a practice in codewars.

def iq_test(numbers):
    splitted_num=numbers.split()
    list_numbers= list(splitted_num)#splitted string was already a list
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    return (odds.index[0, 1] if len(odds)<len(evens) else evens[0, 1])

numbers= ("2 4 7 8 10")
print(iq_test(numbers))

ERROR:

Traceback (most recent call last):
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 13, in <module>
    print(iq_test(numbers))
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in iq_test
    odds = [x for x in list_numbers if x%2!=0]
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in <listcomp>
    odds = [x for x in list_numbers if x%2!=0]
TypeError: not all arguments converted during string formatting

This is the question:

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number. Question: ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

Body:
This should work, just add a line in the function that convert list of string number to list of intergers:

def iq_test(numbers):
    splitted_num=numbers.split()
    list_numbers = map(int, splitted_num)
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    return (odds if len(odds)<len(evens) else evens)

numbers = ("2 4 7 8 10")
print(iq_test(numbers))


答:
this is what you need

Example

class Another {
  constructor() {
  }

  anotherMethod(a) {
    console.log('This is anohter method');
    this.a = a.replace('!d', 'd !e');
    return this;
  }

  otherMethod() {
    return super.otherMethod(this.a);
  }
}

class ChainAble extends Another {
  constructor() {
    super();
  }

  firstMethod() {
    this.a = 'a !b';
    return this;
  }

  secondMethod() {
    this.a = this.a.replace('!b', 'b !c');
    return this;
  }

  thirdMethod() {
    this.a = this.a.replace('!c', 'c !d');
    return this;
  }
  anotherMethod() {
    return super.anotherMethod(this.a);
  }
}

const chainableInstance = new ChainAble();
chainableInstance.firstMethod().secondMethod().thirdMethod().anotherMethod();

console.log(chainableInstance);```

Title: Why my function secondMethod is not a function TypeError: (...).secondMethod is not a function

Body:
I am try to make a chainable instance for a personal project, and I try this simple example with some modifications, but I got a error:

TypeError: chainableInstance.firstMethod(...).secondMethod is not a function
    at Object.<anonymous> (/Users/rodger/Developer/Projects/Personal/unknown/src/teste.js:48:33)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

And my code is this:

  otherMethod(a) {
    return (this.a = a.replace('!e', 'e'));
  }
}
class Another extends Other {
  constructor() {
    super();
  }

  anotherMethod(a) {
    console.log('This is anohter method');
    return (this.a = a.replace('!d', 'd !e'));
  }

  otherMethod() {
    return super.otherMethod(this.a);
  }
}

class ChainAble extends Another {
  constructor() {
    super();
  }

  firstMethod() {
    return (this.a = 'a !b');
  }

  secondMethod() {
    return this.a.replace('!b', 'b !c');
  }

  thirdMethod() {
    return this.a.replace('!c', 'c !d');
  }
  anotherMethod() {
    return super.anotherMethod(this.a);
  }
}

const chainableInstance = new ChainAble();
chainableInstance.firstMethod().secondMethod().thirdMethod().anotherMethod();

console.log(chainableInstance);

I just not undestand why my secondMethod is It is considered "not a function", have someone to see what I am wrong in this stuff?


问:
Reduction columns are not working for group by expression in oracle
I tried to concat two columns and using group by expression, but it is not work. how can I grouped multiple columns in oracle. first_name and last_name are reduction data.</p>

```<code>SELECT employee_id,
  employee_name,
  employee_unique
FROM
  (SELECT a.id AS employee_id,
    (a.first_name
    || a.last_name) AS employee_name,
    b.employee_unique
  FROM A a
  INNER JOIN b
  ON a.id=b.employee_id
  GROUP BY a.id,
    b.employee_unique,
    (a.first_name
    || a.last_name)
  );
</code>```

答:
What does "not work" mean? It works for me (though, as I don't have your tables, I used Scott's EMP and DEPT, but everything else is more or less the same). If it isn't correct, you should explain what is wrong with it. If you want us to work with your data, please, provide CREATE TABLE and INSERT INTO sample data.

```<code>SQL> select employee_id,
  2         employee_name,
  3         employee_unique
  4  from
  5    (select a.empno          as employee_id,
  6            a.ename || a.job as employee_name,
  7            b.dname          as employee_unique
  8    from emp a
  9    inner join dept b
 10       on a.deptno=b.deptno
 11    group by a.empno,
 12             b.dname,
 13             a.ename || a.job
 14    );

EMPLOYEE_ID EMPLOYEE_NAME       EMPLOYEE_UNIQU
----------- ------------------- --------------
       7654 MARTINSALESMAN      SALES
       7876 ADAMSCLERK          RESEARCH
       7566 JONESMANAGER        RESEARCH
       7698 BLAKEMANAGER        SALES
       7844 TURNERSALESMAN      SALES
       7369 SMITHCLERK          RESEARCH
       7788 SCOTTANALYST        RESEARCH
       7900 JAMESCLERK          SALES
       7902 FORDANALYST         RESEARCH
       7782 CLARKMANAGER        ACCOUNTING
       7934 MILLERCLERK         ACCOUNTING
       7499 ALLENSALESMAN       SALES
       7521 WARDSALESMAN        SALES
       7839 KINGPRESIDENT       ACCOUNTING

14 rows selected.

SQL>
</code>```

Though, as there's nothing really to be grouped (no aggregation here), you could have used distinct (without group by clause) and get the same result:

```<code>select employee_id,
       employee_name,
       employee_unique
from
  (select distinct
          a.empno          as employee_id,
          a.ename || a.job as employee_name,
          b.dname          as employee_unique
  from emp a
  inner join dept b
     on a.deptno=b.deptno
  );
</code>```

Body:
I tried to concat two columns and using group by expression, but it is not work. how can I grouped multiple columns in oracle. first_name and last_name are reduction data.

SELECT employee_id,
  employee_name,
  employee_unique
FROM
  (SELECT a.id AS employee_id,
    (a.first_name
    || a.last_name) AS employee_name,
    b.employee_unique
  FROM A a
  INNER JOIN b
  ON a.id=b.employee_id
  GROUP BY a.id,
    b.employee_unique,
    (a.first_name
    || a.last_name)
  );

Body:
What does "not work" mean? It works for me (though, as I don't have your tables, I used Scott's EMP and DEPT, but everything else is more or less the same). If it isn't correct, you should explain what is wrong with it. If you want us to work with your data, please, provide CREATE TABLE and INSERT INTO sample data.

SQL> select employee_id,
  2         employee_name,
  3         employee_unique
  4  from
  5    (select a.empno          as employee_id,
  6            a.ename || a.job as employee_name,
  7            b.dname          as employee_unique
  8    from emp a
  9    inner join dept b
 10       on a.deptno=b.deptno
 11    group by a.empno,
 12             b.dname,
 13             a.ename || a.job
 14    );

EMPLOYEE_ID EMPLOYEE_NAME       EMPLOYEE_UNIQU
----------- ------------------- --------------
       7654 MARTINSALESMAN      SALES
       7876 ADAMSCLERK          RESEARCH
       7566 JONESMANAGER        RESEARCH
       7698 BLAKEMANAGER        SALES
       7844 TURNERSALESMAN      SALES
       7369 SMITHCLERK          RESEARCH
       7788 SCOTTANALYST        RESEARCH
       7900 JAMESCLERK          SALES
       7902 FORDANALYST         RESEARCH
       7782 CLARKMANAGER        ACCOUNTING
       7934 MILLERCLERK         ACCOUNTING
       7499 ALLENSALESMAN       SALES
       7521 WARDSALESMAN        SALES
       7839 KINGPRESIDENT       ACCOUNTING

14 rows selected.

SQL>

Though, as there's nothing really to be grouped (no aggregation here), you could have used distinct (without group by clause) and get the same result:

select employee_id,
       employee_name,
       employee_unique
from
  (select distinct
          a.empno          as employee_id,
          a.ename || a.job as employee_name,
          b.dname          as employee_unique
  from emp a
  inner join dept b
     on a.deptno=b.deptno
  );


问:
Match one list into another with minimum error
I have two lists, A and B. A will be at most ~1000 elements, and B will be at most ~100 elements. I want to match every element of B to an element of A, such that the sum of the absolute differences of the pairs is minimized.

i.e. I want to choose |B| distinct indexes from A, and assign them to the indexes of B, such that the following sum is minimized: sum(abs(A[j] - B[i]) for i in |B|, j = index_mapping(i))

My first approach is:

For each element of B, to compute the |B| closest elements of A.

Choose the pairs in a greedy fashion (i.e. minimum error first)

Playing with some simple examples, it's clear that my approach is not the best. It should work fine for my purpose, but I was wondering if anyone could suggest a better approach?

答:
Hmm...  Offhand, the first thought that comes to mind is that if you can sort A and B, then once you find the first mapping of A[j] to B[i], then for B[i+1], you could start your testing with A[j] instead of A[0].

For example:

```<code>A = [ 23, 34, 38, 52, 67, 68, 77, 80, 84, 95 ]
B = [ 31, 33, 64, 65, 99 ]
</code>```

You start with B[0] = 31 and step through A until you find the closest match, A[1].  Since the lists are ordered, you know that B[1] won't match anything less than A[1], so you can start comparing from there.  Turns out, A[1] is still the closest match.  At B[2], the closest match is A[4], so you know that B[3] won't match anything lower than A[4], there's no need to search A[0] through A[3].

Body:
Hmm...  Offhand, the first thought that comes to mind is that if you can sort A and B, then once you find the first mapping of A[j] to B[i], then for B[i+1], you could start your testing with A[j] instead of A[0].

For example:

A = [ 23, 34, 38, 52, 67, 68, 77, 80, 84, 95 ]
B = [ 31, 33, 64, 65, 99 ]

You start with B[0] = 31 and step through A until you find the closest match, A[1].  Since the lists are ordered, you know that B[1] won't match anything less than A[1], so you can start comparing from there.  Turns out, A[1] is still the closest match.  At B[2], the closest match is A[4], so you know that B[3] won't match anything lower than A[4], there's no need to search A[0] through A[3].