问:
How to assign a function to a tkinter button?
I want to assign a print function in tkinter Button, but something goes wrong.

What should I improve?

```<code>from tkinter import *
import random

text = random.randint(1, 5)
root = Tk()
root.geometry('550x350')
btn = Button(root, text = 'random', bd = '5'
             command = lambda: btn(print(text))

btn.pack(side = 'top')
root.mainloop()
</code>```

答:
Small error there, btn is not defined within the lambda function, you can simply print(text) there.

```<code>btn = Button(root, text = 'random', bd = '5', command = lambda: print(text))
</code>```

if you want to have a random number on every click you can do the following

```<code>btn = Button(root, text = 'random', bd = '5', command = lambda: print(random.randint(1, 5)))
</code>```

Body:
I want to assign a print function in tkinter Button, but something goes wrong.

What should I improve?

from tkinter import *
import random

text = random.randint(1, 5)
root = Tk()
root.geometry('550x350')
btn = Button(root, text = 'random', bd = '5'
             command = lambda: btn(print(text))

btn.pack(side = 'top')
root.mainloop()

Body:
Small error there, btn is not defined within the lambda function, you can simply print(text) there.

btn = Button(root, text = 'random', bd = '5', command = lambda: print(text))

if you want to have a random number on every click you can do the following

btn = Button(root, text = 'random', bd = '5', command = lambda: print(random.randint(1, 5)))


来源: stackexchange

问:
Why might the host behave more deterministic than a docker container?
We use Docker to well define the build environment and help with deterministic builds but on my machine I get a tiny change in the build results using Docker but not when not using Docker.

I did pretty extensive testing and am out of ideas :(

I tested on the following systems:

A: My new PC without Docker

AD1: My new PC with Docker, using our Dockerfile based on ubuntu:18.04 compiled "a year ago"

AD2: My new PC with Docker, using our Dockerfile based on ubuntu:19:10 compiled now

B: My laptop (that I had copied the disk from to my new PC) without Docker

BD: My laptop with Docker

CD1: Co-worker's laptop with Docker, using our Dockerfile based on ubuntu:18.04 compiled "a year ago"

CD2: Co-worker's laptop with Docker, using our Dockerfile based on ubuntu:19:10 compiled now

DD: A Digital Ocean VPS with our Dockerfile based on ubuntu:18.04 compiled now

In all scenarios we got either of two build results I will name variant X and Y.

We got variant X using A, B, CD1, CD2 and DD.

We got variant Y using AD1, AD2 and BD.

The issue keeps being 100% reproducible since several releases of our Android app. It did not go away when I updated my Docker from 19.03.6 to 19.03.8 to match my co-worker's version. We both had Ubuntu 19.10 back then and I now keep getting the issue with Ubuntu 20.04.

I always freshly cloned our project into a new folder, used disorderfs to eliminate file system sorting issues and mounted the folder into the docker container.

I doubt it's relevant but we are using this Dockerfile:

```<code>FROM ubuntu:18.04

RUN dpkg --add-architecture i386 && \
    apt-get update -y && \
    apt-get install -y software-properties-common && \
    apt-get update -y && \
    apt-get install -y wget \
            openjdk-8-jre-headless=8u162-b12-1 \
            openjdk-8-jre=8u162-b12-1 \
            openjdk-8-jdk-headless=8u162-b12-1 \
            openjdk-8-jdk=8u162-b12-1 \
            git unzip && \
    rm -rf /var/lib/apt/lists/* && \
    apt-get autoremove -y && \
    apt-get clean

# download and install Android SDK
ARG ANDROID_SDK_VERSION=4333796
ENV ANDROID_HOME /opt/android-sdk
RUN mkdir -p /opt/android-sdk && cd /opt/android-sdk && \
    wget -q https://dl.google.com/android/repository/sdk-tools-linux-${ANDROID_SDK_VERSION}.zip && \
    unzip *tools*linux*.zip && \
    rm *tools*linux*.zip && \
    yes | $ANDROID_HOME/tools/bin/sdkmanager --licenses
</code>```

Also here are the build instructions I run and get different results. The diff itself is can be found here.

Edit: I also filed it as a bug on the docker repo.

答:
Docker is not fully architecture-independent. For different architecture you may have more or less minute differences. Usually it should not affect anything important but may change some optimisation decisions of a compiler and such things. It is more visible if you try very different CPUs like AMD64 vs ARM. For Java it should not matter but it seems that at least sometimes it matters.

Another thing is network and DNS. When you do apt-get, wget and other such things then it downloads code or binary from network. It may differ depending on which DNS you use (which may lead to different server or different repo url) and there can be some minute differences. Theoretically there should be no difference but practically there can be difference sometimes like when they roll out new version and it's visible only on some nodes or something bad happened or you have some cache/proxy in between and connect through that and it caches etc.

Also the latter can create differences that appear in time. Like app is compiled on one month and someone tries to verify few weeks or months later and apt-get installs other versions of libraries and in effect there are minute differences.

I'm not sure which applies here but I have some ideas:

may try to make some small changes to the app so in effect it will again build same on most of popular CPU's, do extensive testing, and then list architectures on which it can be verified

make verification process a little more complex and non-free so users should have to run a server instance (on AWS or Google or Azure or Rackspace or other) with specified architecture and build and verify there - may try and specify on which types of machines exacly result will be the same and what are minimal requirements (as it may or may not run on free-plan instances)

check diff of created images content (not only apk but full system image), maybe there will be something important that differs between docker images on different machines producing different results

try to find as small as possible initial image and don't allow apt-get or other things automatically install dependencies with newest version but specify all dependencies and their versions

ContentLicense: CC BY-SA 4.0

Body:
We use Docker to well define the build environment and help with deterministic builds but on my machine I get a tiny change in the build results using Docker but not when not using Docker.

I did pretty extensive testing and am out of ideas :(

I tested on the following systems:

A: My new PC without Docker

AD1: My new PC with Docker, using our Dockerfile based on ubuntu:18.04 compiled "a year ago"

AD2: My new PC with Docker, using our Dockerfile based on ubuntu:19:10 compiled now

B: My laptop (that I had copied the disk from to my new PC) without Docker

BD: My laptop with Docker

CD1: Co-worker's laptop with Docker, using our Dockerfile based on ubuntu:18.04 compiled "a year ago"

CD2: Co-worker's laptop with Docker, using our Dockerfile based on ubuntu:19:10 compiled now

DD: A Digital Ocean VPS with our Dockerfile based on ubuntu:18.04 compiled now

In all scenarios we got either of two build results I will name variant X and Y.

We got variant X using A, B, CD1, CD2 and DD.

We got variant Y using AD1, AD2 and BD.

The issue keeps being 100% reproducible since several releases of our Android app. It did not go away when I updated my Docker from 19.03.6 to 19.03.8 to match my co-worker's version. We both had Ubuntu 19.10 back then and I now keep getting the issue with Ubuntu 20.04.

I always freshly cloned our project into a new folder, used disorderfs to eliminate file system sorting issues and mounted the folder into the docker container.

I doubt it's relevant but we are using this Dockerfile:

FROM ubuntu:18.04

RUN dpkg --add-architecture i386 && \
    apt-get update -y && \
    apt-get install -y software-properties-common && \
    apt-get update -y && \
    apt-get install -y wget \
            openjdk-8-jre-headless=8u162-b12-1 \
            openjdk-8-jre=8u162-b12-1 \
            openjdk-8-jdk-headless=8u162-b12-1 \
            openjdk-8-jdk=8u162-b12-1 \
            git unzip && \
    rm -rf /var/lib/apt/lists/* && \
    apt-get autoremove -y && \
    apt-get clean

# download and install Android SDK
ARG ANDROID_SDK_VERSION=4333796
ENV ANDROID_HOME /opt/android-sdk
RUN mkdir -p /opt/android-sdk && cd /opt/android-sdk && \
    wget -q https://dl.google.com/android/repository/sdk-tools-linux-${ANDROID_SDK_VERSION}.zip && \
    unzip *tools*linux*.zip && \
    rm *tools*linux*.zip && \
    yes | $ANDROID_HOME/tools/bin/sdkmanager --licenses

Also here are the build instructions I run and get different results. The diff itself is can be found here.

Edit: I also filed it as a bug on the docker repo.


问:
Django isn't creating db constraints for foreign keys with SQLite
I'm using Django 3.0.6

I'm adding ForeignKey and ManyToManyField to my models, but I've noticed that django creates the INDEX, but not the actual FOREIGN KEY constraints in the db.

I've tried to explicitly set db_constraint=True but as expected is useless, since it's True by default.

I've found so many answers explaining this, but only for very old Django versions, doing tricks for enabling it when it was otherwise disabled. Now instead it should just work out of the box. Couldn't find anything AT ALL regarding Django 3.

Code

```<code>class Token (models.Model):
    owner = models.ForeignKey(Chiefdom, on_delete=models.CASCADE, db_constraint=True)
    county = models.ManyToManyField(County, db_constraint=True)
    amount = models.PositiveSmallIntegerField()
</code>```

SQLite

```<code>CREATE TABLE IF NOT EXISTS Piece_token (
  id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
  amount smallint unsigned NOT NULL,
  owner_id integer NOT NULL
);

CREATE INDEX IF NOT EXISTS Piece_token_owner_id_d27c77f0 ON Piece_token (owner_id);

CREATE TABLE IF NOT EXISTS Piece_token_county (
  id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
  token_id integer NOT NULL,
  county_id integer NOT NULL
);

CREATE INDEX IF NOT EXISTS Piece_token_county_county_id_57802417 ON Piece_token_county (county_id);

CREATE INDEX IF NOT EXISTS Piece_token_county_token_id_e7798ae9 ON Piece_token_county (token_id);

CREATE UNIQUE INDEX IF NOT EXISTS Piece_token_county_token_id_county_id_b06b16cc_uniq ON Piece_token_county (token_id, county_id);
</code>```

答:
I have checked now with same version of Django and SQLite there are all foreign keys present

For example

```<code>SELECT * FROM pragma_foreign_key_list('auth_user_groups');
</code>```

Note all foreign keys are deferred and checked from Django -> source

Body:
I'm using Django 3.0.6

I'm adding ForeignKey and ManyToManyField to my models, but I've noticed that django creates the INDEX, but not the actual FOREIGN KEY constraints in the db.

I've tried to explicitly set db_constraint=True but as expected is useless, since it's True by default.

I've found so many answers explaining this, but only for very old Django versions, doing tricks for enabling it when it was otherwise disabled. Now instead it should just work out of the box. Couldn't find anything AT ALL regarding Django 3.

Code

class Token (models.Model):
    owner = models.ForeignKey(Chiefdom, on_delete=models.CASCADE, db_constraint=True)
    county = models.ManyToManyField(County, db_constraint=True)
    amount = models.PositiveSmallIntegerField()

SQLite

CREATE TABLE IF NOT EXISTS Piece_token (
  id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
  amount smallint unsigned NOT NULL,
  owner_id integer NOT NULL
);

CREATE INDEX IF NOT EXISTS Piece_token_owner_id_d27c77f0 ON Piece_token (owner_id);

CREATE TABLE IF NOT EXISTS Piece_token_county (
  id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
  token_id integer NOT NULL,
  county_id integer NOT NULL
);

CREATE INDEX IF NOT EXISTS Piece_token_county_county_id_57802417 ON Piece_token_county (county_id);

CREATE INDEX IF NOT EXISTS Piece_token_county_token_id_e7798ae9 ON Piece_token_county (token_id);

CREATE UNIQUE INDEX IF NOT EXISTS Piece_token_county_token_id_county_id_b06b16cc_uniq ON Piece_token_county (token_id, county_id);

Body:
I have checked now with same version of Django and SQLite there are all foreign keys present

For example

SELECT * FROM pragma_foreign_key_list('auth_user_groups');

Note all foreign keys are deferred and checked from Django -> source


问:
Tensorflow Reinforcement Learning RNN returning NaN's after Optimization with GradientTape
```<code>def create_example_model():
    tf.keras.backend.set_floatx('float64')
    model = Sequential()
    model.add(LSTM(128, input_shape=((60, len(df_train.columns)))))

    model.add(Dense(64, activation='relu'))

    model.add(Dense(3, activation=None))

    return model

def choose_action(model, observation):
    observation = np.expand_dims(observation, axis=0)

    logits = model.predict(observation)

    prob_weights = tf.nn.softmax(logits).numpy()

    action = np.random.choice(3, size=1, p=prob_weights.flatten())[0]

    return action

def train_step(model, optimizer, observations, actions, discounted_rewards):
    with tf.GradientTape() as tape:

        logits = model(observations)

        loss = compute_loss(logits, actions, discounted_rewards)

        grads = tape.gradient(loss, model.trainable_variables)
        optimizer.apply_gradients(zip(grads, model.trainable_variables))

learning_rate = 1e-3
optimizer = tf.keras.optimizers.Adam(learning_rate)
env = TradingEnv(rnn_ready_array)

model = create_example_model()
memory = Memory()
info_list = []

for i_episode in range(10):
    observation = env.reset()
    memory.clear()

    while True:
        action = choose_action(model, observation)
        next_observation, reward, done, info = env.step(action)
        info_list.append(info)
        memory.add_to_memory(observation, action, reward)
        if done:
            total_reward = sum(memory.rewards)
            train_step(model, optimizer,
                 observations=np.array(memory.observations),
                 actions=np.array(memory.actions),
                 discounted_rewards = discount_rewards(memory.rewards))

            memory.clear()
            break
        observation = next_observation
</code>```

I am working on a reinforcement learning project with Tensorflow 2.0; the format of the code comes from an online MIT course of which I am attempting to adapt to my own project. I am new to Tensorflow 2.0 and I can't glean from the documentation why this problem is occurring. The issue is that when I run the reinforcement learning process,

The first episode will always complete successfully.

A new observation will always be generated from the model successfully.

During the second episode, the network will always output: [NaN, NaN, NaN]

Some debugging info I have found that should be helpful:
If I comment out the optimization lines 'grads = tape.gradient(...)' and 'optimizer.apply_gradients(...)' the script will run to completion error free (though it is obviously not doing anything useful without optimization). This indicates to me the optimization process is changing the model in a way that is causing the problem. I've tried to include only the necessary functions for debugging; if there is any further information one might need for debugging, I'd be happy to add additional info in an edit.

答: After hours of checking and rechecking various containers I realized it was the discounted rewards function that was not working properly, returning NaN in this circumstance. Issue resolved :)</p>

Body:
def create_example_model():
    tf.keras.backend.set_floatx('float64')
    model = Sequential()
    model.add(LSTM(128, input_shape=((60, len(df_train.columns)))))

    model.add(Dense(64, activation='relu'))

    model.add(Dense(3, activation=None))

    return model

def choose_action(model, observation):
    observation = np.expand_dims(observation, axis=0)

    logits = model.predict(observation)

    prob_weights = tf.nn.softmax(logits).numpy()

    action = np.random.choice(3, size=1, p=prob_weights.flatten())[0]

    return action

def train_step(model, optimizer, observations, actions, discounted_rewards):
    with tf.GradientTape() as tape:

        logits = model(observations)

        loss = compute_loss(logits, actions, discounted_rewards)

        grads = tape.gradient(loss, model.trainable_variables)
        optimizer.apply_gradients(zip(grads, model.trainable_variables))

learning_rate = 1e-3
optimizer = tf.keras.optimizers.Adam(learning_rate)
env = TradingEnv(rnn_ready_array)

model = create_example_model()
memory = Memory()
info_list = []

for i_episode in range(10):
    observation = env.reset()
    memory.clear()

    while True:
        action = choose_action(model, observation)
        next_observation, reward, done, info = env.step(action)
        info_list.append(info)
        memory.add_to_memory(observation, action, reward)
        if done:
            total_reward = sum(memory.rewards)
            train_step(model, optimizer,
                 observations=np.array(memory.observations),
                 actions=np.array(memory.actions),
                 discounted_rewards = discount_rewards(memory.rewards))

            memory.clear()
            break
        observation = next_observation

I am working on a reinforcement learning project with Tensorflow 2.0; the format of the code comes from an online MIT course of which I am attempting to adapt to my own project. I am new to Tensorflow 2.0 and I can't glean from the documentation why this problem is occurring. The issue is that when I run the reinforcement learning process,

The first episode will always complete successfully.

A new observation will always be generated from the model successfully.

During the second episode, the network will always output: [NaN, NaN, NaN]

Some debugging info I have found that should be helpful:
If I comment out the optimization lines 'grads = tape.gradient(...)' and 'optimizer.apply_gradients(...)' the script will run to completion error free (though it is obviously not doing anything useful without optimization). This indicates to me the optimization process is changing the model in a way that is causing the problem. I've tried to include only the necessary functions for debugging; if there is any further information one might need for debugging, I'd be happy to add additional info in an edit.


问:
Coalescing multiple columns using multiple conditions
I am trying to coalesce multiple columns using multiple conditional statements. In the example below I want to coalesce with A taking precedence over B followed by C where A is >= 0.1 and < 30, while where A is NA, < 0.1 or > 30 I was to coalesce with B taking precedence over A followed by C.

Below is an example dataset:

```<code>df <- data.frame(1:8)
df$A <- c(102, 0.04, 0.1, NA_real_, 0.01, 0.01, 0.2, NA_real_)
df$B <- c(20.2, 50.1, 10.1, 6.1, 7.1, NA_real_, 8.1, NA_real_)
df$C <- c(NA_real_, 4.1, NA_real_, NA_real_, NA_real_, 8.1, NA_real_, 10.1)

      A    B    C
1   102 20.2   NA
2  0.04 50.1  4.1
3   0.1 10.1   NA
4    NA  6.1   NA
5  0.01  7.1   NA
6  0.01   NA  8.1
7   0.2  8.1   NA
8    NA   NA 10.1
</code>```

Below is the desired output:

```<code>      A    B    C new_col
1   102 20.2   NA    20.2
2  0.04 50.1  4.1    50.1
3   0.1 10.1   NA     0.1
4    NA  6.1   NA     6.1
5  0.01  7.1   NA     7.1
6  0.01   NA  8.1     8.1
7   0.2  8.1   NA     0.2
8    NA   NA 10.1    10.1
</code>```

I tried to solve this using mutate and the coalesce functions in the code below but did not get the desired output (in many cases this works OK as long as the value in column A is a value where the value is NA, Nulls are produced in the output).

```<code>df <- df %>%
  mutate(new_col = if_else(A >= 0.1 & A <= 30,
                           coalesce(A, B, C),
                           coalesce(B, A, C)))

      A    B    C new_col
1   102 20.2   NA    20.2
2  0.04 50.1  4.1    50.1
3   0.1 10.1   NA     0.1
4    NA  6.1   NA    NULL
5  0.01  7.1   NA     7.1
6  0.01   NA  8.1    0.01
7   0.2  8.1   NA     0.2
8    NA   NA 10.1    NULL
</code>```

答:
We can use case_when

```<code>library(dplyr)
df %>%
    mutate(new_col = case_when(A >= 0.1 & A <= 30 & !is.na(A) ~
                   coalesce(A, B, C), TRUE ~ coalesce(B, A, C)))
</code>```

Body:
I am trying to coalesce multiple columns using multiple conditional statements. In the example below I want to coalesce with A taking precedence over B followed by C where A is >= 0.1 and < 30, while where A is NA, < 0.1 or > 30 I was to coalesce with B taking precedence over A followed by C.

Below is an example dataset:

df <- data.frame(1:8)
df$A <- c(102, 0.04, 0.1, NA_real_, 0.01, 0.01, 0.2, NA_real_)
df$B <- c(20.2, 50.1, 10.1, 6.1, 7.1, NA_real_, 8.1, NA_real_)
df$C <- c(NA_real_, 4.1, NA_real_, NA_real_, NA_real_, 8.1, NA_real_, 10.1)

      A    B    C
1   102 20.2   NA
2  0.04 50.1  4.1
3   0.1 10.1   NA
4    NA  6.1   NA
5  0.01  7.1   NA
6  0.01   NA  8.1
7   0.2  8.1   NA
8    NA   NA 10.1

Below is the desired output:

      A    B    C new_col
1   102 20.2   NA    20.2
2  0.04 50.1  4.1    50.1
3   0.1 10.1   NA     0.1
4    NA  6.1   NA     6.1
5  0.01  7.1   NA     7.1
6  0.01   NA  8.1     8.1
7   0.2  8.1   NA     0.2
8    NA   NA 10.1    10.1

I tried to solve this using mutate and the coalesce functions in the code below but did not get the desired output (in many cases this works OK as long as the value in column A is a value where the value is NA, Nulls are produced in the output).

df <- df %>%
  mutate(new_col = if_else(A >= 0.1 & A <= 30,
                           coalesce(A, B, C),
                           coalesce(B, A, C)))

      A    B    C new_col
1   102 20.2   NA    20.2
2  0.04 50.1  4.1    50.1
3   0.1 10.1   NA     0.1
4    NA  6.1   NA    NULL
5  0.01  7.1   NA     7.1
6  0.01   NA  8.1    0.01
7   0.2  8.1   NA     0.2
8    NA   NA 10.1    NULL

Body:
We can use case_when

library(dplyr)
df %>%
    mutate(new_col = case_when(A >= 0.1 & A <= 30 & !is.na(A) ~
                   coalesce(A, B, C), TRUE ~ coalesce(B, A, C)))


问:
A function uses an object to initiate and destroy a resource. How can I rewrite this as HOF that provides a resource?
Here is what I am starting with. convert uses svgInjector to initiate and destroy a resource.

```<code>export async function convert(
  serializedSvg: string,
  svgSourceId: string,
  containerId: string
): Promise<string> {
  const svgInjector = new SvgInjector(serializedSvg, containerId).inject();
  if (!svgInjector.injectedElement) {
    throw new Error("Svg not injected");
  }

  const doc = new TargetDocument({});
  const xml = convertRecursively(
    svgInjector.injectedElement,
    doc,
    {
      svgSourceId,
    }
  );

  svgInjector.remove();

  return doc.saveXML();
}
</code>```

How can I rewrite this to instead have a higher order function initiate, provide and destroy the resource svgInjector.injectedElement to the convert function?

EDIT:

Here is a minimal reproducible example:

var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'

function convert(
  serializedSvg,
  containerId
) {
  // make resource available (cross-cutting convern)
  var container = document.getElementById(containerId);
  var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
  container.appendChild(resource);

  // core convert functionality does things with resource
  console.log(resource.getBBox())

  // clean up resource (cross-cutting concern)
  resource.remove()
}

convert(svg, "container")```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>Minimal</title>
</head>
<body>
<div id="container">
</div>
</body>
</html></code>```

EDIT 2

Here is a TypeScript version of the JavaScript in the previous edit

```<code>var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'

function convert(
  serializedSvg: string,
  containerId: string
) {
  // make resource available (cross-cutting convern)
  var container = document.getElementById(containerId);
  if (!(container instanceof HTMLDivElement)) {
    throw new Error("Extpected a div element")
  }
  var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
  if (!(resource instanceof SVGSVGElement)) {
    throw new Error("Extpected a svg element")
  }
  container.appendChild(resource);

  // core convert functionality does things with resource
  console.log(resource.getBBox())

  // clean up resource (cross-cutting concern)
  resource.remove()
}

convert(svg, "container")
</code>```

答:
Here is my best attempt so far. I hope someone smarter posts a better solution.

Two weaknesses of the solution below I see are:

The typing of the enhancer is not generic, hindering reuse

The enhancer requires binding, hindering enhancer compose

```<code>    type Props = {
      svg: SVGSVGElement;
      svgSourceId: string;
      containerId: string;
    };

    async function convertBase(props: Props): Promise<string> {
      const doc = new TargetDocument({});
      const xml = convertRecursively(props.svg, doc, {
        svgSourceId: props.svgSourceId,
      });

      return doc.saveXML();
    }

    type EnhancerProps = {
      serializedSvg: string;
      svgSourceId: string;
      containerId: string;
    };

    type EnhancerPropsLight = {
      svgSourceId: string;
      containerId: string;
    };

    function enhancer(fn: Function, props: EnhancerProps) {
      const rest = omit(["serializedSvg"])(props) as EnhancerPropsLight;
      const svgInjector = new SvgInjector(
        props.serializedSvg,
        props.containerId
      ).inject();
      if (!svgInjector.injectedElement) {
        throw new Error("Svg not injected");
      }

      const res = convertToTgmlBase({ ...rest, svg: svgInjector.injectedElement });

      svgInjector.remove();

      return res;
    }

    const convert = enhancer.bind(null, convertBase);
    export { convert };

</code>```

Body:
Here is what I am starting with. convert uses svgInjector to initiate and destroy a resource.

export async function convert(
  serializedSvg: string,
  svgSourceId: string,
  containerId: string
): Promise<string> {
  const svgInjector = new SvgInjector(serializedSvg, containerId).inject();
  if (!svgInjector.injectedElement) {
    throw new Error("Svg not injected");
  }

  const doc = new TargetDocument({});
  const xml = convertRecursively(
    svgInjector.injectedElement,
    doc,
    {
      svgSourceId,
    }
  );

  svgInjector.remove();

  return doc.saveXML();
}

How can I rewrite this to instead have a higher order function initiate, provide and destroy the resource svgInjector.injectedElement to the convert function?

EDIT:

Here is a minimal reproducible example:

var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'

function convert(
  serializedSvg,
  containerId
) {
  // make resource available (cross-cutting convern)
  var container = document.getElementById(containerId);
  var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
  container.appendChild(resource);

  // core convert functionality does things with resource
  console.log(resource.getBBox())

  // clean up resource (cross-cutting concern)
  resource.remove()
}

convert(svg, "container")

<!DOCTYPE html>

  <title>Minimal</title>

EDIT 2

Here is a TypeScript version of the JavaScript in the previous edit

var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'

function convert(
  serializedSvg: string,
  containerId: string
) {
  // make resource available (cross-cutting convern)
  var container = document.getElementById(containerId);
  if (!(container instanceof HTMLDivElement)) {
    throw new Error("Extpected a div element")
  }
  var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
  if (!(resource instanceof SVGSVGElement)) {
    throw new Error("Extpected a svg element")
  }
  container.appendChild(resource);

  // core convert functionality does things with resource
  console.log(resource.getBBox())

  // clean up resource (cross-cutting concern)
  resource.remove()
}

convert(svg, "container")

Body:
Here is my best attempt so far. I hope someone smarter posts a better solution.

Two weaknesses of the solution below I see are:

The typing of the enhancer is not generic, hindering reuse

The enhancer requires binding, hindering enhancer compose

    type Props = {
      svg: SVGSVGElement;
      svgSourceId: string;
      containerId: string;
    };

    async function convertBase(props: Props): Promise<string> {
      const doc = new TargetDocument({});
      const xml = convertRecursively(props.svg, doc, {
        svgSourceId: props.svgSourceId,
      });

      return doc.saveXML();
    }

    type EnhancerProps = {
      serializedSvg: string;
      svgSourceId: string;
      containerId: string;
    };

    type EnhancerPropsLight = {
      svgSourceId: string;
      containerId: string;
    };

    function enhancer(fn: Function, props: EnhancerProps) {
      const rest = omit(["serializedSvg"])(props) as EnhancerPropsLight;
      const svgInjector = new SvgInjector(
        props.serializedSvg,
        props.containerId
      ).inject();
      if (!svgInjector.injectedElement) {
        throw new Error("Svg not injected");
      }

      const res = convertToTgmlBase({ ...rest, svg: svgInjector.injectedElement });

      svgInjector.remove();

      return res;
    }

    const convert = enhancer.bind(null, convertBase);
    export { convert };


问:
How to print to screen and save to file in one-line?
Is it possible to print to screen and save to file in one-line?

The following saves to file:

```<code>with open('file.txt', 'a') as f:
   print('hello world', file=f)
</code>```

And currently to print to screen and save to file would have to do the following:

```<code>print['hello world')
print('hello world', file=f)
</code>```

I can't find any answers out there for one-line.

I guess a function can be defined to avoid lines in code, but still wondering if it is possible to do all in one line

答:
You are looking for a tee fitting for Python. Such a package - tee - exists in PyPI.

You can also build one yourself with a few lines of code - the original author of a big package I maintain did just that, and my code uses it to this day. Of source, there is not need for that, since the package is available.

Body:
Is it possible to print to screen and save to file in one-line?

The following saves to file:

with open('file.txt', 'a') as f:
   print('hello world', file=f)

And currently to print to screen and save to file would have to do the following:

print['hello world')
print('hello world', file=f)

I can't find any answers out there for one-line.

I guess a function can be defined to avoid lines in code, but still wondering if it is possible to do all in one line


问:
Python3: Why is my else statement activating regardless of multiple if statements being true
```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

Thank you everyone for the quick responses!!!

答: I would change those if...if...if...else to if..elif...elif...else. There may be some logic error going on.

Body:
tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

Thank you everyone for the quick responses!!!


问:
Updating Objects To Add New Element With .push
In the snippet below the goal is to check if the addedPlayer already exist in players by checking the .name property

if addedPlayer is already in players : Give the player a point

else update players by adding in addedPlayer with a starting point

```<code>let players = []

let addedPlayer = {

   name: /* The Given Name To Check in players */ ,
   points: 1

}

function addPlayer(playerList, playerToAdd){

   const existingPlayers = playerList.map((playerToAdd) => playerToAdd.name);

   if(existingPlayers.includes(playerToAdd.name)){

       playerToAdd.points++

   } else {

      playerList.push(playerToAdd)

   }
}

addPlayer(players, addedPlayer)

console.log(players)
</code>```

The problem is players only returns addedPlayer. My Goal being that players will store every new player and adds points accordingly

答:
It's considered good practice to always initialize our variables. I just created a name variable for our user object.

Each time you run addPlayer it will now push new players to the list.

```<code>let players = []
var name = "";

let addedPlayer = {

    name: name,
    points: 1

}

function addPlayer(playerList, playerToAdd) {

    const existingPlayers = playerList.map((playerToAdd) => playerToAdd.name);

    if (existingPlayers.includes(playerToAdd.name)) {

        playerToAdd.points++

    } else {

        playerList.push(playerToAdd)

    }
}

addPlayer(players, addedPlayer)

console.log(players)
</code>```

Body:
In the snippet below the goal is to check if the addedPlayer already exist in players by checking the .name property

if addedPlayer is already in players : Give the player a point

else update players by adding in addedPlayer with a starting point

let players = []

let addedPlayer = {

   name: /* The Given Name To Check in players */ ,
   points: 1

}

function addPlayer(playerList, playerToAdd){

   const existingPlayers = playerList.map((playerToAdd) => playerToAdd.name);

   if(existingPlayers.includes(playerToAdd.name)){

       playerToAdd.points++

   } else {

      playerList.push(playerToAdd)

   }
}

addPlayer(players, addedPlayer)

console.log(players)

The problem is players only returns addedPlayer. My Goal being that players will store every new player and adds points accordingly

Body:
It's considered good practice to always initialize our variables. I just created a name variable for our user object.

Each time you run addPlayer it will now push new players to the list.

let players = []
var name = "";

let addedPlayer = {

    name: name,
    points: 1

}

function addPlayer(playerList, playerToAdd) {

    const existingPlayers = playerList.map((playerToAdd) => playerToAdd.name);

    if (existingPlayers.includes(playerToAdd.name)) {

        playerToAdd.points++

    } else {

        playerList.push(playerToAdd)

    }
}

addPlayer(players, addedPlayer)

console.log(players)


问:
Bootstrap-vue: how to pass data to modal?
I'm trying to use bootstrap-vue modal to show details from a collection of items.

What I want is to pass data to modal to show a simple message.

I first loop over recordset to show button.

```<code><ul>
  <li v-for="item in items">{{ item.first_name }}
      <b-button size="sm" v-b-modal="'myModal'" user="'item'">
        Saluta {{item.first_name}}
      </b-button>
  </li>
</ul>
</code>```

And then display name in modal:

```<code><b-modal id="myModal" :user="'user'">
  Hello {{user}}!
</b-modal>
</code>```

Here's my fiddle https://jsfiddle.net/bptLavov/259/

答:
You can use vuex and your components won't have to be in the same file or related.

Component which will open the modal:

```<code><ul>
  <li v-for="item in items">{{ item.first_name }}
    <b-button @click="$store.dispatch('modals/openModal', { data: item, modalId: 'myModal' })">
      Saluta {{item.first_name}}
    </b-button>
  </li>
</ul>
</code>```

Modal's template:

```<code><b-modal id="myModal">
  Hello {{selectedUser.first_name}} {{selectedUser.last_name}} !
</b-modal>
</code>```

Modal's computed property:

```<code>selectedUser() { return this.$store.state.modals.modalData },
</code>```

Vuex module (modals.js):

```<code>const state = {
 modalData: {},
}

const mutations = {
  setModalData(state, data) { state.modalData = data },
}

const actions = {
  openModal(context, data) {
    context.commit('setModalData', data.data)
    $('#' + data.modalId).modal('show')
  },
}
</code>```

Body:
I'm trying to use bootstrap-vue modal to show details from a collection of items.

What I want is to pass data to modal to show a simple message.

I first loop over recordset to show button.

{{ item.first_name }}

        Saluta {{item.first_name}}

And then display name in modal:

  Hello {{user}}!

Here's my fiddle https://jsfiddle.net/bptLavov/259/

Body:
You can use vuex and your components won't have to be in the same file or related.

Component which will open the modal:

<ul>
  <li v-for="item in items">{{ item.first_name }}
    <b-button @click="$store.dispatch('modals/openModal', { data: item, modalId: 'myModal' })">
      Saluta {{item.first_name}}
    </b-button>
  </li>
</ul>

Modal's template:

<b-modal id="myModal">
  Hello {{selectedUser.first_name}} {{selectedUser.last_name}} !
</b-modal>

Modal's computed property:

selectedUser() { return this.$store.state.modals.modalData },

Vuex module (modals.js):

const state = {
 modalData: {},
}

const mutations = {
  setModalData(state, data) { state.modalData = data },
}

const actions = {
  openModal(context, data) {
    context.commit('setModalData', data.data)
    $('#' + data.modalId).modal('show')
  },
}


问:
Java NullPointerException when calling listFiles() on a directory
I have a series of folders containing books on a server which I am accessing with this piece of code. I want to make each of these folders an object so I can do some work with the files inside them later on. I'm trying to use this method to return a list of the folders as Book objects.

```<code>public List<Book> getBooks(File folder){
    List<Book> books = new ArrayList<Book>();
    for (File f : folder.listFiles()){
        if (f.isDirectory()){
            System.out.println(f.getAbsolutePath() + "" + f.listFiles());
            books.add(new Book(f));
        }
    }
    return books;
}
</code>```

The println statement in this block is printing, as it should, the direct path to the folder and then the memory address along with some other information. However, somewhere in the folder it is printing out null when listFiles() is called. The folder that it is doing this on is not empty. This supposedly empty folder is then passed to my class init method.

```<code>public Book(File bookFolder) {
    this.bookFolder = bookFolder;
    this.bookPath = bookFolder.getAbsolutePath();

    System.out.println(bookFolder + " " + bookFolder.listFiles());

    for (File f : bookFolder.listFiles()) {
        ...
    }
}
</code>```

The println statement in this block prints out the exact same path to the folder and then a different memory address, which is also expected. When it hits the "empty" folder it prints null for the memory address again.

Now, for the real issue, the line with the for loop is where the program crashes and throws a NullPointerException which isn't even described in the documentation for the listFiles method.

Why could this be happening? Also, why are my non-empty folders returning null?

答: For me it was caused by trailing spaces. Use variable.trim()</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a series of folders containing books on a server which I am accessing with this piece of code. I want to make each of these folders an object so I can do some work with the files inside them later on. I'm trying to use this method to return a list of the folders as Book objects.

public List<Book> getBooks(File folder){
    List<Book> books = new ArrayList<Book>();
    for (File f : folder.listFiles()){
        if (f.isDirectory()){
            System.out.println(f.getAbsolutePath() + "" + f.listFiles());
            books.add(new Book(f));
        }
    }
    return books;
}

The println statement in this block is printing, as it should, the direct path to the folder and then the memory address along with some other information. However, somewhere in the folder it is printing out null when listFiles() is called. The folder that it is doing this on is not empty. This supposedly empty folder is then passed to my class init method.

public Book(File bookFolder) {
    this.bookFolder = bookFolder;
    this.bookPath = bookFolder.getAbsolutePath();

    System.out.println(bookFolder + " " + bookFolder.listFiles());

    for (File f : bookFolder.listFiles()) {
        ...
    }
}

The println statement in this block prints out the exact same path to the folder and then a different memory address, which is also expected. When it hits the "empty" folder it prints null for the memory address again.

Now, for the real issue, the line with the for loop is where the program crashes and throws a NullPointerException which isn't even described in the documentation for the listFiles method.

Why could this be happening? Also, why are my non-empty folders returning null?


问:
Remove specific section of string
Hi I have a file that contains several thousand file paths that I am looking to move to Wazhu. Problem is I need directories so what I have looks like
>/apples/oranges/test.ex< What I need is >/apples/oranges<
Not sure if Regex or just using str.replace() is better. As each line is different I would need to find the last / and remove it as well as everything up to <

Hopefully that makes sense.

答:
you mean you want only everything except for the last "/"?</p>

```<code>import os

file = open('file.txt', 'r')
for line in file.read().splitlines():
    print('/'.join(line.split('/',-1)[:-1]) + "<")
</code>```

Title: Remove specific section of string

Body:
you mean you want only everything except for the last "/"?

import os

file = open('file.txt', 'r')
for line in file.read().splitlines():
    print('/'.join(line.split('/',-1)[:-1]) + "<")


问:
how to set hex color code for background

Possible Duplicate:

  How can I create a UIColor from a hex string?

I want to programmatically set the color of the UIView Background.

It doesn't seem like I can do it through Interfacebuilder. How should I do it if I want to set it to some hex code color?

答: UIView's setBackgroundColor method.  You can create a UIColor from hex with UIColor initWithRed:green:blue:alpha it takes floats so you'll need to do bitshifts and math to get the appropriate components.  This is how I manage it


问:
ClosedXML: remove/change alternating row color?
Here's my code so far (VB):

```<code>Dim wb As New ClosedXML.Excel.XLWorkbook()
wb.Worksheets.Add(dTable, "export")
wb.SaveAs(location)
</code>```

How can I remove just styling of the alternate rows (defaults to light blue)

答:
Assuming you want to skip the header row, something like this should work before the save.</p>

```<code>For i As Integer = 2 To wb.Worksheets.Worksheet("export").Rows.Count
     wb.Worksheets.Worksheet("export").Row(i).Style.Fill.SetBackgroundColor(XLColor.White)
Next
</code>```

Body:
Here's my code so far (VB):

Dim wb As New ClosedXML.Excel.XLWorkbook()
wb.Worksheets.Add(dTable, "export")
wb.SaveAs(location)

How can I remove just styling of the alternate rows (defaults to light blue)

Body:
Assuming you want to skip the header row, something like this should work before the save.

For i As Integer = 2 To wb.Worksheets.Worksheet("export").Rows.Count
     wb.Worksheets.Worksheet("export").Row(i).Style.Fill.SetBackgroundColor(XLColor.White)
Next


问:
How is padding-top as a percentage related to the parent's width?
Here is an example:

http://jsfiddle.net/QZAd8/1/

Notice how all of the red divs are the same height and have padding-top:100%;, yet they A & B have different padding sizes... and it appears that the width of the parent changes this value (note that C changes the height of the parent, yet that doesn't alter the padding).

Why is padding related to width in this way?

Edit: for historical reasons, and in case jsfiddle goes away, the code I used in my example is as follows...

.outer {
  background-color: green;
  height: 300px;
  width: 70px;
  float: left;
  margin-right: 10px;
}

.middle {
  background-color: red;
  height: 100px;
  width: 50px;
  padding-top: 100%;
}

.inner {
  background-color: blue;
  height: 3px;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='outer'>
  <div class='middle'>
    A
    <div class='inner'>
    </div>
  </div>
</div>

<div class='outer' style='width:100px'>
  <div class='middle'>
    B
    <div class='inner'>
    </div>
  </div>
</div>

<div class='outer' style='height:400px'>
  <div class='middle'>
    C
    <div class='inner'>
    </div>
  </div>
</div></code>```

答:
If you came here looking for an alternative like I did, you can set padding-top as a percentage of vertical height using a CSS calculation:</p>

```<code>padding-top: calc(.25 * 100vh);
</code>```

Body:
Here is an example:

http://jsfiddle.net/QZAd8/1/

Notice how all of the red divs are the same height and have padding-top:100%;, yet they A & B have different padding sizes... and it appears that the width of the parent changes this value (note that C changes the height of the parent, yet that doesn't alter the padding).

Why is padding related to width in this way?

Edit: for historical reasons, and in case jsfiddle goes away, the code I used in my example is as follows...

.outer {
  background-color: green;
  height: 300px;
  width: 70px;
  float: left;
  margin-right: 10px;
}

.middle {
  background-color: red;
  height: 100px;
  width: 50px;
  padding-top: 100%;
}

.inner {
  background-color: blue;
  height: 3px;
  width: 100%;
}

    A

    B

    C

Body:
If you came here looking for an alternative like I did, you can set padding-top as a percentage of vertical height using a CSS calculation:

padding-top: calc(.25 * 100vh);


问:
Disable "code hiding feature" in IntelliJ
Remark: This question is (up to now) not a duplicate. I know how to disable the hints. This is not what I am looking for.

In intelliJ a feature "hides" parts of my code, e.g. variable declarations as "var" or getter methods like in the example below.

The code shows t.message, but the code behind this visual abbrevation is t.getMessage(). How can I disable that feature and always show t.getMessage()?

Abbreviated code:

Real code:

Because I don't know the name of the feature I have no idea what I am looking for. Any ideas?

答:
To disable showing val/var instead of variable type
go to Settings | Editor | General | Code Folding
and UnCheck Variable Declaration

And just next to it
Uncheck Getters and setters
to start showing getter Setter method calls with full method name

refer- https://stackoverflow.com/a/48271952/3661654


问:
How to automatically deploy Function App contents using Resource Group project in Visual Studio 2017?
There are very good instructions on how to automate Web App deployment - both creating the required infrastructure and deploying the web app contents.
For example, this is very well described here

However, I can't find any detailed instructions on how this is done for a Function App.

What is my case:

I'm using Azure RM Template deployments with a Visual Studio 2017 Resource Group project

I have successfully defined the Function Template

I have successfully defined the Web Deploy Template for the function

I have created my Function as a separate project and it is working correctly

On the Resource Group project, a reference to the Function project has been added and its properties defined as follows:

When I deploy the Resource Group it fails with the message "The target "Package" does not exist in the project."

This means that it cannot build the ZIP package.

Everything is working fine if I remove the "Package" parameter from "Include Targets" and then manually supply the "package.zip" to the Resource Group project.

How should the Resource Group project be configured in order to be able to self-build the ZIP package for the Function App project?

Is it possible to add a "Package" target in the Function app project?

Many thanks!

答:
Building on Vladislav's very help full answer...

A bug in MSBuildTasks nuget deployment prevents it from installing as documented at the project site for .Net Core projects. The .build folder never gets created.

If you add MSBuildTasks, version 1.4.0.128 to a .Net Framework project in the solution, you can use the Import as described on the site:

```<code>  <PropertyGroup>
    <MSBuildCommunityTasksPath>$(SolutionDir)\.build</MSBuildCommunityTasksPath>
  </PropertyGroup>

  <Import Project="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.Targets" />
</code>```

Body:
Building on Vladislav's very help full answer...

A bug in MSBuildTasks nuget deployment prevents it from installing as documented at the project site for .Net Core projects. The .build folder never gets created.

If you add MSBuildTasks, version 1.4.0.128 to a .Net Framework project in the solution, you can use the Import as described on the site:

  <PropertyGroup>
    <MSBuildCommunityTasksPath>$(SolutionDir)\.build</MSBuildCommunityTasksPath>
  </PropertyGroup>

  <Import Project="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.Targets" />


问:
Reading actual txPower of Android mobile
It is possible to find actual ble

txPower

of android device. So that, I can use it below Beacon builder object instead of -59 as txPower.

```<code>Beacon beacon = new Beacon.Builder()
    .setId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")
    .setId2("1")
    .setId3("2")
    .setManufacturer(0x0118)
    .setTxPower(-59)
    .setDataFields(Arrays.asList(new Long[] {0l}))
    .build();
</code>```

The use case what I have is, to read distance between two android ble device.

答:
The txPower field is supposed to be the expected signal strength in dBm at 1 meter.  Every Android phone model has a slightly different BLE transmitter output power, typically measuring from -50 dBm to -70 dBm at 1 meter.

Unfortunately there is no good way to get the proper value to use for a specific Android device model unless you measure this yourself.  Android has no built-in APIs to get this, and I have never seen any published specs from phone manufacturers.

There has been renewed interest in this subject as teams develop contact tracing apps.  I actually went out in a field last weekend to measure the transmitter output power of a number of devices I had handy.  The Google Pixel 3a, for example, I measured -60 dBm.

If you want to take your own measurements to help in this effort, I suggest this procedure:

Go to an open area several meters away from any obstructions, particularly metal ones.

Elevate the phone transmitter on a non-metal object at least one meter off the ground.  The phone should be placed on end so the screen is perpindicular to the ground. (I used a camera tripod.)

Run an app that transmits a beacon at full power on the phone on the tripod.

Hold a reference phone (preferably an iPhone SE 1st Generation or old iPhone 4-5s) on meter away so that both screens are facing the same direction.

Do a "calibration" in a beacon app like Locate Beacon to get the average RSSI over ~30 seconds.

If the phone used to do the measurement is not one of the above reference models, you will need to adjust for that phone's receiver sensitivity.  The spreadsheet I shared has an example of how to do that for the Pixel 3a measuring the iPhone SE.  This part can be tricky as you need one other phone with a known sensitivity or transmitter power output.

Here's my spreadsheet with the calculations: https://docs.google.com/spreadsheets/d/1-voNJAeHz78AarZmfds8WiplNhUDzeYrsW0YzKfrExU/edit?usp=sharing

I also wrote a blog post that touches on the problem of the lack of a good data set, and tells you more than you ever wanted to know about beacon ranging.

Body:
It is possible to find actual ble

txPower

of android device. So that, I can use it below Beacon builder object instead of -59 as txPower.

Beacon beacon = new Beacon.Builder()
    .setId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")
    .setId2("1")
    .setId3("2")
    .setManufacturer(0x0118)
    .setTxPower(-59)
    .setDataFields(Arrays.asList(new Long[] {0l}))
    .build();

The use case what I have is, to read distance between two android ble device.


问:
BeautifulSoup uncomment a comment by id
I want to use BeautifulSoup to change a html below to uncomment by comment tag id.

```<code><div class="foo">
 cat dog sheep goat
 <!--<p id="p1">test</p>-->
 <p id="p2">
  test
 </p>
</div>
</code>```

This is my expected result below:

```<code><div class="foo">
 cat dog sheep goat
 <p id="p1">test</p>
 <p id="p2">
  test
 </p>
</div>
</code>```

This is my python code I use BeautifulSoup, but I don't know how to complete this function.

```<code>from bs4 import BeautifulSoup,Comment

data = """<div class="foo">
cat dog sheep goat
<p id='p1'>test</p>
<p id='p2'>test</p>
</div>"""
soup = BeautifulSoup(data, 'html.parser')

for comment in soup(text=lambda text: isinstance(text, Comment)):
    if 'id="p1"' in comment.string:
        # I don't know how to complete it here.
        # This is my incorrect solution
        # It will output "<p id="p1">test</p>",
        # not "<p id='p1'>test</p>"
        comment.replace_with(comment.string.replace("<!--", "").replace("-->", ""))
        break
</code>```

Ask for help

答:
You can put new soup to .replace_with() instead of string:

```<code>from bs4 import BeautifulSoup,Comment

data = """<div class="foo">
 cat dog sheep goat
 <!--<p id="p1">test</p>-->
 <p id="p2">
  test
 </p>
</div>"""
soup = BeautifulSoup(data, 'html.parser')

print('Original soup:')
print('-' * 80)
print(soup)
print()

for comment in soup(text=lambda text: isinstance(text, Comment)):
    if 'id="p1"' in comment.string:
        tag = BeautifulSoup(comment, 'html.parser')
        comment.replace_with(tag)
        break

print('New soup:')
print('-' * 80)
print(soup)
print()
</code>```

Prints:

```<code>Original soup:
--------------------------------------------------------------------------------
<div class="foo">
 cat dog sheep goat
 <!--<p id="p1">test</p>-->
<p id="p2">
  test
 </p>
</div>

New soup:
--------------------------------------------------------------------------------
<div class="foo">
 cat dog sheep goat
 <p id="p1">test</p>
<p id="p2">
  test
 </p>
</div>
</code>```

Title: BeautifulSoup uncomment a comment by id

Body:
I want to use BeautifulSoup to change a html below to uncomment by comment tag id.

 cat dog sheep goat

  test

This is my expected result below:

 cat dog sheep goat

test

  test

This is my python code I use BeautifulSoup, but I don't know how to complete this function.

from bs4 import BeautifulSoup,Comment

data = """

cat dog sheep goat

test

test

"""
soup = BeautifulSoup(data, 'html.parser')

for comment in soup(text=lambda text: isinstance(text, Comment)):
    if 'id="p1"' in comment.string:
        # I don't know how to complete it here.
        # This is my incorrect solution
        # It will output "
test
",
        # not "
test
"
        comment.replace_with(comment.string.replace("", ""))
        break

Ask for help

Body:
You can put new soup to .replace_with() instead of string:

from bs4 import BeautifulSoup,Comment

data = """<div class="foo">
 cat dog sheep goat
 <!--<p id="p1">test</p>-->
 <p id="p2">
  test
 </p>
</div>"""
soup = BeautifulSoup(data, 'html.parser')

print('Original soup:')
print('-' * 80)
print(soup)
print()

for comment in soup(text=lambda text: isinstance(text, Comment)):
    if 'id="p1"' in comment.string:
        tag = BeautifulSoup(comment, 'html.parser')
        comment.replace_with(tag)
        break

print('New soup:')
print('-' * 80)
print(soup)
print()

Prints:

Original soup:
--------------------------------------------------------------------------------
<div class="foo">
 cat dog sheep goat
 <!--<p id="p1">test</p>-->
<p id="p2">
  test
 </p>
</div>

New soup:
--------------------------------------------------------------------------------
<div class="foo">
 cat dog sheep goat
 <p id="p1">test</p>
<p id="p2">
  test
 </p>
</div>


问:
Is running flask in the default server safe (security-wise)?
I'm thinking about running a very simple Flask server locally (using the default development server) and then opening it up to the web via http://localhost.run/.  I intend for this to be a personal webhook server and nothing else.

I've seen related questions before (for example, Is the server bundled with Flask safe to use in production?, etc), but:

I don't care that it won't scale well

I don't expect to get more than one request at a time

I will not be using the debugging mode

My question is this: How safe will my computer and local network be if I do this?  I will probably limit requests to POST requests and check to see that they have a special key, or something like that, and the only thing I'm going to be doing with the webhooks is displaying a notification.

答:
Short of someone from the Pallets Project speaking up, the official word on the recommendation is

https://flask.palletsprojects.com/en/1.1.x/tutorial/deploy/#run-with-a-production-server

If you have enough access to a server to permit running something that'll listen to a socket, the step of adding a WSGI server isn't a big one. The link above recommends waitress (and provides instructions), but gunicorn and uwsgi will work, too.

Adding my opinion:

Parsing HTTP and dealing with edge-cases is hard, so why should Flask/Werkzeug spend effort dealing with edge cases when there are WSGI front-ends that already take on the responsibility? In their position (which I'm not), I'd punt scaling and security to WSGI servers, and focus on making an excellent framework.


问:
Is it possible for an overloaded procedure to have a different interface from that of its parent class?
Is it possible to extend a class and overload one of its procedure with one with a different interface?

I would like to create multiple type (say tensor1, tensor2, ...) extending a base class tensor , all implementing a method sub whose arguments depend on the subclass.

Consider the following code:

```<code>module tensor_class
   implicit none
   private
   public :: tensor_Type

   type, abstract :: tensor_Type
   Contains
      procedure,pass(self)                             :: sub
   end type

   Contains
      subroutine sub(self,other)
         class(tensor_Type),intent(inout)              :: self
         integer                                       :: other
         write(*,*) 'sub is not implemented in the main class'
      end subroutine
end module tensor_class

module tensor1_mod
   use tensor_class

   type, extends(tensor_type)                          :: tensor1
      real,dimension(2)                                :: val
   Contains
      procedure, pass(self)                            :: sub
   end type tensor1
 Contains
    subroutine sub(self,other)
       class(tensor1),intent(inout)                     :: self
       real,dimension(2),intent(in)                     :: other

       self%val = self%val + 2.0 * other
    end subroutine
end module

module tensor
   use tensor1_mod
end module

program testTensor
   use tensor
   implicit none

   class(tensor_type),allocatable                      :: t
   type(tensor1)                                       :: t1
   real,dimension(2)                                   :: v1 = [1.0,-2.3]
   integer                                             :: i

   t1 = tensor1(v1)
   t  = tensor1(v1)
   call t1%sub(i)
   call t%sub(i)
end program
</code>```

Neither Intel Fortran (19.1.1.216 20200306) nor gfortran (9.3.0) will compile it. The Intel compiler prints the following error message

```<code>tensorMin.F90(25): error #8383: The dummy arguments of an overriding and overridden binding that correspond by position must have the same characteristics, except for the type of the passed object dummy arguments.   [SUB]
</code>```

and gfortran

```<code>>tensorMin.F90:25:15:

   25 |       procedure, pass(self)                            :: sub
      |               1
Error: Argument mismatch for the overriding procedure 'sub' at (1): Type mismatch in argument 'other' (REAL(4)/INTEGER(4))
</code>```

I cannot declare sub as deferred in tensor_class, if I want to be able to create multiple subclasses and have sub take different type of arguments in each class (say real, dimension(2) in tensor1, real, dimension(2,2) in tensor2 etc).

Upon reading of the Fortran 2008 standard section 4.5.7.3, it seems that the name and number of arguments in sub need to match, but the standard does not seem to say anything about the type of the arguments.

Am I missing something? Is there a way other than creating a class containing all possible arguments of sub?

答:
The Fortran standard does require the argument types to match.

Except for the passed-object dummy arguments the standard says that the dummy arguments which correspond shall have the same characteristics. (This the Intel Fortran error message states.) The type of a dummy argument is one characteristic (of many) of that argument.

You can look in to polymorphic arguments (as in your comment) or at generic bindings.

Body:
Is it possible to extend a class and overload one of its procedure with one with a different interface?

I would like to create multiple type (say tensor1, tensor2, ...) extending a base class tensor , all implementing a method sub whose arguments depend on the subclass.

Consider the following code:

module tensor_class
   implicit none
   private
   public :: tensor_Type

   type, abstract :: tensor_Type
   Contains
      procedure,pass(self)                             :: sub
   end type

   Contains
      subroutine sub(self,other)
         class(tensor_Type),intent(inout)              :: self
         integer                                       :: other
         write(*,*) 'sub is not implemented in the main class'
      end subroutine
end module tensor_class

module tensor1_mod
   use tensor_class

   type, extends(tensor_type)                          :: tensor1
      real,dimension(2)                                :: val
   Contains
      procedure, pass(self)                            :: sub
   end type tensor1
 Contains
    subroutine sub(self,other)
       class(tensor1),intent(inout)                     :: self
       real,dimension(2),intent(in)                     :: other

       self%val = self%val + 2.0 * other
    end subroutine
end module

module tensor
   use tensor1_mod
end module

program testTensor
   use tensor
   implicit none

   class(tensor_type),allocatable                      :: t
   type(tensor1)                                       :: t1
   real,dimension(2)                                   :: v1 = [1.0,-2.3]
   integer                                             :: i

   t1 = tensor1(v1)
   t  = tensor1(v1)
   call t1%sub(i)
   call t%sub(i)
end program

Neither Intel Fortran (19.1.1.216 20200306) nor gfortran (9.3.0) will compile it. The Intel compiler prints the following error message

tensorMin.F90(25): error #8383: The dummy arguments of an overriding and overridden binding that correspond by position must have the same characteristics, except for the type of the passed object dummy arguments.   [SUB]

and gfortran

>tensorMin.F90:25:15:

   25 |       procedure, pass(self)                            :: sub
      |               1
Error: Argument mismatch for the overriding procedure 'sub' at (1): Type mismatch in argument 'other' (REAL(4)/INTEGER(4))

I cannot declare sub as deferred in tensor_class, if I want to be able to create multiple subclasses and have sub take different type of arguments in each class (say real, dimension(2) in tensor1, real, dimension(2,2) in tensor2 etc).

Upon reading of the Fortran 2008 standard section 4.5.7.3, it seems that the name and number of arguments in sub need to match, but the standard does not seem to say anything about the type of the arguments.

Am I missing something? Is there a way other than creating a class containing all possible arguments of sub?


问:
Python method lookup, static vs. instance
Until like one hour ago, I was convinced that in python Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) which passes the instance as first parameter. In this example the last two lines do (apparently) the same thing:

```<code>class Foo (object):
    def bar (self): print "baz"

qux = Foo ()
qux.bar ()
Foo.bar (qux)
</code>```

But now I have a class Animal that has a static method populate() that returns a list of all animals known to man. Also each instance of Animal has a method populate() that fills the properties of the instance with random values.

```<code>#! /usr/bin/env python
# -*- coding: utf-8 -*-

import random

animals = [ ("Bella", "cow"), ("Spike", "dog"), ("José", "iguana"), ("Tux", "penguin") ]

class Animal (object):
    @staticmethod
    def populate (*args): return map (lambda x: Animal (*x), animals)

    def __init__ (self, name = None, species = None):
        def bar (): self.name, self.species = random.choice (animals)
        self.name = name
        self.species = species
        self.populate = bar

    def __repr__ (self): return "%s of species %s" % (self.name, self.species)

print Animal.populate ()
print Animal ("Pinky", "mouse")
qux = Animal ()
qux.populate ()
print qux
</code>```

The code works fine, but what made me suspicious was the fact that print Animal.populate (qux) called the static populate method (and hence returned a list and did not populate poor qux). So apparently my conviction that Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) is wrong.

This raises various questions for me:

What happens when I call Foo ().bar ()?

What happens when I call Foo.bar (Foo () )?

Is there an internal difference between the both?

Am I missing some fundamental concept of python?

If you had to write a class whose static populate method does something else than the populate method invoked over an instance of this class, which would be the way to go?

(Yes it must be the same name.)

答: Static methods and class methods are special descriptors. Since the descriptor's __get__() method's  arguments include both the class and any relevant instance, they can screw with the arguments to the method in any way they like.

Body:
Until like one hour ago, I was convinced that in python Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) which passes the instance as first parameter. In this example the last two lines do (apparently) the same thing:

class Foo (object):
    def bar (self): print "baz"

qux = Foo ()
qux.bar ()
Foo.bar (qux)

But now I have a class Animal that has a static method populate() that returns a list of all animals known to man. Also each instance of Animal has a method populate() that fills the properties of the instance with random values.

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import random

animals = [ ("Bella", "cow"), ("Spike", "dog"), ("José", "iguana"), ("Tux", "penguin") ]

class Animal (object):
    @staticmethod
    def populate (*args): return map (lambda x: Animal (*x), animals)

    def __init__ (self, name = None, species = None):
        def bar (): self.name, self.species = random.choice (animals)
        self.name = name
        self.species = species
        self.populate = bar

    def __repr__ (self): return "%s of species %s" % (self.name, self.species)

print Animal.populate ()
print Animal ("Pinky", "mouse")
qux = Animal ()
qux.populate ()
print qux

The code works fine, but what made me suspicious was the fact that print Animal.populate (qux) called the static populate method (and hence returned a list and did not populate poor qux). So apparently my conviction that Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) is wrong.

