问:
Running a bash script before startup in an NGINX docker container
I'm trying to run a javascript app on localhost:8000 using docker. Part of what I would like to do is swap out some config files based on the docker run command, I'd like to pass an environment variable into the container so that the bash script can use that as a parameter.

What my dockerfile is looking like is this:

```<code>FROM nginx
COPY . /usr/share/nginx/html
CMD ["bash","/usr/share/nginx/html/runfile.sh"]
</code>```

And the bash script looks like this:

```<code>#!/bin/bash
if [ "$SECURITY_VERSION" = "OPENAM" ]; then
    sed -i -e 's/localhost/openam/g' authConfig.js
fi

docker run -p 8000:80 missioncontrol:latest -e SECURITY_VERSION="TEST"
</code>```

Docker gives me an exception saying -e exec command not found.

However if I change the dockerfile to use ENTRYPOINT instead of CMD, the -e flag works but the webserver does not start up.

Is there something I'm missing here? Is the ENTRYPOINT being overriden or something?

EDIT:

So I've updated my dockerfile to use ENTRYPOINT ["bash","/usr/share/nginx/html/runfile.sh", ";", " nginx -g daemon off;"]

But the docker container still shuts down. Is there something I'm missing?

答:
NginX image has docker-entrypoint.d included and on container start will look for any scripts located in there. You can add your custom scripts during docker build. I also found that if you are using alpine image, bash is not installed, so you can add it yourself by running:

```<code>RUN apk update
RUN apk upgrade
RUN apk add bash
</code>```

sample DockerFile:

```<code>FROM nginx:alpine

EXPOSE 443
EXPOSE 80

RUN apk update
RUN apk upgrade
RUN apk add bash

COPY ["my-script.sh", "/docker-entrypoint.d/my-script.sh"]
RUN chown nginx:nginx /docker-entrypoint.d/my-script.sh

USER nginx
</code>```

In order to limit scope execution of your custom script script, it's highly recommended to run your container as a non-privileged user.

Body:
I'm trying to run a javascript app on localhost:8000 using docker. Part of what I would like to do is swap out some config files based on the docker run command, I'd like to pass an environment variable into the container so that the bash script can use that as a parameter.

What my dockerfile is looking like is this:

FROM nginx
COPY . /usr/share/nginx/html
CMD ["bash","/usr/share/nginx/html/runfile.sh"]

And the bash script looks like this:

#!/bin/bash
if [ "$SECURITY_VERSION" = "OPENAM" ]; then
    sed -i -e 's/localhost/openam/g' authConfig.js
fi

docker run -p 8000:80 missioncontrol:latest -e SECURITY_VERSION="TEST"

Docker gives me an exception saying -e exec command not found.

However if I change the dockerfile to use ENTRYPOINT instead of CMD, the -e flag works but the webserver does not start up.

Is there something I'm missing here? Is the ENTRYPOINT being overriden or something?

EDIT:

So I've updated my dockerfile to use ENTRYPOINT ["bash","/usr/share/nginx/html/runfile.sh", ";", " nginx -g daemon off;"]

But the docker container still shuts down. Is there something I'm missing?

Body:
NginX image has docker-entrypoint.d included and on container start will look for any scripts located in there. You can add your custom scripts during docker build. I also found that if you are using alpine image, bash is not installed, so you can add it yourself by running:

RUN apk update
RUN apk upgrade
RUN apk add bash

sample DockerFile:

FROM nginx:alpine

EXPOSE 443
EXPOSE 80

RUN apk update
RUN apk upgrade
RUN apk add bash

COPY ["my-script.sh", "/docker-entrypoint.d/my-script.sh"]
RUN chown nginx:nginx /docker-entrypoint.d/my-script.sh

USER nginx

In order to limit scope execution of your custom script script, it's highly recommended to run your container as a non-privileged user.


来源: stackexchange

问:
How to randomly shuffle the values of only one column in pyspark?
I want to break the correlation between a column and the rest of the dataframe. I want to do this while maintaining the distribution of the values in the said column

In pandas, I used to achieve this by simply shuffling the values of a column and then assigning the values to the column. It is not so straightforward in the case of pyspark because of the data being partitioned. I do not think there is even a way in pyspark to set a new column in a dataframe with a column from another dataframe

So, In pyspark, how do I achieve the following?:

```<code>import pandas as pd
df = pd.DataFrame({'a':[1,2,3,4],'b':[3,4,5,6]})
df['b'] = df['b'].sample(frac=1).reset_index(drop=True)
</code>```

Also, I'm hoping you give me a solution that does not include unnecessary shuffles.

one way to do it is:

```<code>import pandas as pd
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
from pyspark.sql.functions import row_number,lit,rand
from pyspark.sql.window import Window
df = pd.DataFrame({'a':[1,2,3,4],'b':[3,4,5,6]})
dfs = spark.createDataFrame(df)
w = Window().orderBy(lit('A'))
dfs = dfs.withColumn("row_num", row_number().over(w))
dfs_ts = dfs.select('b')
dfs_ts = dfs_ts.withColumn('o',rand()).orderBy('o')
dfs = dfs.drop('b')
dfs_ts = dfs_ts.drop('o')
w = Window().orderBy(lit('A'))
dfs_ts = dfs_ts.withColumn("row_num", row_number().over(w))
dfs = dfs.join(dfs_ts,on='row_num').drop('row_num')
</code>```

But, I do not need the shuffles that come with join and they are not necessary. If a blind hstack is possible per partition basis in pyspark that should be enough. Also, the window function tells me that I have not defined any partitions so all my data would be collected to one partition. Might as well use pandas in that case

答:
I am not fully confident in this answer, but I think it's right.

We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

So if we get your Pandas example:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3,4],'b':[3,4,5,6]})
df['b'] = df['b'].sample(frac=1).reset_index(drop=True)
```
<p>We can just wrap the <code>.sample</code> expression in a function.</p>
```def shuffle(df: pd.DataFrame) -> pd.DataFrame:
    df['b'] = df['b'].sample(frac=1).reset_index(drop=True)
    return df
```
<p>And then we can bring it to Spark using the transform function. The ``transform` function can take in both Pandas and Spark DataFrames and then will convert it to Spark if you are using the Spark engine.</p>
```from fugue import transform
import fugue_spark
transform(df, shuffle, schema="*", engine="spark")
```
<p>But of course, this <code>transform</code> is applied per partition. If you don't specify the partitions, it uses the default partitions. If you want to shuffle to really randomize it, you can do:</p>
<pre class="lang-py prettyprint-override"><code>transform(df, shuffle, schema="*", engine="spark", partition={"algo":"rand"}).show()
</code>```

And Fugue will partition your data randomly before this operation.

You may not see the shuffle for your test case because the data is really small. If you end up with 4 partitions with 1 row each, they will end up returning the same value.

ContentLicense: CC BY-SA 4.0

Body:
I want to break the correlation between a column and the rest of the dataframe. I want to do this while maintaining the distribution of the values in the said column

In pandas, I used to achieve this by simply shuffling the values of a column and then assigning the values to the column. It is not so straightforward in the case of pyspark because of the data being partitioned. I do not think there is even a way in pyspark to set a new column in a dataframe with a column from another dataframe

So, In pyspark, how do I achieve the following?:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3,4],'b':[3,4,5,6]})
df['b'] = df['b'].sample(frac=1).reset_index(drop=True)

Also, I'm hoping you give me a solution that does not include unnecessary shuffles.

one way to do it is:

import pandas as pd
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
from pyspark.sql.functions import row_number,lit,rand
from pyspark.sql.window import Window
df = pd.DataFrame({'a':[1,2,3,4],'b':[3,4,5,6]})
dfs = spark.createDataFrame(df)
w = Window().orderBy(lit('A'))
dfs = dfs.withColumn("row_num", row_number().over(w))
dfs_ts = dfs.select('b')
dfs_ts = dfs_ts.withColumn('o',rand()).orderBy('o')
dfs = dfs.drop('b')
dfs_ts = dfs_ts.drop('o')
w = Window().orderBy(lit('A'))
dfs_ts = dfs_ts.withColumn("row_num", row_number().over(w))
dfs = dfs.join(dfs_ts,on='row_num').drop('row_num')

But, I do not need the shuffles that come with join and they are not necessary. If a blind hstack is possible per partition basis in pyspark that should be enough. Also, the window function tells me that I have not defined any partitions so all my data would be collected to one partition. Might as well use pandas in that case

Body:
I am not fully confident in this answer, but I think it's right.

We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

So if we get your Pandas example:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3,4],'b':[3,4,5,6]})
df['b'] = df['b'].sample(frac=1).reset_index(drop=True)

We can just wrap the .sample expression in a function.

def shuffle(df: pd.DataFrame) -> pd.DataFrame:
    df['b'] = df['b'].sample(frac=1).reset_index(drop=True)
    return df

And then we can bring it to Spark using the transform function. The ``transform` function can take in both Pandas and Spark DataFrames and then will convert it to Spark if you are using the Spark engine.

from fugue import transform
import fugue_spark
transform(df, shuffle, schema="*", engine="spark")

But of course, this transform is applied per partition. If you don't specify the partitions, it uses the default partitions. If you want to shuffle to really randomize it, you can do:

transform(df, shuffle, schema="*", engine="spark", partition={"algo":"rand"}).show()

And Fugue will partition your data randomly before this operation.

You may not see the shuffle for your test case because the data is really small. If you end up with 4 partitions with 1 row each, they will end up returning the same value.


问:
Regarding Instance in Spring mvc web application development
I am new to spring mvc web development. I have one query.
Suppose we are having different service classes. So do we have one instance of those classes per request OR only single instance of that class gets create. Actually i want to use instance variables , so with each request new instance will get created or it will be like singleton type of behavior.  Hopefully i am able to explain my question.</p>

答:
If you have not defined any scope explicitly, it will be singleton by default, singleton means there will be one object per spring container, for your context, one object for all your request threads. In case of singleton scope, be cautious while using member variables, because thread safety comes into picture.

If you are modifying state of a member variable inside your singleton scoped bean, you need to write thread safe code because multiple threads are accessing your member variable and a race condition may occur.

Moreover, you can define other scopes too using @Scope at the class level(i.e above @Component) or at method level above @Bean annotations.

Generally, we keep using the default scope (i.e singleton scope), this way spring container also does not waste time in creating the new object of the bean asked for, though it would be a little overhead creating an object on each request thread.

If you want a new object on every bean injection, you can have prototype scope for that bean.

ContentLicense: CC BY-SA 3.0


问:
write_pandas snowflake connector function is not able to operate on table
I am working on a python script that is designed to process some data, create a table if not exists, and truncate the table before inserting a refreshed dataset. I am using a role that has usage, read, write, create table permissions, as well stage permissions set as follows:

grant usage, read, write on future stages in schema <schema> to role <role>

I am using the write_pandas function in python via the snowflake connector. The documentation says that this function uses PUT and Copy Into commands:

To write the data to the table, the function saves the data to Parquet files, uses the PUT command to upload these files to a temporary stage, and uses the COPY INTO
 command to copy the data from the files to the table. You can use some of the function parameters to control how the PUT and COPY INTO
 statements are executed.

I still get the error message that I am unable to operate on the schema, and I am not sure what else I need to add. Does someone have the list of permissions that are required to run the write_pandas command?

答:
In the community spirit of StackOverflow, I made some changes / cleanup to the answer that @Cory Randolph posted.

```<code>import snowflake.connector
from snowflake.connector.pandas_tools import write_pandas

conn = snowflake.connector.connect(
    user=USER,
    password=PASSWORD,
    account=ACCOUNT,
    database=DATABASE,
    role=ROLE,
    warehouse=WAREHOUSE,
    schema=ML)

def get_table_metadata(df):
    def map_dtypes(x):
        if (x == 'object') or (x=='category'):
            return 'VARCHAR'
        elif 'date' in x:
            return 'DATETIME'
        elif 'int' in x:
            return 'NUMERIC'
        elif 'float' in x: return 'FLOAT'
        else:
            print("cannot parse pandas dtype")
    sf_dtypes = [map_dtypes(str(s)) for s in df.dtypes]
    table_metadata = ", ". join([" ".join([y.upper(), x]) for x, y in zip(sf_dtypes, list(df.columns))])
    return table_metadata

def df_to_snowflake_table(table_name, operation, df, conn=conn):
    if operation=='create_replace':
        df.columns = [c.upper() for c in df.columns]
        table_metadata = get_table_metadata(df)
        conn.cursor().execute(f"CREATE OR REPLACE TABLE {table_name} ({table_metadata})")
        write_pandas(conn, df, table_name.upper())
    elif operation=='insert':
        table_rows = str(list(df.itertuples(index=False, name=None))).replace('[','').replace(']','')
        conn.cursor().execute(f"INSERT INTO {table_name} VALUES {table_rows}")
</code>```

Then

```<code>df_to_snowflake_table('table_test', 'create_replace', df)
</code>```

and/or

```<code>df_to_snowflake_table('table_test', 'insert', df)
</code>```

Body:
In the community spirit of StackOverflow, I made some changes / cleanup to the answer that @Cory Randolph posted.

import snowflake.connector
from snowflake.connector.pandas_tools import write_pandas

conn = snowflake.connector.connect(
    user=USER,
    password=PASSWORD,
    account=ACCOUNT,
    database=DATABASE,
    role=ROLE,
    warehouse=WAREHOUSE,
    schema=ML)

def get_table_metadata(df):
    def map_dtypes(x):
        if (x == 'object') or (x=='category'):
            return 'VARCHAR'
        elif 'date' in x:
            return 'DATETIME'
        elif 'int' in x:
            return 'NUMERIC'
        elif 'float' in x: return 'FLOAT'
        else:
            print("cannot parse pandas dtype")
    sf_dtypes = [map_dtypes(str(s)) for s in df.dtypes]
    table_metadata = ", ". join([" ".join([y.upper(), x]) for x, y in zip(sf_dtypes, list(df.columns))])
    return table_metadata

def df_to_snowflake_table(table_name, operation, df, conn=conn):
    if operation=='create_replace':
        df.columns = [c.upper() for c in df.columns]
        table_metadata = get_table_metadata(df)
        conn.cursor().execute(f"CREATE OR REPLACE TABLE {table_name} ({table_metadata})")
        write_pandas(conn, df, table_name.upper())
    elif operation=='insert':
        table_rows = str(list(df.itertuples(index=False, name=None))).replace('[','').replace(']','')
        conn.cursor().execute(f"INSERT INTO {table_name} VALUES {table_rows}")

Then

df_to_snowflake_table('table_test', 'create_replace', df)

and/or

df_to_snowflake_table('table_test', 'insert', df)


问:
Writing to a file with mode "w" versus "a" - I can't get "w" to work properly
Let me start out by saying I am very new to Python.  I'm taking a Udemy bootcamp, so I am not by any means condoning my solution as the best solution, but for the life of me, I cannot figure out why, when I write to the output files, I have to use mode "a" instead of "w".  If I use "w", it only writes the last line of the starting_letter.txt.

invited_names.txt is a .txt file attached to the project with the following records.  There is no new line \n after the last name in the file:

```<code>Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph
</code>```

The starting_letter.txt file is also attached to my project.

```<code>Dear [name],

You are invited to my birthday this Saturday.

Hope you can make it!

Joel
</code>```

The function of the program is to replace [name] from the first record in the starting_letter.txt file with a name from the invited_names.txt file and create an output file for each name in invited_names.txt. I would prefer to use mode "w" so the files get overlaid each time the file runs because mode "a" obviously will append to an existing file if it already exists. I compared my code to the instructor's solution, and I can't see why hers works with "w", but mine doesn't.

```<code>invited_names = open("./Input/Names/invited_names.txt")
invited_names_list = invited_names.readlines()

for i in range(len(invited_names_list)):
    invited_names_list[i] = invited_names_list[i].strip()

starting_letter = open("./Input/Letters/starting_letter.txt")
starting_letter_list = starting_letter.readlines()

for name in invited_names_list:
    for line in starting_letter_list:
        new_line = line.replace("[name]", name)
        with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="a") as file:
            file.write(new_line)
</code>```

答:
Replace

```<code>with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="a") as file:
</code>```

with

```<code>with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="w") as file:
</code>```

Body:
Let me start out by saying I am very new to Python.  I'm taking a Udemy bootcamp, so I am not by any means condoning my solution as the best solution, but for the life of me, I cannot figure out why, when I write to the output files, I have to use mode "a" instead of "w".  If I use "w", it only writes the last line of the starting_letter.txt.

invited_names.txt is a .txt file attached to the project with the following records.  There is no new line \n after the last name in the file:

Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph

The starting_letter.txt file is also attached to my project.

Dear [name],

You are invited to my birthday this Saturday.

Hope you can make it!

Joel

The function of the program is to replace [name] from the first record in the starting_letter.txt file with a name from the invited_names.txt file and create an output file for each name in invited_names.txt. I would prefer to use mode "w" so the files get overlaid each time the file runs because mode "a" obviously will append to an existing file if it already exists. I compared my code to the instructor's solution, and I can't see why hers works with "w", but mine doesn't.

invited_names = open("./Input/Names/invited_names.txt")
invited_names_list = invited_names.readlines()

for i in range(len(invited_names_list)):
    invited_names_list[i] = invited_names_list[i].strip()

starting_letter = open("./Input/Letters/starting_letter.txt")
starting_letter_list = starting_letter.readlines()

for name in invited_names_list:
    for line in starting_letter_list:
        new_line = line.replace("[name]", name)
        with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="a") as file:
            file.write(new_line)

Body:
Replace

with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="a") as file:

with

with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="w") as file:


问:
Problem with calling a method using a prototype
Hi I have this code written and I want the output to be "bill jones is a snowboarder of beginner skill on the slopes.". I am getting "function () { return this.firstName + " " + this.lastName; } is a snowboarder of beginner skill on the slopes." I think the problem is the way I am calling the fullName method but I am stuck.

https://codepen.io/stefan927/pen/yLPJdQG?editors=1111

```<code>(function() {
  const fullName = document.getElementById('fullName');
  const type = document.getElementById('type');
  const ability = document.getElementById('ability');

  function Person(firstname, lastname, type, ability) {
    this.firstName = firstname;
    this.lastName = lastname;
    this.type = type;
    this.ability = ability;
  }
  Person.prototype.fullName = function() {
    return this.firstName + " " + this.lastName;
  }

  var skier = new Person('Bill', 'Jones', 'snowboarder', 'beginner');

  fullName.textContent = skier.fullName;
  type.textContent = skier.type;
  ability.textContent = skier.ability;

}())
</code>```

答: Like Pointy pointed ( no pun intended ) out in his comment, you are not calling the fullName function which is invoked with a pair of (). So, in your code fullName.textContent = skier.fullName should be fullName.textContent = skier.fullName(). That should resolve your issue.

Body:
Hi I have this code written and I want the output to be "bill jones is a snowboarder of beginner skill on the slopes.". I am getting "function () { return this.firstName + " " + this.lastName; } is a snowboarder of beginner skill on the slopes." I think the problem is the way I am calling the fullName method but I am stuck.

https://codepen.io/stefan927/pen/yLPJdQG?editors=1111

(function() {
  const fullName = document.getElementById('fullName');
  const type = document.getElementById('type');
  const ability = document.getElementById('ability');

  function Person(firstname, lastname, type, ability) {
    this.firstName = firstname;
    this.lastName = lastname;
    this.type = type;
    this.ability = ability;
  }
  Person.prototype.fullName = function() {
    return this.firstName + " " + this.lastName;
  }

  var skier = new Person('Bill', 'Jones', 'snowboarder', 'beginner');

  fullName.textContent = skier.fullName;
  type.textContent = skier.type;
  ability.textContent = skier.ability;

}())


问:
PHP: insert into associative array by index?
I have an array like:

```<code>$example = array("car"=>"red", "banana"=>"yellow", etc...)
</code>```

Is it possible to alter a value of the array by index instead of key value like

```<code>$example[0] = "blue";
</code>```

So that the array now looks like

```<code>$example = array("car"=>"blue", "banana"=>"yellow", etc...)
</code>```

答:
you can do this way:

```<code>$e = array("car"=>"red", "banana"=>"yellow");
$keys = array_keys($e);
$e[$keys[0]] = 'blue';

var_dump($e);
</code>```

the output is

```<code>array(2) { ["car"]=> string(4) "blue" ["banana"]=> string(6) "yellow" }
</code>```

Body:
I have an array like:

$example = array("car"=>"red", "banana"=>"yellow", etc...)

Is it possible to alter a value of the array by index instead of key value like

$example[0] = "blue";

So that the array now looks like

$example = array("car"=>"blue", "banana"=>"yellow", etc...)

Body:
you can do this way:

$e = array("car"=>"red", "banana"=>"yellow");
$keys = array_keys($e);
$e[$keys[0]] = 'blue';

var_dump($e);

the output is

array(2) { ["car"]=> string(4) "blue" ["banana"]=> string(6) "yellow" }


问:
Button's clickable area is above the button
I'm relitavely new to HTML and have ran into this error after using display: flex.
My buttons clickable area is about 10px above the actual button, and when I use inspect element, the button highlight says its above where the visible button is.

CoderTom

Home

        <button style="position : relative; top: 50px; background-color: rgb(0, 255, 55); font-family: sans-serif; font-weight: 700; color: black; width: 100%; height: 100%;">Contact</button>