This raises various questions for me:

What happens when I call Foo ().bar ()?

What happens when I call Foo.bar (Foo () )?

Is there an internal difference between the both?

Am I missing some fundamental concept of python?

If you had to write a class whose static populate method does something else than the populate method invoked over an instance of this class, which would be the way to go?

(Yes it must be the same name.)


问:
Assign stored procedure to a report.recordset in Microsoft Access
I've heard you can only do this is adp, I'm connecting directly to SQL Server, and would like to assign a stored procedure to a record and I get the error that can be done only in adp file?

I'm not linked to SQL Server, I connect directly to it with ODBC driver.

Is there any way I can assign this stored procedure to the report?

Thanks..

答:
All you have to do is create a query in Access, but mark it (change it) to a pass-thougthh query.

So, the pt query can be

```<code>Exec MyStoredProcedure
</code>```

Save the query. Now just use this query as the source for the report. You don't really need to write any code here. Now of course if you need to pass a value or some kind of parameter?

Well, then you can use this code:

Let's assume that the stored procedure returns data for a given invoice number.

So, your code would look like this:

```<code>dim strInvoiceNumber   as string
strInvoiceNumber = InputBox("Enter invoice number")

currentdb.QueryDefs("MyPass").sql = "EXEC StorProc " & strInvoiceNumber

' code here follows to open report
 docmd.OpenReport "MyInoice",acViewPreview
</code>```