```

答: property top: 50px in anchor tag moves element up 50px. I guess you wanted to give it to parent (.button-group)</p>


答:
I recommend you to style the  tag like a button and add ' display: block '
Also remember to reset default styling of the browser</p>

Title: Button's clickable area is above the button

Body:
I'm relitavely new to HTML and have ran into this error after using display: flex.
My buttons clickable area is about 10px above the actual button, and when I use inspect element, the button highlight says its above where the visible button is.

CoderTom

Home

        <button style="position : relative; top: 50px; background-color: rgb(0, 255, 55); font-family: sans-serif; font-weight: 700; color: black; width: 100%; height: 100%;">Contact</button>


答:
You have added fullName to the Persons prototype, and it's a function.

So you need to call/invoke this function.

```<code>fullName.textContent = skier.fullName(); //added () to fullName
</code>```

Title: Problem with calling a method using a prototype

Body:
You have added fullName to the Persons prototype, and it's a function.

So you need to call/invoke this function.

fullName.textContent = skier.fullName(); //added () to fullName


问:
Get instruction pointer on segmentation fault or crash (for x86 JIT compiler project)?
I'm implementing the backend for a JavaScript JIT compiler that produces x86 code. Sometimes, as the result of bugs, I get segmentation faults. It can be quite difficult to trace back what caused them. Hence, I've been wondering if there would be some "easy" way to trap segmentation faults and other such crashes, and get the address of the instruction that caused the fault. This way, I could map the address back to compiled x86 assembly, or even back to source code.

This needs to work on Linux, but ideally on any POSIX compliant system. In the worst case, if I can't catch the seg fault and get the IP in my running JIT, I'd like to be able to trap it outside (kernel log?), and perhaps just have the compiler dump a big file with mappings of addresses to instructions, which I could match with a Python script or something.

Any ideas/suggestions are appreciated. Feel free to share your own debugging tips if you've ever worked on a compiler project of your own.

答:
If you use sigaction, you can define a signal handler that takes 3 arguments:

```<code>void (*sa_sigaction)(int signum, siginfo_t *info, void *ucontext)
</code>```

The third argument passed to the signal handler is a pointer to an OS and architecture specific data structure.  On linux, its a ucontext_t which is defined in the <sys/ucontext.h> header file.  Within that, uc_mcontext is an mcontext_t (machine context) which for x86 contains all the registers at the time of the signal in gregs.  So you can access

```<code>ucontext->uc_mcontext.gregs[REG_EIP]  (32 bit mode)
ucontext->uc_mcontext.gregs[REG_RIP]  (64 bit mode)
</code>```

to get the instruction pointer of the faulting instruction.

Body:
If you use sigaction, you can define a signal handler that takes 3 arguments:

void (*sa_sigaction)(int signum, siginfo_t *info, void *ucontext)

The third argument passed to the signal handler is a pointer to an OS and architecture specific data structure.  On linux, its a ucontext_t which is defined in the <sys/ucontext.h> header file.  Within that, uc_mcontext is an mcontext_t (machine context) which for x86 contains all the registers at the time of the signal in gregs.  So you can access

ucontext->uc_mcontext.gregs[REG_EIP]  (32 bit mode)
ucontext->uc_mcontext.gregs[REG_RIP]  (64 bit mode)

to get the instruction pointer of the faulting instruction.


问:
Want to create Serialized Field that is a list, and has Enumerated options
This works for creating a field that has a drop down box with all available options.

```<code>   [System.Serializable]
    private enum researchTypes
    {
        PHYSICS, BIOLOGY, ENGINEERING, ALL, NONE
    }
</code>```

This does not work when I try to do the same thing, except now with the intention of being able to list several enumerated items.

```<code>    [System.Serializable]
    private enum worldCardTagTypes
    {
        NONE, ROCKY, ICE, MINIMAL_GRAVITY, GAS_GIANT //
    }

    [SerializeField] List<worldCardTagTypes> worldCardTags = new List<worldCardTagTypes>;
</code>```

My goal is to be able to edit a list of tags. If there is something wrong with how I asked this question, please feel free to comment on that, too.

答:
Why not rather use a Flags instead

```<code>[Flags]
private enum researchTypes
{
    // Important that the values are 2^X so they aren't overlapping on a bits level
    PHYSICS = 1,
    BIOLOGY = 2,
    ENGINEERING = 4
}

[SerializeField] private researchTypes worldCardTags;
</code>```

For this Unity will show a drop-down where you can select multiple items.

Afaik by default it will include also a Nothing (==0) and Everything (==bitwise "sum"/combination of all) option.

You then use bitwise and shift operators to combine, invert and check for certain values.

E.g. for combining or appending multiple values use bitwise OR

```<code>var physicsAndBiology = researchTypes.PHYSICS | researchTypes.BIOLOGY;
</code>```

For checking if a certain flag is contained either bitwise AND

```<code>var hasPhysics = physicsAndBiology & researchTypes.PHYSICS == researchTypes.PHYSICS;
</code>```

or also

```<code> var hasPhysics = physicsAndBiology.HasFlag(researchTypes.PHYSICS);
</code>```

If you want to check if any of some given flags is set you can use e.g.

```<code>var hasPhysicsOrBiologyOrBoth = worldCardTags & researchTypes.PHYSICS & researchTypes.BIOLOGY != 0;
</code>```

or if you want to check if both flags are set then

```<code>var hasPhysicsAndBiology = worldCardTags.HasFlag(researchTypes.PHYSICS | researchTypes.BIOLOGY);
</code>```

Body:
This works for creating a field that has a drop down box with all available options.

   [System.Serializable]
    private enum researchTypes
    {
        PHYSICS, BIOLOGY, ENGINEERING, ALL, NONE
    }

This does not work when I try to do the same thing, except now with the intention of being able to list several enumerated items.

    [System.Serializable]
    private enum worldCardTagTypes
    {
        NONE, ROCKY, ICE, MINIMAL_GRAVITY, GAS_GIANT //
    }

    [SerializeField] List<worldCardTagTypes> worldCardTags = new List<worldCardTagTypes>;

My goal is to be able to edit a list of tags. If there is something wrong with how I asked this question, please feel free to comment on that, too.

Body:
Why not rather use a Flags instead

[Flags]
private enum researchTypes
{
    // Important that the values are 2^X so they aren't overlapping on a bits level
    PHYSICS = 1,
    BIOLOGY = 2,
    ENGINEERING = 4
}

[SerializeField] private researchTypes worldCardTags;

For this Unity will show a drop-down where you can select multiple items.

Afaik by default it will include also a Nothing (==0) and Everything (==bitwise "sum"/combination of all) option.

You then use bitwise and shift operators to combine, invert and check for certain values.

E.g. for combining or appending multiple values use bitwise OR

var physicsAndBiology = researchTypes.PHYSICS | researchTypes.BIOLOGY;

For checking if a certain flag is contained either bitwise AND

var hasPhysics = physicsAndBiology & researchTypes.PHYSICS == researchTypes.PHYSICS;

or also

 var hasPhysics = physicsAndBiology.HasFlag(researchTypes.PHYSICS);

If you want to check if any of some given flags is set you can use e.g.

var hasPhysicsOrBiologyOrBoth = worldCardTags & researchTypes.PHYSICS & researchTypes.BIOLOGY != 0;

or if you want to check if both flags are set then

var hasPhysicsAndBiology = worldCardTags.HasFlag(researchTypes.PHYSICS | researchTypes.BIOLOGY);


问:
Get the element from hashset where hashset.Count==1
How to get the element from hashset that is known to contain exactly 1 element?
(without iterating it)</p>

答:
I had a HashSet<object> that for some reason couldn't be accessed with [0] or .First().

Though technically iterating, I'm leaving this here just in case someone else with my issue runs into this post.

```<code>foreach (var i in myHash){
    object o = i;
    break;
}
</code>```

Simply start to iterate, then immediately break the iteration.

Body:
I had a HashSet<object> that for some reason couldn't be accessed with [0] or .First().

Though technically iterating, I'm leaving this here just in case someone else with my issue runs into this post.

foreach (var i in myHash){
    object o = i;
    break;
}

Simply start to iterate, then immediately break the iteration.


问:
Loop with matrix in R
Suppose,I have a matrix of 10 X 100 as follow (actually matrix quite big):

```<code>x = matrix(norm(n=10), 10, 100)
</code>```

Now I want to make 1000 by 1 matrix by combining column 1 though 100. [for example like rbind.

my code is as follow:

```<code>y=matrix(0,nrow=1000,ncol=1)

for(row in 1:10){
y[1+(row-1)*100:(row)*100, 1]=x[row,1:100]
}
</code>```

My expected output is something like this

y=matrix(rnorm(1000),nrow=1000, ncol=1)
```

Somehow my code does not seem to be correct.

答:
All you need to do is change the dimensions of the matrix:</p>
```<code>x <- matrix(1:100, 5, 20)
y <- matrix(x, 100, 1)
</code>```

Title: Loop with matrix in R

Body:
Suppose,I have a matrix of 10 X 100 as follow (actually matrix quite big):

x = matrix(norm(n=10), 10, 100)