So, you can create a pass-thorough query, and type into the query any exec or command that would run/call the stored procedure. And as noted, if there are no parameters, then you don't need to write any code at all - just create the pass-though query, and use that as the source for the report.

Body:
All you have to do is create a query in Access, but mark it (change it) to a pass-thougthh query.

So, the pt query can be

Exec MyStoredProcedure

Save the query. Now just use this query as the source for the report. You don't really need to write any code here. Now of course if you need to pass a value or some kind of parameter?

Well, then you can use this code:

Let's assume that the stored procedure returns data for a given invoice number.

So, your code would look like this:

dim strInvoiceNumber   as string
strInvoiceNumber = InputBox("Enter invoice number")

currentdb.QueryDefs("MyPass").sql = "EXEC StorProc " & strInvoiceNumber

' code here follows to open report
 docmd.OpenReport "MyInoice",acViewPreview

So, you can create a pass-thorough query, and type into the query any exec or command that would run/call the stored procedure. And as noted, if there are no parameters, then you don't need to write any code at all - just create the pass-though query, and use that as the source for the report.


问:
Copy and Paste a Cell to First Empty Row in Specific Column google sheets
I am trying to copy and paste values of cell J3 from Activity Report to the first empty cell in column L.

The cell to copy is fixed, but the cell to paste in is variable.