Now I want to make 1000 by 1 matrix by combining column 1 though 100. [for example like rbind.

my code is as follow:

y=matrix(0,nrow=1000,ncol=1)

for(row in 1:10){
y[1+(row-1)*100:(row)*100, 1]=x[row,1:100]
}

My expected output is something like this

y=matrix(rnorm(1000),nrow=1000, ncol=1)

Somehow my code does not seem to be correct.

Body:
All you need to do is change the dimensions of the matrix:

x <- matrix(1:100, 5, 20)
y <- matrix(x, 100, 1)


问:
how to play sound using java
I am trying to play a sound(a.mp3 ) on button ckick in java.

I tried this code

AudioPlayer.player.start(new FileInputStream(new File("E://a.mp3")));

but the sound is not clear....

What should I do,(I'm a beginner in java).

答: take a look at JLayer. It's the best library I could find a couple of years ago. It's not perfect, but should fit your needs.</p>

Title: how to play sound using java


问:
How to mock lowdb in NestJS
I'm trying to mock my data access object using lowdb. But I'm not sure how to mock the collection based on my implementation.

AuthDao.ts

```<code>import { Injectable } from "@nestjs/common";
import { User } from "libs/api-interfaces/src/lib/api-interfaces";
import * as low from 'lowdb';
import * as FileSync from 'lowdb/adapters/FileSync';

  export interface MaintenanceRequestDB extends User {
    id: string;
    name: string;
  }

  export interface MaintenanceRequestData {
    users: MaintenanceRequestDB[];
  }

  const adapter = new FileSync<MaintenanceRequestDB>('./db/maint-requests.json')
  const db = low(adapter)

  db.defaults({ users: [] }).write();

@Injectable()
export class AuthDao {

    private get collection(): any {
            return db.get('users');
    }

    constructor(
    ) {
        //
    }

    async getAdminUsers(user: User): Promise<MaintenanceRequestDB> {
        const { username, password } = user;
        const values = await this.collection.find({
            username, password
    }).value();
        return values;
    }
}
</code>```

Auth.Dao.Spec.TS

```<code>import { Test } from "@nestjs/testing";
import { User } from "libs/api-interfaces/src/lib/api-interfaces";
import { AuthDao } from "./auth.dao";

describe('AuthService', () => {
    let dao: AuthDao;
    beforeAll(async () => {
      const app = await Test.createTestingModule({
        providers: [AuthDao],
      }).compile();
      dao = app.get<AuthDao>(AuthDao);
    });

    describe('getData', () => {
      it('should return valid user', async () => {

         const result = await dao.getAdminUsers(createUser("johndoe", "123456"));
         expect(result).toEqual({username: 'johndoe'});
      });
    });
  });

  function createUser(username: string, password: string): User {
    return ({
      username: username,
      password: password
    })
}
</code>```

Also since I use createUser function almost in every test, where and how can I refactor my code so that it can be use with other tests?

答:
I added two database to prevent iterating the real database, one holds the data to seed and the other the seeded database to use for unit test.

```<code>import { seedDatabase} from "../../../database";
beforeAll(async () => {
        seedDatabase();
    });
</code>```

then defined the database.ts

```<code>const databaseFile = path.join(__dirname, "../db/test-db.json");
const adapter = new FileSync<MaintenanceRequestDB>(databaseFile);
const db = low(adapter);
export const seedDatabase = () => {
    const testSeed = JSON.parse(
      fs.readFileSync(path.join(process.cwd(), "db", "test-db-seed.json"), "utf-8")
    );

    // seed database with test data
    db.setState(testSeed).write();
    return;
  };
</code>```

I thought you need spyOn or jest to mock the db, I guess you just need to load the db again.

Title: How to mock lowdb in NestJS

Body:
I'm trying to mock my data access object using lowdb. But I'm not sure how to mock the collection based on my implementation.

AuthDao.ts

import { Injectable } from "@nestjs/common";
import { User } from "libs/api-interfaces/src/lib/api-interfaces";
import * as low from 'lowdb';
import * as FileSync from 'lowdb/adapters/FileSync';

  export interface MaintenanceRequestDB extends User {
    id: string;
    name: string;
  }

  export interface MaintenanceRequestData {
    users: MaintenanceRequestDB[];
  }

  const adapter = new FileSync<MaintenanceRequestDB>('./db/maint-requests.json')
  const db = low(adapter)

  db.defaults({ users: [] }).write();

@Injectable()
export class AuthDao {

    private get collection(): any {
            return db.get('users');
    }

    constructor(
    ) {
        //
    }

    async getAdminUsers(user: User): Promise<MaintenanceRequestDB> {
        const { username, password } = user;
        const values = await this.collection.find({
            username, password
    }).value();
        return values;
    }
}

Auth.Dao.Spec.TS

import { Test } from "@nestjs/testing";
import { User } from "libs/api-interfaces/src/lib/api-interfaces";
import { AuthDao } from "./auth.dao";

describe('AuthService', () => {
    let dao: AuthDao;
    beforeAll(async () => {
      const app = await Test.createTestingModule({
        providers: [AuthDao],
      }).compile();
      dao = app.get<AuthDao>(AuthDao);
    });

    describe('getData', () => {
      it('should return valid user', async () => {

         const result = await dao.getAdminUsers(createUser("johndoe", "123456"));
         expect(result).toEqual({username: 'johndoe'});
      });
    });
  });

  function createUser(username: string, password: string): User {
    return ({
      username: username,
      password: password
    })
}

Also since I use createUser function almost in every test, where and how can I refactor my code so that it can be use with other tests?

Body:
I added two database to prevent iterating the real database, one holds the data to seed and the other the seeded database to use for unit test.

import { seedDatabase} from "../../../database";
beforeAll(async () => {
        seedDatabase();
    });

then defined the database.ts

const databaseFile = path.join(__dirname, "../db/test-db.json");
const adapter = new FileSync<MaintenanceRequestDB>(databaseFile);
const db = low(adapter);
export const seedDatabase = () => {
    const testSeed = JSON.parse(
      fs.readFileSync(path.join(process.cwd(), "db", "test-db-seed.json"), "utf-8")
    );

    // seed database with test data
    db.setState(testSeed).write();
    return;
  };

I thought you need spyOn or jest to mock the db, I guess you just need to load the db again.


问:
how to set english as default language when changing language in settings?
How can I set the default language to English if I changed the language in the settings

in this case, I do not have the first language localized, but the other two are localized

therefore, I will always have a second language by default, but I want only English in any such situations

that is, if my language is not localized, I want it to be English instead

i used https://pub.dev/packages/intl library

答:
There is a locale property inside the material app , your can set it to your default language</p>
```<code>locale: _locale,

Locale _locale = const Locale('en', '');
</code>```

Body:
There is a locale property inside the material app , your can set it to your default language

locale: _locale,

Locale _locale = const Locale('en', '');


问:
How to turn off FCM's automatic notifications with code, when the App is in the background?
My app has an option to turn on/off FCM notifications.

I can not show FCM notification when the App in foreground.

But how to turn off the notification function of FCM when the App in background?

Turn off FCM functionality with code in Android Studio.

答:
Firebase Cloud Messaging has two payload types in its messages:

Notification payloads, which is handled by the system itself if the app is not active, and can be handled by your code if the app is active.

Data payloads, which are always handled by your code. This code can then display a notification, but it can also do something else (or nothing at all) with the data.

If you send a Notification message and the app is not actively being used, that message is handled by the system and there's no way to prevent it from being displayed.

So you have two options:

Always send message with (only) a data payload, so that your own code can handle it - and display a notification if the user hasn't disabled that.

Don't send a message with a notification payload if the user has disabled receiving notifications.


问:
Replacing numerical IDs contained as lists of strings and lists of ints in a Pandas DataFrame
In order to make data anonymous, I need to replace original IDs with a different set of new IDs, but still have identical original IDs match across all fields after being replaced. The challenge is doing so elegantly across 4 different presentations of IDs in this Pandas DataFrame.

I have real-world data where numerical IDs are found in 4 possible formats:

Within a list of strings '["38", "15", "42"]'

Within a list of numbers [14, 42, 94]

As integers 42

As floats 1.0

Here is a generalized small DataFrame with all 4 data types.

```<code>df = pd.DataFrame([['["38", "15", "42"]', [14, 42, 94], 42, 1.0],\
 ['["8", "28"]', [1, 4], 8, 94.0], ['["12"]', [12], 12, 12.0]],\
 columns = ['CommentsID','AgentID','CaseID','TicketID'])

df
| CommentsID            | AgentID         | CaseID  | TicketID |
| --------------------- | --------------- | ------- | -------- |
| ['38', '15', '42']    | [14, 42, 94]    | 42      | 1.0      |
| ['8', '28']           | [1, 4]          | 8       | 94.0     |
| ['12']                | [12]            | 12      | 12.0     |
</code>```

For ease of use in a generalized example, I'm just adding 100 to generate a list of 'new IDs'. However, in the actual problem, the list of corresponding new IDs are randomly generated, so no adding 100 throughout to solve for this one.

```<code>orig_ids = list(range(100))
new_ids = [x + 100 for x in orig_ids]
</code>```

What I would like is to find the most efficient way to replace all of the original IDs in the dataframe with the new IDs across these four data types.

Best solution I have so far is to split into three parts:

Tackle the float and int versions with a replace() function (this does not affect the lists, even with regex=True):

```<code>df = df.replace(orig_ids, new_ids)
</code>```

For the lists of integers, use a far-from-Pythonic doubled for-loop to match indices on the ID lists:

```<code>def newIDnumbers(datacol):
    newlist = []
    for i in range(len(datacol)):
        numlist = [orig_ids.index(x) for x in df.AgentID[i]]
        newlistrow = []
        for idx in range(len(numlist)):
            newlistrow.append(new_ids[numlist[idx]])
        newlist.append(newlistrow)
    return newlist

df.AgentID = newIDnumbers(df.AgentID)
df
</code>```

For the lists of strings, build string lists of original ids and new ids, then use a far-from-Pythonic doubled for-loop to match indices on the ID lists:

```<code>str_orig_ids = [str(x) for x in orig_ids]
str_new_ids = [str(x) for x in new_ids]

def newIDstrings(datacol):
    newlist = []
    for i in range(len(datacol)):
        numlist = [str_orig_ids.index(x) for x in datacol.str.findall(r'"(\d*)"')[i]]
        newlistrow = []
        for idx in range(len(numlist)):
            newlistrow.append(str_new_ids[numlist[idx]])
        newlist.append(newlistrow)
    return newlist

df.CommentsID = [str(x) for x in newIDstrings(df.CommentsID)]
df
</code>```

Does anyone have a more elegant and less computationally-heavy way to achieve this output?

```<code>df
| CommentsID            | AgentID         | CaseID  | TicketID |
| --------------------- | --------------- | ------- | -------- |
| ['138', '115', '142'] | [114, 142, 194] | 142     | 100.0    |
| ['108', '128']        | [101, 104]      | 108     | 194.0    |
| ['112']               | [112]           | 112     | 112.0    |
</code>```

答:
If adding 100 is sufficient,

```<code>import json
df['CaseID'] = df['CaseID'] + 100
df['TicketID'] = df['TicketID'] + 100
df['AgentID'] = df['AgentID'].apply(lambda x: list(map(lambda y: y+100, x)))
df['CommentsID'] = df['CommentsID'].apply(lambda x: json.dumps(list(map(lambda y: str(int(y)+100), json.loads(x)))))
</code>```

For AgentID and CommentsID Series, we can use apply to apply transformation one by one.

For AgentID, this is easier because it is a column of list, so we only need to map each integer in the list to the addition.

For CommentsID, we need an additional step at the beginning to convert the list in str into a python list by json.loads, and another additional step at the end to convert the python list back to str using json.dumps.

Body:
In order to make data anonymous, I need to replace original IDs with a different set of new IDs, but still have identical original IDs match across all fields after being replaced. The challenge is doing so elegantly across 4 different presentations of IDs in this Pandas DataFrame.

I have real-world data where numerical IDs are found in 4 possible formats:

Within a list of strings '["38", "15", "42"]'

Within a list of numbers [14, 42, 94]

As integers 42

As floats 1.0

Here is a generalized small DataFrame with all 4 data types.

df = pd.DataFrame([['["38", "15", "42"]', [14, 42, 94], 42, 1.0],\
 ['["8", "28"]', [1, 4], 8, 94.0], ['["12"]', [12], 12, 12.0]],\
 columns = ['CommentsID','AgentID','CaseID','TicketID'])

df
| CommentsID            | AgentID         | CaseID  | TicketID |
| --------------------- | --------------- | ------- | -------- |
| ['38', '15', '42']    | [14, 42, 94]    | 42      | 1.0      |
| ['8', '28']           | [1, 4]          | 8       | 94.0     |
| ['12']                | [12]            | 12      | 12.0     |

For ease of use in a generalized example, I'm just adding 100 to generate a list of 'new IDs'. However, in the actual problem, the list of corresponding new IDs are randomly generated, so no adding 100 throughout to solve for this one.

orig_ids = list(range(100))
new_ids = [x + 100 for x in orig_ids]

What I would like is to find the most efficient way to replace all of the original IDs in the dataframe with the new IDs across these four data types.

Best solution I have so far is to split into three parts:

Tackle the float and int versions with a replace() function (this does not affect the lists, even with regex=True):

df = df.replace(orig_ids, new_ids)

For the lists of integers, use a far-from-Pythonic doubled for-loop to match indices on the ID lists:

def newIDnumbers(datacol):
    newlist = []
    for i in range(len(datacol)):
        numlist = [orig_ids.index(x) for x in df.AgentID[i]]
        newlistrow = []
        for idx in range(len(numlist)):
            newlistrow.append(new_ids[numlist[idx]])
        newlist.append(newlistrow)
    return newlist

df.AgentID = newIDnumbers(df.AgentID)
df

For the lists of strings, build string lists of original ids and new ids, then use a far-from-Pythonic doubled for-loop to match indices on the ID lists:

str_orig_ids = [str(x) for x in orig_ids]
str_new_ids = [str(x) for x in new_ids]

def newIDstrings(datacol):
    newlist = []
    for i in range(len(datacol)):
        numlist = [str_orig_ids.index(x) for x in datacol.str.findall(r'"(\d*)"')[i]]
        newlistrow = []
        for idx in range(len(numlist)):
            newlistrow.append(str_new_ids[numlist[idx]])
        newlist.append(newlistrow)
    return newlist

df.CommentsID = [str(x) for x in newIDstrings(df.CommentsID)]
df

Does anyone have a more elegant and less computationally-heavy way to achieve this output?

df
| CommentsID            | AgentID         | CaseID  | TicketID |
| --------------------- | --------------- | ------- | -------- |
| ['138', '115', '142'] | [114, 142, 194] | 142     | 100.0    |
| ['108', '128']        | [101, 104]      | 108     | 194.0    |
| ['112']               | [112]           | 112     | 112.0    |

Body:
If adding 100 is sufficient,

import json
df['CaseID'] = df['CaseID'] + 100
df['TicketID'] = df['TicketID'] + 100
df['AgentID'] = df['AgentID'].apply(lambda x: list(map(lambda y: y+100, x)))
df['CommentsID'] = df['CommentsID'].apply(lambda x: json.dumps(list(map(lambda y: str(int(y)+100), json.loads(x)))))

For AgentID and CommentsID Series, we can use apply to apply transformation one by one.

For AgentID, this is easier because it is a column of list, so we only need to map each integer in the list to the addition.

For CommentsID, we need an additional step at the beginning to convert the list in str into a python list by json.loads, and another additional step at the end to convert the python list back to str using json.dumps.


问:
Wordpress contact form 7 conditional logic pdf generation
I've built a multi-step contact form 7 questionnaire which uses a conditional logic plugin to help with some of the sections.

I've added the problem area below, it's one part of the form where the user makes a selection and is offered one of four additional sections depending on their choice.

This all works well. In the message body of the email that is sent this section displays correctly. The remaining 3 groups are hidden and don't display. Great.

But in the PDF that is generated using other WordPress plugins we have tested unfortunately all the group tags are displayed.

Is there any way I can structure the conditional logic differently or is there an alternative solution?

Any help or additional information, please ask.

Thanks

Contact Form 7

My Choice - Step 4

Select 'ONE' procedure [radio procedure use_label_element "Mesh Tape" "Colposuspension" "Natural Tissue Sling" "Urethra Bulking Agent Injection"]

[group mesh-selected clear_on_hide]
    Statement 1 [text mesh-mesh1 use_label_element placeholder"Reason Why"]
    Statement 2 [text mesh-colp1 use_label_element placeholder"Why I'm not"]
    Statement 3 [text mesh-sling1 use_label_element placeholder"Why I'm not"]
    Statement 4 [text mesh-ureth1 use_label_element placeholder"Why I'm not"]
[/group]
[group colp-selected clear_on_hide]
    Statement 1 [text colp-colp2 placeholder"Reason Why"]
    Statement 2 [text colp-mesh2 placeholder"Why I'm not"]
    Statement 3 [text colp-sling2 placeholder"Why I'm not"]
    Statement 4 [text colp-ureth2 placeholder"Why I'm not"]
[/group]
[group sling-selected clear_on_hide]
    Statement 1 [text sling-sling3 placeholder"Reason Why"]
    Statement 2 [text sling-colp3 placeholder"Why I'm not"]
    Statement 3 [text sling-mesh3 placeholder"Why I'm not"]
    Statement 4 [text sling-ureth3 placeholder"Why I'm not"]
[/group]
[group ureth-selected clear_on_hide]
    Statement 1 [text ureth-ureth4 placeholder"Reason Why I'm"]
    Statement 2 [text ureth-sling4 placeholder"Why I'm not"]
    Statement 3 [text ureth-colp4 placeholder"Why I'm not"]
    Statement 4 [text ureth-mesh4 placeholder"Why I'm not"]
[/group]

```

<p><strong>Conditional Logic</strong></p>

```show [mesh-selected] if [procedure] equals "Mesh Tape"
show [colp-selected] if [procedure] equals "Colposuspension"
show [sling-selected] if [procedure] equals "Natural Tissue Sling"
show [ureth-selected] if [procedure] equals "Urethral Bulking Agent Injection"
```

<p><strong>PDF Form Layout</strong></p>

```MY CHOICE
---------
Chosen Procedure: [procedure][mesh-selected]
[mesh-mesh1]
[mesh-colp1]
[mesh-sling1]
[mesh-ureth1]
[/mesh-selected][colp-selected]
[colp-mesh2]
[colp-colp2]
[colp-sling2]
[colp-ureth2]
[/colp-selected][sling-selected]
[sling-mesh3]
[sling-colp3]
[sling-sling3]
[sling-ureth3]
[/sling-selected][ureth-selected]
[ureth-mesh4]
[ureth-colp4]
[ureth-sling4]
[ureth-ureth4]
[/ureth-selected]
```

PDF Screenshot

Shows some random characters that were entered into one field section & the [group][/group] tags that are unfortunately displaying:

答:
Your conditional tags are closed on your form structure like this:

```<code>[group group-394][/group]
</code>```

But in the PDF you need to close tags like this:

```<code>[group-394][/group-394]
</code>```

This way you can hide separate texts along with the question.

Body:
I've built a multi-step contact form 7 questionnaire which uses a conditional logic plugin to help with some of the sections.

I've added the problem area below, it's one part of the form where the user makes a selection and is offered one of four additional sections depending on their choice.

This all works well. In the message body of the email that is sent this section displays correctly. The remaining 3 groups are hidden and don't display. Great.

But in the PDF that is generated using other WordPress plugins we have tested unfortunately all the group tags are displayed.

Is there any way I can structure the conditional logic differently or is there an alternative solution?

Any help or additional information, please ask.

Thanks

Contact Form 7

My Choice - Step 4

Select 'ONE' procedure [radio procedure use_label_element "Mesh Tape" "Colposuspension" "Natural Tissue Sling" "Urethra Bulking Agent Injection"]

[group mesh-selected clear_on_hide]
    Statement 1 [text mesh-mesh1 use_label_element placeholder"Reason Why"]
    Statement 2 [text mesh-colp1 use_label_element placeholder"Why I'm not"]
    Statement 3 [text mesh-sling1 use_label_element placeholder"Why I'm not"]
    Statement 4 [text mesh-ureth1 use_label_element placeholder"Why I'm not"]
[/group]
[group colp-selected clear_on_hide]
    Statement 1 [text colp-colp2 placeholder"Reason Why"]
    Statement 2 [text colp-mesh2 placeholder"Why I'm not"]
    Statement 3 [text colp-sling2 placeholder"Why I'm not"]
    Statement 4 [text colp-ureth2 placeholder"Why I'm not"]
[/group]
[group sling-selected clear_on_hide]
    Statement 1 [text sling-sling3 placeholder"Reason Why"]
    Statement 2 [text sling-colp3 placeholder"Why I'm not"]
    Statement 3 [text sling-mesh3 placeholder"Why I'm not"]
    Statement 4 [text sling-ureth3 placeholder"Why I'm not"]
[/group]
[group ureth-selected clear_on_hide]
    Statement 1 [text ureth-ureth4 placeholder"Reason Why I'm"]
    Statement 2 [text ureth-sling4 placeholder"Why I'm not"]
    Statement 3 [text ureth-colp4 placeholder"Why I'm not"]
    Statement 4 [text ureth-mesh4 placeholder"Why I'm not"]
[/group]

Conditional Logic

show [mesh-selected] if [procedure] equals "Mesh Tape"
show [colp-selected] if [procedure] equals "Colposuspension"
show [sling-selected] if [procedure] equals "Natural Tissue Sling"
show [ureth-selected] if [procedure] equals "Urethral Bulking Agent Injection"

PDF Form Layout

MY CHOICE
---------
Chosen Procedure: [procedure][mesh-selected]
[mesh-mesh1]
[mesh-colp1]
[mesh-sling1]
[mesh-ureth1]
[/mesh-selected][colp-selected]
[colp-mesh2]
[colp-colp2]
[colp-sling2]
[colp-ureth2]
[/colp-selected][sling-selected]
[sling-mesh3]
[sling-colp3]
[sling-sling3]
[sling-ureth3]
[/sling-selected][ureth-selected]
[ureth-mesh4]
[ureth-colp4]
[ureth-sling4]
[ureth-ureth4]
[/ureth-selected]

PDF Screenshot

Shows some random characters that were entered into one field section & the [group][/group] tags that are unfortunately displaying:

Body:
Your conditional tags are closed on your form structure like this:

[group group-394][/group]

But in the PDF you need to close tags like this:

[group-394][/group-394]

This way you can hide separate texts along with the question.


问:
Pushing to one element in a nested array is adding to all elements in javascript
I am creating a prefilled nested array and want to push elements to specific indexes, but the elements are being added to all indexes.

```<code>let arr = new Array(4).fill([])
arr => Array(4) [ [], [], [], [] ] //this is what I want
arr[0].push(3)
arr => Array(4) [ [3], [3], [3], [3] ] //I only wanted to push 3 to first index,
//why do all indexes have this element?
</code>```

Any help on how to just update one index would be appreciated.

答:
```<code>let arr = new Array(4).fill([])
</code>```

This is creating arr as an array of four references to the same array ([] passed as argument). Thus, modifying any of the references modifies the underlying array, and since it's referenced by all of them, you will notice this when logging the object.

```<code>> arr[0] === arr[1]
< true
</code>```

Just use a good ol' for, or even simply [[],[],[],[]] if we are just talking about 4 elements.

```<code>let arr = new Array(4)

for (let i = 0; i < arr.length; i++)
    arr[i] = new Array()
</code>```
```<code>> arr[0] === arr[1]
< false
</code>```

Body:
I am creating a prefilled nested array and want to push elements to specific indexes, but the elements are being added to all indexes.

let arr = new Array(4).fill([])
arr => Array(4) [ [], [], [], [] ] //this is what I want
arr[0].push(3)
arr => Array(4) [ [3], [3], [3], [3] ] //I only wanted to push 3 to first index,
//why do all indexes have this element?

Any help on how to just update one index would be appreciated.

Body:
let arr = new Array(4).fill([])

This is creating arr as an array of four references to the same array ([] passed as argument). Thus, modifying any of the references modifies the underlying array, and since it's referenced by all of them, you will notice this when logging the object.

> arr[0] === arr[1]
< true

Just use a good ol' for, or even simply [[],[],[],[]] if we are just talking about 4 elements.

let arr = new Array(4)

for (let i = 0; i < arr.length; i++)
    arr[i] = new Array()

> arr[0] === arr[1]
< false


问:
Toast not show in OnItemCLick
```<code>package com.custom;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    ListView list;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("", "on create");
        ListView list = (ListView)findViewById(R.id.list);

        List<PhoneList> listOfPhonebook = new ArrayList<PhoneList>();
        listOfPhonebook.add(new PhoneList("Sutadi","9898989", "Jl.Pasar"));
        listOfPhonebook.add(new PhoneList("Iyand","1234455", "Jl.Mall"));
        listOfPhonebook.add(new PhoneList("Yanti","00000", "Jl.Sawah"));
        Log.v("", "Add phone list");

        PhoneBookAdapter adapter = new PhoneBookAdapter(this, listOfPhonebook);
        Log.v("", "Adapter create");

        list.setAdapter(adapter);
        Log.v("", "adapter implement");

    list.setOnItemClickListener(new OnItemClickListener() {

        @Override

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), "You clciked ", Toast.LENGTH_LONG).show();

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

why the toast can not show ? anyone can help me ?

This is my PhoneBookAdapter

```<code>package com.custom;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class PhoneBookAdapter extends BaseAdapter{
    private Context context;

    private List<PhoneList> listPhonebook;

    public PhoneBookAdapter(Context context, List<PhoneList> listPhonebook) {
        this.context = context;
        this.listPhonebook = listPhonebook;
    }

    public int getCount() {
        return listPhonebook.size();
    }

    public Object getItem(int position) {
        return listPhonebook.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup viewGroup) {
        PhoneList entry = listPhonebook.get(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.row, null);
        }
        TextView tvContact = (TextView) convertView.findViewById(R.id.textstatus);
        tvContact.setText(entry.getName());

        TextView tvPhone = (TextView) convertView.findViewById(R.id.textkonos);
        tvPhone.setText(entry.getPhone());

        TextView tvAlamat = (TextView) convertView.findViewById(R.id.textalamat);
        tvAlamat.setText(entry.getAlamat());

        return convertView;
    }

}
</code>```

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Custom"
    android:textSize="10pt"
    android:paddingBottom="7px"
    android:background="#d5d5d5"
    android:textColor="#000000"
    />
<ListView
    android:paddingLeft="2px"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/list"
></ListView>

</LinearLayout>
</code>```

row.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"

    android:padding="6dip">

    <CheckBox android:text=""
    android:layout_width="wrap_content"
    android:id="@+id/checkBox1"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"></CheckBox>

    <TextView
    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textnama"
            android:padding="7px"
            android:layout_alignParentLeft="true"
            android:text="Konos : "/>

    <TextView
       android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textstatus"
            android:singleLine="true"
            android:padding="7px"

            android:layout_below="@+id/textnama"
            android:layout_alignParentLeft="true"
            android:text="haha"/>

     <TextView android:layout_width="wrap_content"
     android:text="hohohoho"
     android:layout_height="wrap_content"
     android:id="@+id/textkonos"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_above="@+id/textstatus"
     android:layout_toRightOf="@+id/textnama"></TextView>

    <TextView android:layout_width="wrap_content"
     android:text="-"
     android:layout_height="wrap_content"
     android:id="@+id/text"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_below="@+id/textkonos"
     android:layout_toRightOf="@+id/textstatus"></TextView>

     <TextView android:layout_width="wrap_content"
     android:text=""
     android:layout_height="wrap_content"
     android:id="@+id/textalamat"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_alignParentBottom="true"
     android:layout_alignLeft="@+id/textkonos"></TextView>

</RelativeLayout>
</code>```

答:
```<code>Toast.makeText(getApplicationContext(), "You clicked ", Toast.LENGTH_LONG).show();
</code>```

Title: Toast not show in OnItemCLick

Body:
package com.custom;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    ListView list;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("", "on create");
        ListView list = (ListView)findViewById(R.id.list);

        List<PhoneList> listOfPhonebook = new ArrayList<PhoneList>();
        listOfPhonebook.add(new PhoneList("Sutadi","9898989", "Jl.Pasar"));
        listOfPhonebook.add(new PhoneList("Iyand","1234455", "Jl.Mall"));
        listOfPhonebook.add(new PhoneList("Yanti","00000", "Jl.Sawah"));
        Log.v("", "Add phone list");

        PhoneBookAdapter adapter = new PhoneBookAdapter(this, listOfPhonebook);
        Log.v("", "Adapter create");

        list.setAdapter(adapter);
        Log.v("", "adapter implement");

    list.setOnItemClickListener(new OnItemClickListener() {

        @Override

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), "You clciked ", Toast.LENGTH_LONG).show();

    }
    });
    }
}