So far the code I am using has only been able to copy the values from J3 to the last row of column L instead of the first blank row from the top. Any attempt to manipulate the destination has been unsuccessful. I was able to have it paste at the top but it kept overwriting the same cell.

```<code>   function copyData() {
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sName = ss.getSheetName();

if (sName == 'Activity Report'){
  var source = ss.getRange("Activity Report!J3");
  var destSheet = ss.getSheetByName("Activity Report");
  var lastRow = destSheet.getLastRow();

  var destination = destSheet.getRange("L"+lastRow);
  destination.activate();
  source.copyTo(destination, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  };
}
</code>```

Thanks in advance!

答:
Copying data to first empty cell in Columnn L

Copy value from J3 to bottom of column L

```<code>function copyData() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Activity Report');
  sh.getRange(sh.getLastRow()+1,12).setValue(sh.getRange(3,10).getValue());
}
</code>```

Try this:

This will put it into the very first empty cell in column L which could be the lastRow()+1 if there are no blanks.

```<code>function runOne() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Activity Report');
  var f=false;
  var L=sh.getRange(1,12,sh.getLastRow()+1,1).getValues().map(function(r,i){if(!f && r[0].toString().length==0){f=true;return i+1;}else{return '';}}).filter(function(e){return e;});
  sh.getRange(L,12).setValue(sh.getRange(3,10).getValue());
}
</code>```

This uses reduce:

If nothing else it's a bit simpler.

```<code>function copyData() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Activity Report');
  var f=false;
  var L=sh.getRange(1,12,sh.getLastRow()+1,1).getValues().reduce(function(a,r,i){if(!f && r[0].toString().length==0){f=true;return a + i;}return a;},1);
  sh.getRange(L,12).setValue(sh.getRange(3,10).getValue());
}
</code>```

Array.map

Array.filter

Array.reduce

Body:
I am trying to copy and paste values of cell J3 from Activity Report to the first empty cell in column L.

The cell to copy is fixed, but the cell to paste in is variable.

So far the code I am using has only been able to copy the values from J3 to the last row of column L instead of the first blank row from the top. Any attempt to manipulate the destination has been unsuccessful. I was able to have it paste at the top but it kept overwriting the same cell.

   function copyData() {
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sName = ss.getSheetName();

if (sName == 'Activity Report'){
  var source = ss.getRange("Activity Report!J3");
  var destSheet = ss.getSheetByName("Activity Report");
  var lastRow = destSheet.getLastRow();

  var destination = destSheet.getRange("L"+lastRow);
  destination.activate();
  source.copyTo(destination, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  };
}

Thanks in advance!

Body:
Copying data to first empty cell in Columnn L

Copy value from J3 to bottom of column L

function copyData() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Activity Report');
  sh.getRange(sh.getLastRow()+1,12).setValue(sh.getRange(3,10).getValue());
}