why the toast can not show ? anyone can help me ?

This is my PhoneBookAdapter

package com.custom;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class PhoneBookAdapter extends BaseAdapter{
    private Context context;

    private List<PhoneList> listPhonebook;

    public PhoneBookAdapter(Context context, List<PhoneList> listPhonebook) {
        this.context = context;
        this.listPhonebook = listPhonebook;
    }

    public int getCount() {
        return listPhonebook.size();
    }

    public Object getItem(int position) {
        return listPhonebook.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup viewGroup) {
        PhoneList entry = listPhonebook.get(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.row, null);
        }
        TextView tvContact = (TextView) convertView.findViewById(R.id.textstatus);
        tvContact.setText(entry.getName());

        TextView tvPhone = (TextView) convertView.findViewById(R.id.textkonos);
        tvPhone.setText(entry.getPhone());

        TextView tvAlamat = (TextView) convertView.findViewById(R.id.textalamat);
        tvAlamat.setText(entry.getAlamat());

        return convertView;
    }

}

main.xml

<?xml version="1.0" encoding="utf-8"?>

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Custom"
    android:textSize="10pt"
    android:paddingBottom="7px"
    android:background="#d5d5d5"
    android:textColor="#000000"
    />
<ListView
    android:paddingLeft="2px"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/list"
></ListView>

</LinearLayout>

row.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"

    android:padding="6dip">

    <CheckBox android:text=""
    android:layout_width="wrap_content"
    android:id="@+id/checkBox1"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"></CheckBox>

    <TextView
    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textnama"
            android:padding="7px"
            android:layout_alignParentLeft="true"
            android:text="Konos : "/>

    <TextView
       android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textstatus"
            android:singleLine="true"
            android:padding="7px"

            android:layout_below="@+id/textnama"
            android:layout_alignParentLeft="true"
            android:text="haha"/>

     <TextView android:layout_width="wrap_content"
     android:text="hohohoho"
     android:layout_height="wrap_content"
     android:id="@+id/textkonos"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_above="@+id/textstatus"
     android:layout_toRightOf="@+id/textnama"></TextView>

    <TextView android:layout_width="wrap_content"
     android:text="-"
     android:layout_height="wrap_content"
     android:id="@+id/text"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_below="@+id/textkonos"
     android:layout_toRightOf="@+id/textstatus"></TextView>

     <TextView android:layout_width="wrap_content"
     android:text=""
     android:layout_height="wrap_content"
     android:id="@+id/textalamat"
     android:paddingRight="3px"
     android:padding="7px"
     android:layout_alignParentBottom="true"
     android:layout_alignLeft="@+id/textkonos"></TextView>

</RelativeLayout>


问:
Why is it that this form is being submitted twice?
I am trying to understand why the form in the following snippet is submitted multiple times, after following the steps:

Click one of the submit buttons. A confirmation div will appear.

Click the Cancel button in the confirmation.

Now click the other submit button.

Click the Yes button in the confirmation.

The console log shows that the form submission handler is fired twice.

Can anyone help me see how/why this is happening, so that I can prevent multiple submissions?

const $form = $("#form-test");
const $confirm = $("#confirm");

$form.on("submit", function (e, $btn) {
    e.preventDefault();
    console.log("Submitting!", $btn);
});

$confirm.find("button").on("click", function () {
    $confirm.hide();
});

$form.find("button").on("click", function (e) {
    const $btn = $(this);

    $("#btn-yes").one("click", function () {
        $form.trigger("submit", $btn);
    });

    $("#btn-cancel").one("click", function () {
        console.log("Cancelled!", this);
    });

    $confirm.show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#form-container, #confirm {
  border: 1px solid #000;
  padding: 10px;
}

#confirm {
  display: none;
}</code>```

    Are you sure?
    <button id="btn-cancel" type="button">Cancel</button>
    <button id="btn-yes" type="button">Yes</button>

    <form id="form-test">
        <input type="text" name="test" value="Foo">
        <button type="button">Submit 1</button>
        <button type="button">Submit 2</button>
    </form>

```

答:
You are running the following:

```<code>$("#btn-yes").one("click", function () {
    $form.trigger("submit", $btn);
});
</code>```

inside the $form.find("button").on("click" handler. If you click into the buttons twice, you'll be adding the handler twice.

Either remove the previous handler before adding the new one, or add the yes/cancel handlers outside (there's no need for them to be added inside the click handler).

const $form = $("#form-test");
const $confirm = $("#confirm");

$form.on("submit", function(e) {
  e.preventDefault();
  console.log("Submitting!");
});

$confirm.find("button").on("click", function() {
  $confirm.hide();
});

$("#btn-yes").one("click", function() {
  $form.trigger("submit");
});
$("#btn-cancel").one("click", function() {
  console.log("Cancelled!", this);
});
$form.find("button").on("click", function() {
  $confirm.show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#form-container,
#confirm {
  border: 1px solid #000;
  padding: 10px;
}

#confirm {
  display: none;
}</code>```

  Are you sure?
  <button id="btn-cancel" type="button">Cancel</button>
  <button id="btn-yes" type="button">Yes</button>

  <form id="form-test">
    <input type="text" name="test" value="Foo">
    <button type="button">Submit 1</button>
    <button type="button">Submit 2</button>
  </form>

```

Body:
I am trying to understand why the form in the following snippet is submitted multiple times, after following the steps:

Click one of the submit buttons. A confirmation div will appear.

Click the Cancel button in the confirmation.

Now click the other submit button.

Click the Yes button in the confirmation.

The console log shows that the form submission handler is fired twice.

Can anyone help me see how/why this is happening, so that I can prevent multiple submissions?

const $form = $("#form-test");
const $confirm = $("#confirm");

$form.on("submit", function (e, $btn) {
    e.preventDefault();
    console.log("Submitting!", $btn);
});

$confirm.find("button").on("click", function () {
    $confirm.hide();
});

$form.find("button").on("click", function (e) {
    const $btn = $(this);

    $("#btn-yes").one("click", function () {
        $form.trigger("submit", $btn);
    });

    $("#btn-cancel").one("click", function () {
        console.log("Cancelled!", this);
    });

    $confirm.show();
});

#form-container, #confirm {
  border: 1px solid #000;
  padding: 10px;
}

#confirm {
  display: none;
}

    Are you sure?
    <button id="btn-cancel" type="button">Cancel</button>
    <button id="btn-yes" type="button">Yes</button>

    <form id="form-test">
        <input type="text" name="test" value="Foo">
        <button type="button">Submit 1</button>
        <button type="button">Submit 2</button>
    </form>