Try this:

This will put it into the very first empty cell in column L which could be the lastRow()+1 if there are no blanks.

function runOne() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Activity Report');
  var f=false;
  var L=sh.getRange(1,12,sh.getLastRow()+1,1).getValues().map(function(r,i){if(!f && r[0].toString().length==0){f=true;return i+1;}else{return '';}}).filter(function(e){return e;});
  sh.getRange(L,12).setValue(sh.getRange(3,10).getValue());
}

This uses reduce:

If nothing else it's a bit simpler.

function copyData() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Activity Report');
  var f=false;
  var L=sh.getRange(1,12,sh.getLastRow()+1,1).getValues().reduce(function(a,r,i){if(!f && r[0].toString().length==0){f=true;return a + i;}return a;},1);
  sh.getRange(L,12).setValue(sh.getRange(3,10).getValue());
}

Array.map

Array.filter

Array.reduce


问:
How to construct org.jooq.Result for unit testing
I am writing unit tests for fetching records from Oracle DB using JOOQ library and I need to mock data returned by DSLContext's fetch() function. How can I create sample Result<Record> to be returned by mocked function? I googled it for few hours and could not find an answer.

答:
Try to use JOOQ's own mock API. Here are the official docs

You probably want to end up with something like that:

```<code>final MockDataProvider myMockProvider = new MockDataProvider() {
    @Override
    public MockResult[] execute(final MockExecuteContext context) throws SQLException {
        final DSLContext context = DSL.using(SQLDialect.ORACLE);
        final Result<Record> resultRecord = context.newResult(YOUR_TABLE_HERE);

        // customize your record with needed fields

        resultRecord.add(context.newRecord(YOUR_TABLE_HERE));

        return new MockResult[] { new MockResult(1, resultRecord) };
    }
};

final DSLContext mockedDSL = DSL.using(new MockConnection(myMockProvider), SQLDialect.ORACLE);

// here you go with your tests
</code>```