Body:
You are running the following:

$("#btn-yes").one("click", function () {
    $form.trigger("submit", $btn);
});

inside the $form.find("button").on("click" handler. If you click into the buttons twice, you'll be adding the handler twice.

Either remove the previous handler before adding the new one, or add the yes/cancel handlers outside (there's no need for them to be added inside the click handler).

const $form = $("#form-test");
const $confirm = $("#confirm");

$form.on("submit", function(e) {
  e.preventDefault();
  console.log("Submitting!");
});

$confirm.find("button").on("click", function() {
  $confirm.hide();
});

$("#btn-yes").one("click", function() {
  $form.trigger("submit");
});
$("#btn-cancel").one("click", function() {
  console.log("Cancelled!", this);
});
$form.find("button").on("click", function() {
  $confirm.show();
});

#form-container,
#confirm {
  border: 1px solid #000;
  padding: 10px;
}

#confirm {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="confirm">
  Are you sure?
  <button id="btn-cancel" type="button">Cancel</button>
  <button id="btn-yes" type="button">Yes</button>
</div>

<div id="form-container">
  <form id="form-test">
    <input type="text" name="test" value="Foo">
    <button type="button">Submit 1</button>
    <button type="button">Submit 2</button>
  </form>
</div>


问:
Not able to change TextField Border Color
I am trying to change color of the border of my TextField using a BorderSide, but it does not work.

This is my code below.

new TextField(
  decoration: new InputDecoration(
    border: new OutlineInputBorder(
      borderSide: new BorderSide(color: Colors.teal)
    ),
    hintText: 'Tell us about yourself',
    helperText: 'Keep it short, this is just a demo.',
    labelText: 'Life story',
    prefixIcon: const Icon(Icons.person, color: Colors.green,),
    prefixText: ' ',
    suffixText: 'USD',
    suffixStyle: const TextStyle(color: Colors.green)),
  )
)
```

Screenshot of the result is shown below.

答:
```<code>border: OutlineInputBorder(borderSide: BorderSide(color: CustomColors.primaryColor),),
</code>```

Body:
I am trying to change color of the border of my TextField using a BorderSide, but it does not work.

This is my code below.

new TextField(
  decoration: new InputDecoration(
    border: new OutlineInputBorder(
      borderSide: new BorderSide(color: Colors.teal)
    ),
    hintText: 'Tell us about yourself',
    helperText: 'Keep it short, this is just a demo.',
    labelText: 'Life story',
    prefixIcon: const Icon(Icons.person, color: Colors.green,),
    prefixText: ' ',
    suffixText: 'USD',
    suffixStyle: const TextStyle(color: Colors.green)),
  )
)

Screenshot of the result is shown below.


问:
How to parse nested JSON object?
I am working on a new project in HubSpot that returns nested JSON like the sample below. I am trying to access the associated contacts id, but am struggling to reference it correctly (the id I am looking for is the value '201' in the example below). I've put together this script, but this script only returns the entire associations portion of the JSON and I only want the id. How do I reference the id correctly?

Here is the output from the script:

```<code>{'contacts': {'paging': None, 'results': [{'id': '201', 'type': 'ticket_to_contact'}]}}
</code>```

And here is the script I put together:

```<code>import hubspot
from pprint import pprint

client = hubspot.Client.create(api_key="API_KEY")

try:
    api_response = client.crm.tickets.basic_api.get_page(limit=2, associations=["contacts"], archived=False)

    for x in range(2):
        pprint(api_response.results[x].associations)

except ApiException as e:
    print("Exception when calling basic_api->get_page: %s\n" % e)
</code>```

Here is what the full JSON looks like ('contacts' property shortened for readability):

```<code>{
  "results": [
    {
      "id": "34018123",
      "properties": {
        "content": "Hi xxxxx,\r\n\r\nCan you clarify on how the blocking of script happens? Is it because of any CSP (or) the script will decide run time for every URL’s getting triggered from browser?\r\n\r\nRegards,\r\nLogan",
        "createdate": "2019-07-03T04:20:12.366Z",
        "hs_lastmodifieddate": "2020-12-09T01:16:12.974Z",
        "hs_object_id": "34018123",
        "hs_pipeline": "0",
        "hs_pipeline_stage": "4",
        "hs_ticket_category": null,
        "hs_ticket_priority": null,
        "subject": "RE: call followup"
      },
      "createdAt": "2019-07-03T04:20:12.366Z",
      "updatedAt": "2020-12-09T01:16:12.974Z",
      "archived": false
    },
    {
      "id": "34018892",
      "properties": {
        "content": "Hi Guys,\r\n\r\nI see that we were placed back on the staging and then removed again.",
        "createdate": "2019-07-03T07:59:10.606Z",
        "hs_lastmodifieddate": "2021-12-17T09:04:46.316Z",
        "hs_object_id": "34018892",
        "hs_pipeline": "0",
        "hs_pipeline_stage": "3",
        "hs_ticket_category": null,
        "hs_ticket_priority": null,
        "subject": "Re: Issue due to server"
      },
      "createdAt": "2019-07-03T07:59:10.606Z",
      "updatedAt": "2021-12-17T09:04:46.316Z",
      "archived": false,
      "associations": {
        "contacts": {
          "results": [
            {
              "id": "201",
              "type": "ticket_to_contact"
            }
          ]
        }
      }
    }
  ],
  "paging": {
    "next": {
      "after": "35406270",
      "link": "https://api.hubapi.com/crm/v3/objects/tickets?associations=contacts&archived=false&hs_static_app=developer-docs-ui&limit=2&after=35406270&hs_static_app_version=1.3488"
    }
  }
}
</code>```

答:
In my case type was ModelProperty or CollectionResponseProperty couldn't reach dict anyhow.

For the record this got me to go through the results.

```<code>for result in list(api_response.results):
   ID = result.id
</code>```

Title: How to parse nested JSON object?

Body:
I am working on a new project in HubSpot that returns nested JSON like the sample below. I am trying to access the associated contacts id, but am struggling to reference it correctly (the id I am looking for is the value '201' in the example below). I've put together this script, but this script only returns the entire associations portion of the JSON and I only want the id. How do I reference the id correctly?

Here is the output from the script:

{'contacts': {'paging': None, 'results': [{'id': '201', 'type': 'ticket_to_contact'}]}}

And here is the script I put together:

import hubspot
from pprint import pprint

client = hubspot.Client.create(api_key="API_KEY")

try:
    api_response = client.crm.tickets.basic_api.get_page(limit=2, associations=["contacts"], archived=False)

    for x in range(2):
        pprint(api_response.results[x].associations)

except ApiException as e:
    print("Exception when calling basic_api->get_page: %s\n" % e)

Here is what the full JSON looks like ('contacts' property shortened for readability):

{
  "results": [
    {
      "id": "34018123",
      "properties": {
        "content": "Hi xxxxx,\r\n\r\nCan you clarify on how the blocking of script happens? Is it because of any CSP (or) the script will decide run time for every URL’s getting triggered from browser?\r\n\r\nRegards,\r\nLogan",
        "createdate": "2019-07-03T04:20:12.366Z",
        "hs_lastmodifieddate": "2020-12-09T01:16:12.974Z",
        "hs_object_id": "34018123",
        "hs_pipeline": "0",
        "hs_pipeline_stage": "4",
        "hs_ticket_category": null,
        "hs_ticket_priority": null,
        "subject": "RE: call followup"
      },
      "createdAt": "2019-07-03T04:20:12.366Z",
      "updatedAt": "2020-12-09T01:16:12.974Z",
      "archived": false
    },
    {
      "id": "34018892",
      "properties": {
        "content": "Hi Guys,\r\n\r\nI see that we were placed back on the staging and then removed again.",
        "createdate": "2019-07-03T07:59:10.606Z",
        "hs_lastmodifieddate": "2021-12-17T09:04:46.316Z",
        "hs_object_id": "34018892",
        "hs_pipeline": "0",
        "hs_pipeline_stage": "3",
        "hs_ticket_category": null,
        "hs_ticket_priority": null,
        "subject": "Re: Issue due to server"
      },
      "createdAt": "2019-07-03T07:59:10.606Z",
      "updatedAt": "2021-12-17T09:04:46.316Z",
      "archived": false,
      "associations": {
        "contacts": {
          "results": [
            {
              "id": "201",
              "type": "ticket_to_contact"
            }
          ]
        }
      }
    }
  ],
  "paging": {
    "next": {
      "after": "35406270",
      "link": "https://api.hubapi.com/crm/v3/objects/tickets?associations=contacts&archived=false&hs_static_app=developer-docs-ui&limit=2&after=35406270&hs_static_app_version=1.3488"
    }
  }
}

Body:
In my case type was ModelProperty or CollectionResponseProperty couldn't reach dict anyhow.

For the record this got me to go through the results.

for result in list(api_response.results):
   ID = result.id


问:
Conditional context manager and decorator in Python
I have the following Python code littered throughout my code base which profiles a code block and sends the results to a monitoring solution if the SHOULD_PROFILE environment variable is set.

```<code>from contextlib import ExitStack

with ExitStack() as stack:
    if os.environ.get("SHOULD_PROFILE"):
        stack.enter_context(profile())
    ...
</code>```

I would like to consolidate this snippet into a single context manager / decorator so it can be used as a context manager AND a decorator:

```<code>with profile_if_enabled():
    ...

# AND

@profile_if_enabled()
def func():
    ....
</code>```

This is what I've come up with but it isn't working.

```<code>from contextlib import ContextDecorator, ExitStack

class profile_if_enabled(ContextDecorator):
    def __enter__(self):
        with ExitStack() as stack:
            if os.environ.get("SHOULD_PROFILE"):
                stack.enter_context(profile())
            return self

    def __exit__(self, *exc):
        return False
</code>```

Any idea what I'm doing wrong?

答:
Figured it out using the contextmanager decorator:</p>
```<code>import os
from contextlib import ExitStack, contextmanager

@contextmanager
def profile_if_enabled():
    with ExitStack() as stack:
        if os.environ.get("SHOULD_PROFILE"):
            stack.enter_context(profile())
        yield
</code>```

Body:
I have the following Python code littered throughout my code base which profiles a code block and sends the results to a monitoring solution if the SHOULD_PROFILE environment variable is set.

from contextlib import ExitStack

with ExitStack() as stack:
    if os.environ.get("SHOULD_PROFILE"):
        stack.enter_context(profile())
    ...

I would like to consolidate this snippet into a single context manager / decorator so it can be used as a context manager AND a decorator:

with profile_if_enabled():
    ...

# AND

@profile_if_enabled()
def func():
    ....

This is what I've come up with but it isn't working.

from contextlib import ContextDecorator, ExitStack

class profile_if_enabled(ContextDecorator):
    def __enter__(self):
        with ExitStack() as stack:
            if os.environ.get("SHOULD_PROFILE"):
                stack.enter_context(profile())
            return self

    def __exit__(self, *exc):
        return False

Any idea what I'm doing wrong?

Body:
Figured it out using the contextmanager decorator:

import os
from contextlib import ExitStack, contextmanager

@contextmanager
def profile_if_enabled():
    with ExitStack() as stack:
        if os.environ.get("SHOULD_PROFILE"):
            stack.enter_context(profile())
        yield


问:
For python's built-in sort()'s key parameter, when to use base class vs object as identifier?
Let me take an example to clarify what I am talking about.

Say I'm trying to sort() a string s with a key of count (frequency of letters) and in a different case, with a key of lower.

Now, for count, it is required that I use the variable (object) identifier s as follows

"".join(sorted(s, key=s.count))
```
<p>While, for <code>lower</code>, it is required that I use the base class identifier <code>str</code> as follows</p>
<pre class="lang-py prettyprint-override"><code>"".join(sorted(s, key=str.lower))
</code>```

I want to understand why is the usage different in these two examples? And for other methods, how should I understand which identifier to use?

答:
The key parameter takes a function which takes a single argument which is an item in the list. For methods of a class like str, their methods have the signatures

def count(self, x):
    ...
def lower(self):
    ...
```

In particular, the both have self as the first argument. If you create an instance of the class, the first argument is "bound" to that instance, which basically passes in that instance for self when you call it. Then, calling s.count(x) is the same as str.count(s, x), and str.lower(s) passes in s as self, and it's the same as s.lower().

For the sorting example, passing in key=s.count means you want to sort the string based on the number of times a character appears in the string. For each character x of s, it calls s.count(x).

When key=str.lower, it sorts the string based on the lowercase value of each character, and it is the same as calling x.lower() for each character x in s.

Body:
Let me take an example to clarify what I am talking about.

Say I'm trying to sort() a string s with a key of count (frequency of letters) and in a different case, with a key of lower.

Now, for count, it is required that I use the variable (object) identifier s as follows

"".join(sorted(s, key=s.count))

While, for lower, it is required that I use the base class identifier str as follows

"".join(sorted(s, key=str.lower))

I want to understand why is the usage different in these two examples? And for other methods, how should I understand which identifier to use?

Body:
The key parameter takes a function which takes a single argument which is an item in the list. For methods of a class like str, their methods have the signatures

def count(self, x):
    ...
def lower(self):
    ...

In particular, the both have self as the first argument. If you create an instance of the class, the first argument is "bound" to that instance, which basically passes in that instance for self when you call it. Then, calling s.count(x) is the same as str.count(s, x), and str.lower(s) passes in s as self, and it's the same as s.lower().

For the sorting example, passing in key=s.count means you want to sort the string based on the number of times a character appears in the string. For each character x of s, it calls s.count(x).

When key=str.lower, it sorts the string based on the lowercase value of each character, and it is the same as calling x.lower() for each character x in s.


问:
How to iterate mutli-dimensional arrays in Python?
Community.
I'm working with a Pandas Dataframe and I've reached a point where I need to sample two columns from the DataFrame. I want to do this by converting the sample to a multi-dimensional array but I do not know how to go from there. This is what I have done so far:

```<code>for i,j in abcarray:
    if 'positive' in j:
        print(abcarray[i])
        get_image("img1")
    elif 'negative' in j:
        print(abcarray[i])
        get_image("img2")
    elif 'neutral' in j:
        print(abcarray[i])
        get_image("img3")
</code>```

This is only supposed to print the ith element while the jth element is whatever I've specified.
Now usually in Java, I could have a counter variable that iterates through the rows, but how do you do this in Python? I know that I could use "range(len(abcarray))" but it still doesn't help. I'm very new to Python but I have to use Python for this for obvious reasons.

Edit:
Adding a bit more context here after the first few replies.
So get_image is a function that checks the value and returns the appropriate image. That part of the code works absolutely fine so I did not include that.

The Dataframe is from a CSV but the sample looks like this

["Review Review Review Text Text Text Text" 'positive'] ["Review Review Review Text Text Text Text" 'negative'] ["Review Review Review Text Text Text Text" 'neutral'] ["Review Review Review Text Text Text Text" 'positive'] ["Review Review Review Text Text Text Text" 'positive']

答:
I've taken a stab at what I think you're trying to do. The key is that you've got a nested list which is something like:

```<code>myList = [['review is like this', 'positive'],
          ['i dont like', 'negative'],
          ['meh','neutral']]
</code>```

Doing a for loop the way you've done is not how it's done in python. For loops iterate over objects (such as lists and arrays) and return the element that it's currently up to (which can be any data type). If you want to return the index that it's up to you can either use the range(len(list)) method which you've mentioned , or use

```<code>for ix, i in enumerate(myList):
     ...
</code>```

which returns the index ix and the element of the list i.

In regards to your problem, I assume you just want something as simple as:

```<code>def get_image(string):
    #dummy function which just shows which image is being called
    print(string)

for i in myList:
    print(i[0]) #this is the same no matter the if statement
    if 'positive' in i:
        get_image("img1")
    elif 'negative' in i:
        get_image("img2")
    elif 'neutral' in i:
        get_image("img3")
</code>```

Which outputs:

```<code>review is like this
img1
i dont like
img2
meh
img3
</code>```

Body:
Community.
I'm working with a Pandas Dataframe and I've reached a point where I need to sample two columns from the DataFrame. I want to do this by converting the sample to a multi-dimensional array but I do not know how to go from there. This is what I have done so far:

for i,j in abcarray:
    if 'positive' in j:
        print(abcarray[i])
        get_image("img1")
    elif 'negative' in j:
        print(abcarray[i])
        get_image("img2")
    elif 'neutral' in j:
        print(abcarray[i])
        get_image("img3")

This is only supposed to print the ith element while the jth element is whatever I've specified.
Now usually in Java, I could have a counter variable that iterates through the rows, but how do you do this in Python? I know that I could use "range(len(abcarray))" but it still doesn't help. I'm very new to Python but I have to use Python for this for obvious reasons.

Edit:
Adding a bit more context here after the first few replies.
So get_image is a function that checks the value and returns the appropriate image. That part of the code works absolutely fine so I did not include that.

The Dataframe is from a CSV but the sample looks like this

["Review Review Review Text Text Text Text" 'positive'] ["Review Review Review Text Text Text Text" 'negative'] ["Review Review Review Text Text Text Text" 'neutral'] ["Review Review Review Text Text Text Text" 'positive'] ["Review Review Review Text Text Text Text" 'positive']

Body:
I've taken a stab at what I think you're trying to do. The key is that you've got a nested list which is something like:

myList = [['review is like this', 'positive'],
          ['i dont like', 'negative'],
          ['meh','neutral']]

Doing a for loop the way you've done is not how it's done in python. For loops iterate over objects (such as lists and arrays) and return the element that it's currently up to (which can be any data type). If you want to return the index that it's up to you can either use the range(len(list)) method which you've mentioned , or use

for ix, i in enumerate(myList):
     ...

which returns the index ix and the element of the list i.

In regards to your problem, I assume you just want something as simple as:

def get_image(string):
    #dummy function which just shows which image is being called
    print(string)

for i in myList:
    print(i[0]) #this is the same no matter the if statement
    if 'positive' in i:
        get_image("img1")
    elif 'negative' in i:
        get_image("img2")
    elif 'neutral' in i:
        get_image("img3")

Which outputs:

review is like this
img1
i dont like
img2
meh
img3


问:
Why my kotlin suspend function don't throw error? And continue to nextline?
This is my code in my viewModel which calls the function.

```<code>viewModelScope.launch {
        resource.postValue(Resource.loading(true))
        try {
            localRepository.insertFile(fileEntity)
///This lines throw exeption
            messageRepository.sendMessageWithMediaAudio(message, mediaUri,        duration)
///But still continue to this line and don't catch the error
            resource.postValue(Resource.success(true))
        } catch (exception: Exception) {
            Timber.e(exception)
            resource.postValue(
                Resource.error(exception, exception.message!!)
            )
        }
    }
</code>```

I want to catch the error but it wont go to catch.

This is the suspend function

```<code>  suspend fun sendMessageWithMediaAudio(message: Message, uri: Uri, duration: Long) =
    withContext(ioDispatcher) {
        applicationScope.launch{Body}.join()
 }
</code>```

答:
It is because of this line:

applicationScope.launch {
    Body
}
```
<p>You are launching a new coroutine in a different coroutine scope. <code>sendMessageWithMediaAudio</code> returns before the <code>Body</code> completes. If you want to wait until <code>sendMessageWithMediaAudio</code> completes (which probably is what you want looking at the call to <code>.join()</code>), don't use <code>applicationScope</code>, just launch the new coroutine in the scope provided by <code>withContext</code>.</p>
<p>Also, launching a new coroutine and immediately waiting for it to complete (<code>.join()</code>) isn't of any use. You can simply put the <code>Body</code> directly inside <code>withContext</code>.</p>
<pre class="lang-kotlin prettyprint-override"><code>suspend fun sendMessageWithMediaAudio(message: Message, uri: Uri, duration: Long) {
    withContext(ioDispatcher) {
        Body
    }
}
</code>```

Body:
This is my code in my viewModel which calls the function.

viewModelScope.launch {
        resource.postValue(Resource.loading(true))
        try {
            localRepository.insertFile(fileEntity)
///This lines throw exeption
            messageRepository.sendMessageWithMediaAudio(message, mediaUri,        duration)
///But still continue to this line and don't catch the error
            resource.postValue(Resource.success(true))
        } catch (exception: Exception) {
            Timber.e(exception)
            resource.postValue(
                Resource.error(exception, exception.message!!)
            )
        }
    }

I want to catch the error but it wont go to catch.

This is the suspend function

  suspend fun sendMessageWithMediaAudio(message: Message, uri: Uri, duration: Long) =
    withContext(ioDispatcher) {
        applicationScope.launch{Body}.join()
 }

Body:
It is because of this line:

applicationScope.launch {
    Body
}

You are launching a new coroutine in a different coroutine scope. sendMessageWithMediaAudio returns before the Body completes. If you want to wait until sendMessageWithMediaAudio completes (which probably is what you want looking at the call to .join()), don't use applicationScope, just launch the new coroutine in the scope provided by withContext.

Also, launching a new coroutine and immediately waiting for it to complete (.join()) isn't of any use. You can simply put the Body directly inside withContext.

suspend fun sendMessageWithMediaAudio(message: Message, uri: Uri, duration: Long) {
    withContext(ioDispatcher) {
        Body
    }
}