Body:
Try to use JOOQ's own mock API. Here are the official docs

You probably want to end up with something like that:

final MockDataProvider myMockProvider = new MockDataProvider() {
    @Override
    public MockResult[] execute(final MockExecuteContext context) throws SQLException {
        final DSLContext context = DSL.using(SQLDialect.ORACLE);
        final Result<Record> resultRecord = context.newResult(YOUR_TABLE_HERE);

        // customize your record with needed fields

        resultRecord.add(context.newRecord(YOUR_TABLE_HERE));

        return new MockResult[] { new MockResult(1, resultRecord) };
    }
};

final DSLContext mockedDSL = DSL.using(new MockConnection(myMockProvider), SQLDialect.ORACLE);

// here you go with your tests


问:
Getting Data out of a container
I wrote a function that creates new Input fields based on the number of input fields needed. That code is below.

```<code>for (i=0;i<number;i++){
    container.appendChild(document.createTextNode("Guest " + (i+1)));
    var input = document.createElement("input");
    input.id = "Guest" + i;
    container.appendChild(input);
    container.appendChild(document.createElement("br"));
    console.log(i.value);
</code>```

It creates a new Id for each input field. In the function below,depending on the number you set for i, the function creates a generated message.

```<code>function sendInput ()
{
    var guestNames = document.getElementById("Guest").value
    var personName = document.getElementById("people").value;
    var eventType = document.getElementById("event").value;
    var date = document.getElementById("date").value;
    var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date +  " Thank you for coming!!";
    document.getElementById('output').innerHTML = output.repeat(i);
}
</code>```

The problem is it is not collecting the data for guestNames. I am pretty new to JS but have searched and cannot find a solution to my problem. Any feedback wouls be helpful.

答:
You try to get node by id var guestNames = document.getElementById("Guest").value
But all nodes have a different id, like a Guest0,Guest1 etc. I am trying to write my own code, but your snippet isn't full. I hope I helped you.

Title: Getting Data out of a container

Body:
I wrote a function that creates new Input fields based on the number of input fields needed. That code is below.

for (i=0;i<number;i++){
    container.appendChild(document.createTextNode("Guest " + (i+1)));
    var input = document.createElement("input");
    input.id = "Guest" + i;
    container.appendChild(input);
    container.appendChild(document.createElement("br"));
    console.log(i.value);

It creates a new Id for each input field. In the function below,depending on the number you set for i, the function creates a generated message.

function sendInput ()
{
    var guestNames = document.getElementById("Guest").value
    var personName = document.getElementById("people").value;
    var eventType = document.getElementById("event").value;
    var date = document.getElementById("date").value;
    var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date +  " Thank you for coming!!";
    document.getElementById('output').innerHTML = output.repeat(i);
}

The problem is it is not collecting the data for guestNames. I am pretty new to JS but have searched and cannot find a solution to my problem. Any feedback wouls be helpful.


问:
Web Application to know database update
My web application (ASP.NET 4) connects to a database (SQL Server 2005). For every new row inserted in a certain table, I want the web app can do some process (like send  an email to me with new data).

How do I implement the system? My first though is having web app check the table SN column, and have a variable lastProcessedSN. And keep polling every minute. Is it possible to have DB notify web app when there's a new row being inserted?

Please advise, thanks.

EDIT:
Sending an email is just an example, not the exact thing I want to do. So this question is focusing on how to implement the trigger on MSSQL table insert to call my program.

答: You can write a trigger for that table so that when a new record comes to the table, it can call a dot net assembly.you can have the email sending code in your dot net assembly</p>

Title: Web Application to know database update


答:
IDs are difficult to work with in a dynamic environment, classes are generally the simplest solution. This code will convert your inputs to have classes, then loop through them and collect the names.

So change:

```<code>input.id = "Guest" + i;
</code>```

to

```<code>input.setAttribute("class","guest");
</code>```

And change

```<code>var guestNames = document.getElementById("Guest").value
</code>```

to:

```<code>var guests = document.querySelectorAll(".guest");
var guestNames = [];

guests.forEach(function(el){
  guestNames.push(el.value);
});

guestNames = guestNames.join(",");
</code>```

If you are wanting a message for EACH guest, then you would use the below function:

```<code>function sendInput ()
{
    var personName = document.getElementById("people").value;
    var eventType = document.getElementById("event").value;
    var date = document.getElementById("date").value;

    var guests = document.querySelectorAll(".guest");
    var guestNames = [];

   document.getElementById('output').innerHTML = "";

    guests.forEach(function(el){
     document.getElementById('output').innerHTML += "Dear " + el.value + " You have been invited to " + personName + "'s " + eventType + " on " + date +  " Thank you for coming!!";
    });
}
</code>```

Title: Getting Data out of a container

Body:
IDs are difficult to work with in a dynamic environment, classes are generally the simplest solution. This code will convert your inputs to have classes, then loop through them and collect the names.

So change:

input.id = "Guest" + i;

to

input.setAttribute("class","guest");

And change

var guestNames = document.getElementById("Guest").value

to:

var guests = document.querySelectorAll(".guest");
var guestNames = [];

guests.forEach(function(el){
  guestNames.push(el.value);
});

guestNames = guestNames.join(",");

If you are wanting a message for EACH guest, then you would use the below function:

function sendInput ()
{
    var personName = document.getElementById("people").value;
    var eventType = document.getElementById("event").value;
    var date = document.getElementById("date").value;

    var guests = document.querySelectorAll(".guest");
    var guestNames = [];

   document.getElementById('output').innerHTML = "";

    guests.forEach(function(el){
     document.getElementById('output').innerHTML += "Dear " + el.value + " You have been invited to " + personName + "'s " + eventType + " on " + date +  " Thank you for coming!!";
    });
}


问:
Middleware implementation not working for some routes
In my project, I have 2 different functions serving as middleware, which are in a separate file in a separate directory, and I have imported them in my route files.
However, one of the functions executes properly while the other throws and error

The first middleware function (which is functioning properly) is :-

```<code>isLoggedIn : function(req,res,next){
        if(req.isAuthenticated()){
            return next();
        }
        res.redirect("/login");
    },
</code>```

The other function (not working) is :-

```<code>checkCampgroundOwnership : function(req,res,next){
        if(req.isAuthenticated()){
                Campground.findById(req.params.id, function(err,foundCamp){
                    if(err){
                        res.redirect("back");
                    }
                    else{
                        if(foundCamp.author.id.equals(req.user._id)){
                            return next();
                        }
                        else{
                            res.redirect("back");
                        }
                    }
                })
            }
            else{
                res.redirect("back");
            }
        }
</code>```

I'm implementing them in my routes as follows :-

```<code>router.post("/", middleware.isLoggedIn, function(req,res){
    req.body.description = req.sanitize(req.body.description);
    Campground.create(req.body.camp, function(err,created){
        if(err){
            console.log(err);
        }
        else{
            created.author.id = req.user.id;
            created.author.username = req.user.username;
            created.save();
            res.redirect("/campgrounds");
        }
    })
})

router.put("/:id", middleware.checkCampgroundOwenership, function(req,res){
    Campground.findByIdAndUpdate(req.params.id, req.body.camp, function(err,result){
        if(err){
            console.log(err)
        }
        else{
            res.redirect("/campgrounds/"+ req.params.id);
        }
    })
})
</code>```

The error which is generated is as follows :-

Error: Route.get() requires a callback function but got a [object
  Undefined]

What is the problem and how to solve it

答:
You have a typo:

You've typed: checkCampgroundOwenership

Should be: checkCampgroundOwnership

Body:
In my project, I have 2 different functions serving as middleware, which are in a separate file in a separate directory, and I have imported them in my route files.
However, one of the functions executes properly while the other throws and error

The first middleware function (which is functioning properly) is :-

isLoggedIn : function(req,res,next){
        if(req.isAuthenticated()){
            return next();
        }
        res.redirect("/login");
    },

The other function (not working) is :-

checkCampgroundOwnership : function(req,res,next){
        if(req.isAuthenticated()){
                Campground.findById(req.params.id, function(err,foundCamp){
                    if(err){
                        res.redirect("back");
                    }
                    else{
                        if(foundCamp.author.id.equals(req.user._id)){
                            return next();
                        }
                        else{
                            res.redirect("back");
                        }
                    }
                })
            }
            else{
                res.redirect("back");
            }
        }

I'm implementing them in my routes as follows :-

router.post("/", middleware.isLoggedIn, function(req,res){
    req.body.description = req.sanitize(req.body.description);
    Campground.create(req.body.camp, function(err,created){
        if(err){
            console.log(err);
        }
        else{
            created.author.id = req.user.id;
            created.author.username = req.user.username;
            created.save();
            res.redirect("/campgrounds");
        }
    })
})

router.put("/:id", middleware.checkCampgroundOwenership, function(req,res){
    Campground.findByIdAndUpdate(req.params.id, req.body.camp, function(err,result){
        if(err){
            console.log(err)
        }
        else{
            res.redirect("/campgrounds/"+ req.params.id);
        }
    })
})

The error which is generated is as follows :-

Error: Route.get() requires a callback function but got a [object
  Undefined]

What is the problem and how to solve it


问:
How to activate Python virtual environment without admin privileges?
Python 3.8.3, Windows 10

I created a virtual environment using Python's virtualenv package, with this command:

```<code>python -m venv C:/<Path>
</code>```

Now when I try to activate the virtual environment with:

```<code>.\C:/<Path>/activate.bat
</code>```

I get the following error message:

```<code>This program is blocked by group policy. For more information, contact your system administrator.
</code>```

I unfortunately have no way of bypassing the admin blocks on this computer, is there anything I can do?

答:
try to switch symbol / on this \

```<code>.\C:<Path>\activate.bat
</code>```

In windows env activated like this

```<code>%venv_folder%\Scripts\activate.bat
</code>```

or u can use pipenv

1.

```<code>pip install pipenv
</code>```

2.

```<code>pipenv shell
</code>```

3.

```<code>pipenv install <lib_name>
</code>```

For activation env use

```<code>exit
</code>```

Body:
Python 3.8.3, Windows 10

I created a virtual environment using Python's virtualenv package, with this command:

python -m venv C:/<Path>

Now when I try to activate the virtual environment with:

.\C:/<Path>/activate.bat

I get the following error message:

This program is blocked by group policy. For more information, contact your system administrator.

I unfortunately have no way of bypassing the admin blocks on this computer, is there anything I can do?

Body:
try to switch symbol / on this \

.\C:<Path>\activate.bat

In windows env activated like this

%venv_folder%\Scripts\activate.bat

or u can use pipenv

1.

pip install pipenv

2.

pipenv shell

3.

pipenv install <lib_name>

For activation env use

exit


问:
How to print to screen and save to file in one-line?
Is it possible to print to screen and save to file in one-line?

The following saves to file:

```<code>with open('file.txt', 'a') as f:
   print('hello world', file=f)
</code>```

And currently to print to screen and save to file would have to do the following:

```<code>print['hello world')
print('hello world', file=f)
</code>```

I can't find any answers out there for one-line.

I guess a function can be defined to avoid lines in code, but still wondering if it is possible to do all in one line

答:
Try the snipette below, I had success with it in Jupyter Notebook</p>

```<code>f=open('file.txt','a');print('hello world');f.write('hello world');f.close()
</code>```

Body:
Is it possible to print to screen and save to file in one-line?

The following saves to file:

with open('file.txt', 'a') as f:
   print('hello world', file=f)

And currently to print to screen and save to file would have to do the following:

print['hello world')
print('hello world', file=f)

I can't find any answers out there for one-line.

I guess a function can be defined to avoid lines in code, but still wondering if it is possible to do all in one line

Body:
Try the snipette below, I had success with it in Jupyter Notebook

f=open('file.txt','a');print('hello world');f.write('hello world');f.close()