问:
Move tuple containing lambda
I am trying to implement a generic RAII cleanup. This looked like it was working, until I tried to use the move constructor:

```<code>#include <functional>
#include <tuple>
#include <utility>

template <typename R, typename D>
class Cleaner {
public:
  Cleaner() = default;
  Cleaner(R r, D d = {}) : data(std::move(d), std::move(r)), owns(true) {
  }
  ~Cleaner() {
    if (!owns) return;
    std::apply(
      [](auto&&... args){
        std::invoke(std::forward<decltype(args)>(args)...);
      },
      std::move(data)
    );
  }
  Cleaner(Cleaner&& other) noexcept {
    swap(*this, other);
  }
  Cleaner& operator=(Cleaner&& other) noexcept {
    swap(*this, other);
    return *this;
  }

  void release() { owns = false; }

  R& get() { return std::get<1>(data); }
  R const& get() const { return std::get<1>(data); }

  friend void swap(Cleaner& a, Cleaner& b) noexcept {
    using std::swap;
    swap(a.data, b.data);
    swap(a.owns, b.owns);
  }

private:
  std::tuple<D, R> data;
  bool owns = false;
};

#include <iostream>

int main() {
    auto c = Cleaner(0, [](int){ std::cout << "clean\n"; });
    auto a(std::move(c)); // <- this fails to compile
}
</code>```

(The compile error message is to long to copy here, but you can see it here: https://godbolt.org/z/5fqz5qTxT)

The message starts with:

source>: In instantiation of 'Cleaner<R, D>::Cleaner(Cleaner<R, D>&&) [with R = int; D = main()::<lambda(int)>]':
<source>:48:24:   required from here
<source>:20:37: error: no matching function for call to 'std::tuple<main()::<lambda(int)>, int>::tuple()'
   20 |   Cleaner(Cleaner&& other) noexcept {
      |                                     ^
In file included from /opt/compiler-explorer/gcc-trunk-20220208/include/c++/12.0.1/functional:54,
                 from <source>:1:
/opt/compiler-explorer/gcc-trunk-20220208/include/c++/12.0.1/tuple:1259:9: note: candidate: 'template<class _Alloc, class _U1, class _U2, typename std::enable_if<__is_explicitly_constructible<_U1, _U2>(), bool>::type <anonymous> > std::tuple<_T1, _T2>::tuple(std::allocator_arg_t, const _Alloc&, std::pair<_U1, _U2>&&) [with _U1 = _Alloc; _U2 = _U1; typename std::enable_if<std::_TupleConstraints<true, _T1, _T2>::__is_explicitly_constructible<_U1, _U2>(), bool>::type <anonymous> = _U2; _T1 = main()::<lambda(int)>; _T2 = int]'
 1259 |         tuple(allocator_arg_t __tag, const _Alloc& __a, pair<_U1, _U2>&& __in)
      |         ^~~~~
[...]
```

Can someone help me understand what the problem is so I can fix it?

答:
Your issue is that lambda is not default constructible (non-capturing ones are since C++20).

You might change constructor to:

```<code>Cleaner(Cleaner&& other) noexcept :
    data(std::move(other.data)),
    owns(other.owns)
{
    other.owns = false;
}
</code>```

Demo

Title: Move tuple containing lambda

Body:
I am trying to implement a generic RAII cleanup. This looked like it was working, until I tried to use the move constructor:

#include <functional>
#include <tuple>
#include <utility>

template <typename R, typename D>
class Cleaner {
public:
  Cleaner() = default;
  Cleaner(R r, D d = {}) : data(std::move(d), std::move(r)), owns(true) {
  }
  ~Cleaner() {
    if (!owns) return;
    std::apply(
      [](auto&&... args){
        std::invoke(std::forward<decltype(args)>(args)...);
      },
      std::move(data)
    );
  }
  Cleaner(Cleaner&& other) noexcept {
    swap(*this, other);
  }
  Cleaner& operator=(Cleaner&& other) noexcept {
    swap(*this, other);
    return *this;
  }

  void release() { owns = false; }

  R& get() { return std::get<1>(data); }
  R const& get() const { return std::get<1>(data); }

  friend void swap(Cleaner& a, Cleaner& b) noexcept {
    using std::swap;
    swap(a.data, b.data);
    swap(a.owns, b.owns);
  }

private:
  std::tuple<D, R> data;
  bool owns = false;
};

#include <iostream>

int main() {
    auto c = Cleaner(0, [](int){ std::cout << "clean\n"; });
    auto a(std::move(c)); // <- this fails to compile
}

(The compile error message is to long to copy here, but you can see it here: https://godbolt.org/z/5fqz5qTxT)

The message starts with:

source>: In instantiation of 'Cleaner<R, D>::Cleaner(Cleaner<R, D>&&) [with R = int; D = main()::<lambda(int)>]':
<source>:48:24:   required from here
<source>:20:37: error: no matching function for call to 'std::tuple<main()::<lambda(int)>, int>::tuple()'
   20 |   Cleaner(Cleaner&& other) noexcept {
      |                                     ^
In file included from /opt/compiler-explorer/gcc-trunk-20220208/include/c++/12.0.1/functional:54,
                 from <source>:1:
/opt/compiler-explorer/gcc-trunk-20220208/include/c++/12.0.1/tuple:1259:9: note: candidate: 'template<class _Alloc, class _U1, class _U2, typename std::enable_if<__is_explicitly_constructible<_U1, _U2>(), bool>::type <anonymous> > std::tuple<_T1, _T2>::tuple(std::allocator_arg_t, const _Alloc&, std::pair<_U1, _U2>&&) [with _U1 = _Alloc; _U2 = _U1; typename std::enable_if<std::_TupleConstraints<true, _T1, _T2>::__is_explicitly_constructible<_U1, _U2>(), bool>::type <anonymous> = _U2; _T1 = main()::<lambda(int)>; _T2 = int]'
 1259 |         tuple(allocator_arg_t __tag, const _Alloc& __a, pair<_U1, _U2>&& __in)
      |         ^~~~~
[...]

Can someone help me understand what the problem is so I can fix it?

Body:
Your issue is that lambda is not default constructible (non-capturing ones are since C++20).

You might change constructor to:

Cleaner(Cleaner&& other) noexcept :
    data(std::move(other.data)),
    owns(other.owns)
{
    other.owns = false;
}

Demo


来源: stackexchange

问:
is it possible to define multidim arrays with #define directive in pure C?
I want to manage my packs of string constants separately from the computational code. I want to do it in separate file.

So, I need to create a multidim array of strings and conclude it under a STR_PACK_X.

If it is possible, can anyone route me right way with #define multidim-string-constants syntax?

Help me please, what's wrong with that attempt:

```<code>#define STR_PACK_X \
({ \
\ // comm1
    { "string1", "string2", "string3" }, \
\ // comm2
    { "string11", "string22", "string33" }, \
\ // comm3
    { "string111", "string222", "string333" } \
})
</code>```

I want to use it like that:

```<code>int line_lim = 4, word_lim = 4, char_lim = 50;

if (flag1)
{
  char array[line_lim][word_lim][char_lim] = STR_PACK_1;
  /* array processing */
  ...
}
if (flag2)
{
  char array[line_lim][word_lim][char_lim] = STR_PACK_2;
  /* array processing */
  ...
}
</code>```

答:
You have multiple issues:

You want to create an initializer list. For arrays this has to look like this: int arr[] = { ... } while your replacement text puts everything into additional brackets ({ ... }). That only produces one single value, not an array.

In macros, the replacement can be continued on the next line by putting a \ as last character in the line. No characters (also no comments) shall follow afterwards.

The issues above arise when you want to initialize a normal array with constant dimensions.
What you have is a variable length array (VLA). These cannot be initialized at all.

ContentLicense: CC BY-SA 4.0

Body:
I want to manage my packs of string constants separately from the computational code. I want to do it in separate file.

So, I need to create a multidim array of strings and conclude it under a STR_PACK_X.

If it is possible, can anyone route me right way with #define multidim-string-constants syntax?

Help me please, what's wrong with that attempt:

#define STR_PACK_X \
({ \
\ // comm1
    { "string1", "string2", "string3" }, \
\ // comm2
    { "string11", "string22", "string33" }, \
\ // comm3
    { "string111", "string222", "string333" } \
})

I want to use it like that:

int line_lim = 4, word_lim = 4, char_lim = 50;

if (flag1)
{
  char array[line_lim][word_lim][char_lim] = STR_PACK_1;
  /* array processing */
  ...
}
if (flag2)
{
  char array[line_lim][word_lim][char_lim] = STR_PACK_2;
  /* array processing */
  ...
}


问:
Unit testing NodeJS stream with jest - timeout issue
Given the following NodeJS Transform Stream:

```<code>class ObjectToCSVTransform extends Transform {
  private hasSetHeaders: boolean;

  constructor() {
    super({ objectMode: true });
    this.hasSetHeaders = false;
  }

  static create(): ObjectToCSVTransform {
    return new this();
  }

  _write(
    object: Record<string, unkwnown>,
    _encoding: BufferEncoding,
    callback: TransformCallback
  ): void {
    this.push(this.generateCSV(telemetry));
    callback();
  }

  private generateCSV(object: Record<string, unkwnown>): string {
    let csv = '';

    if (!this.hasSetHeaders) {
      csv += this.createCSVHeaders(object);
      this.hasSetHeaders = true;
    }

    csv += this.createRecord(object);

    return csv;
  }

  private createCSVHeaders(object: Record<string, unkwnown>): string {
    return `${Object.keys(object)}\n`;
  }

  private createCSVRecord(object: Record<string, unkwnown>): string {
    return `${Object.values(object)}\n`;
  }
}
</code>```

I implemented the following test case (using jest), to test that given a stream of plain objects of the "same type" the expected output is a valid CSV representation of them:

```<code>describe('object to csv stream', () => {
  const items: Record<string, unknown> = [
    { foo: 1, bar: 2, baz: 3 },
    { foo: 10, bar: 20, baz: 30 },
    { foo: 100, bar: 200, baz: 300 },
  ];

  it('should transform a list of items to csv', (done) => {
    const expectedCsv = 'foo,bar,baz\n1,2,3\n10,20,30\n100,200,300\n';
    let csv = '';

    Readable.from(items)
      .pipe(ObjectToCSVTransform.create())
      .on('data', (csvResult) => {
        csv += csvResult;
        console.log(csvResult); // just for debugging purposes
      })
      .on('end', () => {
        console.log('streaming ended'); // just for debugging purposes
        expect(csv).toEqual(expectedCsv);
        done();
      });
  });
});
</code>```

Apparently, during the test case implementation I wanted to see how my test case failed: the stream seemed to work as it logged every expected csv result line and the 'streaming ended' message also at the end once the stream ended, but the test execution did not finish at all then. It was jest that actually finished the execution after exceeding the default timeout:

thrown: "Exceeded timeout of 5000 ms for a test. Use
jest.setTimeout(newTimeout) to increase the timeout value, if this is
a long-running test."

What am I missing here?

Note that I am currently using the jest callback to notify when the async operation has finished.

答:
There is something that I was missing in my test case that wasn't handling asynchrony correctly at all and therefore was making the Exceeded timeout exception to be thrown by jest:

surrounding the assertion by a try-catch and having the done() callback called in case the assertion failed.

```<code>.on('end', () => {
  try {
    expect(csv).toEqual(expectedCsv);
    done();
  } catch (error) {
    done(error);
  }
});
</code>```

For more info / reference, check the jest docs: https://jestjs.io/docs/asynchronous#callbacks

Body:
Given the following NodeJS Transform Stream:

class ObjectToCSVTransform extends Transform {
  private hasSetHeaders: boolean;

  constructor() {
    super({ objectMode: true });
    this.hasSetHeaders = false;
  }

  static create(): ObjectToCSVTransform {
    return new this();
  }

  _write(
    object: Record<string, unkwnown>,
    _encoding: BufferEncoding,
    callback: TransformCallback
  ): void {
    this.push(this.generateCSV(telemetry));
    callback();
  }

  private generateCSV(object: Record<string, unkwnown>): string {
    let csv = '';

    if (!this.hasSetHeaders) {
      csv += this.createCSVHeaders(object);
      this.hasSetHeaders = true;
    }

    csv += this.createRecord(object);

    return csv;
  }

  private createCSVHeaders(object: Record<string, unkwnown>): string {
    return `${Object.keys(object)}\n`;
  }

  private createCSVRecord(object: Record<string, unkwnown>): string {
    return `${Object.values(object)}\n`;
  }
}

I implemented the following test case (using jest), to test that given a stream of plain objects of the "same type" the expected output is a valid CSV representation of them:

describe('object to csv stream', () => {
  const items: Record<string, unknown> = [
    { foo: 1, bar: 2, baz: 3 },
    { foo: 10, bar: 20, baz: 30 },
    { foo: 100, bar: 200, baz: 300 },
  ];

  it('should transform a list of items to csv', (done) => {
    const expectedCsv = 'foo,bar,baz\n1,2,3\n10,20,30\n100,200,300\n';
    let csv = '';

    Readable.from(items)
      .pipe(ObjectToCSVTransform.create())
      .on('data', (csvResult) => {
        csv += csvResult;
        console.log(csvResult); // just for debugging purposes
      })
      .on('end', () => {
        console.log('streaming ended'); // just for debugging purposes
        expect(csv).toEqual(expectedCsv);
        done();
      });
  });
});

Apparently, during the test case implementation I wanted to see how my test case failed: the stream seemed to work as it logged every expected csv result line and the 'streaming ended' message also at the end once the stream ended, but the test execution did not finish at all then. It was jest that actually finished the execution after exceeding the default timeout:

thrown: "Exceeded timeout of 5000 ms for a test. Use
jest.setTimeout(newTimeout) to increase the timeout value, if this is
a long-running test."

What am I missing here?

Note that I am currently using the jest callback to notify when the async operation has finished.

Body:
There is something that I was missing in my test case that wasn't handling asynchrony correctly at all and therefore was making the Exceeded timeout exception to be thrown by jest:

surrounding the assertion by a try-catch and having the done() callback called in case the assertion failed.

.on('end', () => {
  try {
    expect(csv).toEqual(expectedCsv);
    done();
  } catch (error) {
    done(error);
  }
});

For more info / reference, check the jest docs: https://jestjs.io/docs/asynchronous#callbacks


问:
How to replace body text in MIME message?
I am trying to send an automated email to various users with the lake that they are subscribed to changing:

message = MIMEMultipart()
message['From'] = email  # Sender
message['Subject'] = "Algae Bloom Alert\n"  # Subject

for user in subscriber_dict:
    sms_gateway = subscriber_dict[user]['email']
    message['To'] = subscriber_dict[user]['email']
    body = (
        f"This is an algae alert for Lake {subscriber_dict[user]['lake']}.\n\n"
        f"Sent at {sent_time_date} {sent_time_time}"
    )
    message.attach(MIMEText(body, 'plain'))  # Attaching body to email
    sms = message.as_string()
    server.sendmail(email, sms_gateway, sms)

    # Reset body here ideally

    print(f"Email sent at {formatted_time}")
```

However, when the emails are sent, each successive email contains the contents from the emails prior to it. Does anyone know how I can reset the body so that I am not attaching to the previous bodies but rather writing new ones?

答:
Don't reuse the same message. Create a new one inside the loop.

Your code seems to be written for Python 3.5 or earlier. The email library was overhauled in 3.6 and is now quite a bit more versatile and logical. Probably throw away what you have and start over with the examples from the email documentation.

```<code>from email.message import EmailMessage
...

for user in subscriber_dict:
    message = EmailMessage()
    message['From'] = email
    message['Subject'] = "Algae Bloom Alert"  # no \n
    message['To'] = subscriber_dict[user]['email']
    message.set_content(
        f"This is an algae alert for Lake {subscriber_dict[user]['lake']}.\n\n"
        f"Sent at {sent_time_date} {sent_time_time}"
    )
    server.send_message(message)

    print(f"Email sent at {formatted_time}")
</code>```

You might want to avoid calling your sender variable email to avoid shadowing the email library, although in this example it doesn't really matter.

With .set_content() you could actually reuse the same message over and over but there is no actual benefit from that, and the problems if you fail to replace some part of an earlier message by mistake could be ugly. (For example, a typo could cause you to send the same message to the same recipient as many times as you have users!)

Body:
I am trying to send an automated email to various users with the lake that they are subscribed to changing:

message = MIMEMultipart()
message['From'] = email  # Sender
message['Subject'] = "Algae Bloom Alert\n"  # Subject

for user in subscriber_dict:
    sms_gateway = subscriber_dict[user]['email']
    message['To'] = subscriber_dict[user]['email']
    body = (
        f"This is an algae alert for Lake {subscriber_dict[user]['lake']}.\n\n"
        f"Sent at {sent_time_date} {sent_time_time}"
    )
    message.attach(MIMEText(body, 'plain'))  # Attaching body to email
    sms = message.as_string()
    server.sendmail(email, sms_gateway, sms)

    # Reset body here ideally

    print(f"Email sent at {formatted_time}")

However, when the emails are sent, each successive email contains the contents from the emails prior to it. Does anyone know how I can reset the body so that I am not attaching to the previous bodies but rather writing new ones?

Body:
Don't reuse the same message. Create a new one inside the loop.

Your code seems to be written for Python 3.5 or earlier. The email library was overhauled in 3.6 and is now quite a bit more versatile and logical. Probably throw away what you have and start over with the examples from the email documentation.

from email.message import EmailMessage
...

for user in subscriber_dict:
    message = EmailMessage()
    message['From'] = email
    message['Subject'] = "Algae Bloom Alert"  # no \n
    message['To'] = subscriber_dict[user]['email']
    message.set_content(
        f"This is an algae alert for Lake {subscriber_dict[user]['lake']}.\n\n"
        f"Sent at {sent_time_date} {sent_time_time}"
    )
    server.send_message(message)

    print(f"Email sent at {formatted_time}")

You might want to avoid calling your sender variable email to avoid shadowing the email library, although in this example it doesn't really matter.

With .set_content() you could actually reuse the same message over and over but there is no actual benefit from that, and the problems if you fail to replace some part of an earlier message by mistake could be ugly. (For example, a typo could cause you to send the same message to the same recipient as many times as you have users!)


问:
Write svg latex into a canvas html
My goal is to record maths scripts running on the canvas and at the same time record sound from the mic (I am a math teacher). I would like very much to allow latex formulas. Of course latex formulas do not write directly to canvas. MathJax can produce SVG elements. I wonder if it is possible to go from SVG->image->canvas, using javascript. I don't care if the obtained image on canvas is a little blured.
I couldn't find good examples of this yet on the internet.
Thanks!</p>

答:
Indeed there is no Latex to canvas direct way.

You can however draw an SVG over a canvas. See this Q/A to see how to proceed from an SVG in the DOM (which MathJax should give you).

Title: Write svg latex into a canvas html


问:
how to change starting position of a sphere in threejs
I created a 3D Earth using three.js that rotates, but the problem is that it starts spinning over the ocean.
i triedto change starting position using matrixWorld but didn't change anything
can someone help plz
here is my js:

...
const earthgeometry = new THREE.SphereGeometry(0.344,64,32);

```<code>            const eatrhmaterial = new THREE.MeshPhongMaterial({
                roughness: 1,
                metalness:0,
                map: THREE.ImageUtils.loadTexture('static/img/earthmap1k.jpg'),
                bumpMap: THREE.ImageUtils.loadTexture('static/img/earthbump.jpg'),
                bumpScale: 0.3,
            });

            const earthmesh = new THREE.Mesh(earthgeometry,eatrhmaterial);
            earthmesh.position.set (0.49,0.035,0.58);
            earthmesh.matrixWorld.setPosition(new THREE.Vector3(100, 100, 100));
</code>```

...

答:
The same way you set a position, you can set a rotation of your object.

const earthgeometry = new THREE.SphereGeometry(0.344,64,32);

const earthmaterial = new THREE.MeshPhongMaterial({
//material definition here
});

const earthmesh = new THREE.Mesh(earthgeometry,earthmaterial);
earthmesh.position.set (0.49,0.035,0.58);
earthmesh.rotation.set (0,1.1,0);//or any other values
```

remember :

rotation are in radians: 360° = 2*Math.PI

Y axis is the vertical one

Body:
I created a 3D Earth using three.js that rotates, but the problem is that it starts spinning over the ocean.
i triedto change starting position using matrixWorld but didn't change anything
can someone help plz
here is my js:

...
const earthgeometry = new THREE.SphereGeometry(0.344,64,32);

            const eatrhmaterial = new THREE.MeshPhongMaterial({
                roughness: 1,
                metalness:0,
                map: THREE.ImageUtils.loadTexture('static/img/earthmap1k.jpg'),
                bumpMap: THREE.ImageUtils.loadTexture('static/img/earthbump.jpg'),
                bumpScale: 0.3,
            });

            const earthmesh = new THREE.Mesh(earthgeometry,eatrhmaterial);
            earthmesh.position.set (0.49,0.035,0.58);
            earthmesh.matrixWorld.setPosition(new THREE.Vector3(100, 100, 100));

...

Body:
The same way you set a position, you can set a rotation of your object.

const earthgeometry = new THREE.SphereGeometry(0.344,64,32);

const earthmaterial = new THREE.MeshPhongMaterial({
//material definition here
});

const earthmesh = new THREE.Mesh(earthgeometry,earthmaterial);
earthmesh.position.set (0.49,0.035,0.58);
earthmesh.rotation.set (0,1.1,0);//or any other values

remember :

rotation are in radians: 360° = 2*Math.PI

Y axis is the vertical one


问:
How to Invert column values in pandas - pythonic way?
I have a dataframe like as shown below

```<code>cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,1,1,0,0]})
</code>```

My objective is to

a) replace 0s as 1s AND 1s as 0s in Label column

I was trying something like the below

```<code>cdf.assign(invert_label=cdf.Label.loc[::-1].reset_index(drop=True)) #not work
cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0')
</code>```

'
but this doesn't work. It reverses the order

I expect my output to be like as shown below

```<code>    Id  Label
0   1   0
1   2   0
2   3   0
3   4   1
4   5   1
</code>```

答:
You could map the not function as well -

import operator
cdf['Label'].map(operator.not_).astype('int')
```

Body:
I have a dataframe like as shown below

cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,1,1,0,0]})

My objective is to

a) replace 0s as 1s AND 1s as 0s in Label column

I was trying something like the below

cdf.assign(invert_label=cdf.Label.loc[::-1].reset_index(drop=True)) #not work
cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0')

'
but this doesn't work. It reverses the order

I expect my output to be like as shown below

    Id  Label
0   1   0
1   2   0
2   3   0
3   4   1
4   5   1


问:
Cannot convert undefined or null to object or not length
If you put a value in every input, it works normally. However, errors appear even if only one input is empty.
nameValue.length, an error appears that you cannot work on the length.
Object.values(nameValue).length, the error  'Cannot convert undefined or null to object' appears.

const [values, setValues] = useState({
    nameValue: '',
    numberValue: '',
    contentValue: '',
  });

  const { nameValue, numberValue, contentValue } = values;

  const handleNumber = e => {
    const { value, name } = e.target;

    setValues({
      ...values,
      [name]: value,
    });
  };
```
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
    if (numberValue.length === 11) {
      setValues({
        numberValue: numberValue.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3'),
      });
    } else if (numberValue.length === 13) {
      setValues({
        numberValue: numberValue
          .replace(/-/g, '')
          .replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3'),
      });
    }
  }, [numberValue]);
</code>```

const handleSend = e => {
    e.preventDefault();
    //console.log(typeof stringify(nameValue) === 'undefined');

    const nameValueTrue =
      Object.values(nameValue).length > 4 ||
      Object.values(nameValue).length < 1 ||
      typeof nameValue !== 'string' ||
      typeof nameValue === 'undefined';

    const numberValueTrue =
      Object.values(numberValue).length < 13 ||
      Object.values(numberValue).length > 14;

    const contentValueTrue =
      typeof contentValue !== 'string' ||
      Object.values(contentValue).length < 2;

    const error = !e.target.value;

    if (nameValueTrue) {
      alert('이름을 확인해주세요.');
      console.log('name안');
    } else if (numberValueTrue) {
      console.log('number');
      alert('휴대폰번호를 확인해주세요.');
    } else if (contentValueTrue) {
      console.log('content');
      alert('내용을 확인해주세요.');
    } else {
      goto();
    }
  };
```
<pre class="lang-js prettyprint-override"><code><ContentBox>
          <div>Name</div>
          <ContentInput
            name="nameValue"
            value={nameValue || undefined}
            //value={nameValue || ''}
            //value={nameValue}
            onChange={handleNumber}
          />
        </ContentBox>
        <ContentBox>
          <div>Phone Number</div>
          <ContentInput
            name="numberValue"
            value={numberValue || undefined}
            //value={numberValue || ''}
            //value={numberValue}
            onChange={handleNumber}
          />
        </ContentBox>
        <ContentBox>
          <div>Content</div>
          <ContentInput
            placeholder="내용 입력."
            name="contentValue"
            value={contentValue || undefined}
            //value={contentValue || ''}
            //value={contentValue}
            onChange={handleNumber}
          />
        </ContentBox>
        <Submit onClick={handleSend}>Send</Submit>
</code>```

答: In your useEffect, you're overwriting the whole values object to just be numberValue. You need to spread the object there too, like you have in handleNumber</p>

Body:
If you put a value in every input, it works normally. However, errors appear even if only one input is empty.
nameValue.length, an error appears that you cannot work on the length.
Object.values(nameValue).length, the error  'Cannot convert undefined or null to object' appears.

const [values, setValues] = useState({
    nameValue: '',
    numberValue: '',
    contentValue: '',
  });

  const { nameValue, numberValue, contentValue } = values;

  const handleNumber = e => {
    const { value, name } = e.target;

    setValues({
      ...values,
      [name]: value,
    });
  };

useEffect(() => {
    if (numberValue.length === 11) {
      setValues({
        numberValue: numberValue.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3'),
      });
    } else if (numberValue.length === 13) {
      setValues({
        numberValue: numberValue
          .replace(/-/g, '')
          .replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3'),
      });
    }
  }, [numberValue]);

const handleSend = e => {
    e.preventDefault();
    //console.log(typeof stringify(nameValue) === 'undefined');

    const nameValueTrue =
      Object.values(nameValue).length > 4 ||
      Object.values(nameValue).length < 1 ||
      typeof nameValue !== 'string' ||
      typeof nameValue === 'undefined';

    const numberValueTrue =
      Object.values(numberValue).length < 13 ||
      Object.values(numberValue).length > 14;

    const contentValueTrue =
      typeof contentValue !== 'string' ||
      Object.values(contentValue).length < 2;

    const error = !e.target.value;

    if (nameValueTrue) {
      alert('이름을 확인해주세요.');
      console.log('name안');
    } else if (numberValueTrue) {
      console.log('number');
      alert('휴대폰번호를 확인해주세요.');
    } else if (contentValueTrue) {
      console.log('content');
      alert('내용을 확인해주세요.');
    } else {
      goto();
    }
  };

<ContentBox>

Name

          <ContentInput
            name="nameValue"
            value={nameValue || undefined}
            //value={nameValue || ''}
            //value={nameValue}
            onChange={handleNumber}
          />
        </ContentBox>
        <ContentBox>

Phone Number

          <ContentInput
            name="numberValue"
            value={numberValue || undefined}
            //value={numberValue || ''}
            //value={numberValue}
            onChange={handleNumber}
          />
        </ContentBox>
        <ContentBox>

Content

          <ContentInput
            placeholder="내용 입력."
            name="contentValue"
            value={contentValue || undefined}
            //value={contentValue || ''}
            //value={contentValue}
            onChange={handleNumber}
          />
        </ContentBox>
        <Submit onClick={handleSend}>Send</Submit>


问:
JIRA 3.13 dashboard show ticket with specific columns
I am using JIRA 3.13, I want to show list of tickets (based on a certain filter) in the dashboard with a column of my choice. For example, I want to show the ticket name, description, and resolution date (or a column of my choice). Is this possible? I use "Show saved Filter", the one that came with JIRA, but it does not allow me to do any customization.

Does anyone has a solution of how to have this showed in JIRA dashboard? Do I need to install a certain for this? Is it free? How do I install it?

Thanks all for the help!

答:
There is a paid portlet that we can use to do this. The portlet is called "Jira Show Saved Filter With Columns" made by jPlugs.com. We have to pay ~$200.

Installation is pretty simple but requires to bring down JIRA (restart). Anyway, the steps is:
1. Put the jar file in WEB-INF/lib
2. Restart JIRA

The company offer 30 days trial. In order to get the trial key, you need to create an account in their website and then generate the trial key also from their website. Make sure you check the version of the portlet that you install. For me, I use version 2.03 which looks like the latest that was released for my JIRA.

Hopefully, this info will help others.

ContentLicense: CC BY-SA 3.0


问:
Make div bigger then its parent
is there any way how can I make div bigger then its parent? I know its bad practice.
Basically I have div that is small and I need to create div inside which will be through entire window. But cant find way how to do it.
Thanks for any help.</p>

答:
You can use absolute sizing in CSS to have a child div be larger than the parent. You will also need to add in the top and left attributes and set them to 0. This will frame the div to begin in the top left corner.

If you want a div to be the full width and height of the viewport, use the following CSS:

.parent {
  position: relative;
  width: 120px;
  height: 120px;
  border: 1px solid red;
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  border: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='parent'>
  <div class='child'>
  </div>
</div></code>```

This will allow the div to resize based on the user's screen dimensions.

More on CSS sizing can be found here.

Title: Make div bigger then its parent

Body:
You can use absolute sizing in CSS to have a child div be larger than the parent. You will also need to add in the top and left attributes and set them to 0. This will frame the div to begin in the top left corner.

If you want a div to be the full width and height of the viewport, use the following CSS:

.parent {
  position: relative;
  width: 120px;
  height: 120px;
  border: 1px solid red;
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  border: 1px solid blue;
}

<div class='parent'>
  <div class='child'>
  </div>
</div>

This will allow the div to resize based on the user's screen dimensions.

More on CSS sizing can be found here.


问:
Shopware 6 custom product fields in tabs
I am completely new to the the Shopware (6) community and I am still learning how to code in Symfony and Vue.js.

After trying some how to's in the developer wiki, I wanted to try some coding by myself.

I would like to combine https://docs.shopware.com/en/shopware-platform-dev-en/how-to/add-admin-new-field and https://docs.shopware.com/en/shopware-platform-dev-en/how-to/new-tab-admin?category=shopware-platform-dev-en/how-to into one functionallity (Product tabs with custom admin fields).

However, when I use the v-model attribute into an input field, the complete tab will turn white and the following error is outputted in the console: product is not defined.

My guess is that the model needs to be imported into the module (I can't find this anywhere into the docs).

Can someone tell me what I have to do to make this work? My current source code can be found here: https://github.com/Millerdigital-matthew/miller-product-upsells

答:
As I understand, you need to change your index.js as follows:

```<code>const { Component } = Shopware;
const { mapState } = Component.getComponentHelper();

Component.register('...', {
    computed: {
        ...mapState('swProductDetail', [
            'product'
        ]),
    }
});
</code>```

Body:
As I understand, you need to change your index.js as follows:

const { Component } = Shopware;
const { mapState } = Component.getComponentHelper();

Component.register('...', {
    computed: {
        ...mapState('swProductDetail', [
            'product'
        ]),
    }
});


问:
Vscode - Python Debugger: unrecognized arguments
I'm trying to debug some Python code I have which I can run with no problem by typing the following in bash:

```<code>CUDA_VISIBLE_DEVICES=0 \
python test_multi.py \
--experiment_name 128_shortcut1_inject1_none \
--test_atts Eyeglasses \
--test_ints -1.0
</code>```

I've created this json config file for VScode:

```<code>{
    "version": "0.2.0",
    "configurations": [

        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "<absolute_path>/test_multi.py",
            "console": "integratedTerminal",
            "env": [{ "name":"CUDA_VISIBLE_DEVICES", "value":0}],
            "args": ["--experiment_name 128_shortcut1_inject1_none", "--test_atts Eyeglasses", "--test_ints -1"]
        }
    ]
}
</code>```

but I keep getting

test_multi.py: error: unrecognized arguments: --experiment_name 128_shortcut1_inject1_none --test_atts Eyeglasses --test_ints -1

答:
The way Brett shows didn't work with my case. I want to use the Number "1" GPU for debugging, so I added
"env": {"CUDA_VISIBLE_DEVICES":"1"}, to the launcher.json file.

Body:
I'm trying to debug some Python code I have which I can run with no problem by typing the following in bash:

CUDA_VISIBLE_DEVICES=0 \
python test_multi.py \
--experiment_name 128_shortcut1_inject1_none \
--test_atts Eyeglasses \
--test_ints -1.0

I've created this json config file for VScode:

{
    "version": "0.2.0",
    "configurations": [

        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "<absolute_path>/test_multi.py",
            "console": "integratedTerminal",
            "env": [{ "name":"CUDA_VISIBLE_DEVICES", "value":0}],
            "args": ["--experiment_name 128_shortcut1_inject1_none", "--test_atts Eyeglasses", "--test_ints -1"]
        }
    ]
}

but I keep getting

test_multi.py: error: unrecognized arguments: --experiment_name 128_shortcut1_inject1_none --test_atts Eyeglasses --test_ints -1


问:
why does this for loop in C++ using getline() work
I compiled this nested for loop in C++. It works, however I don't understand why. Can you please explain the mechanics, and also any information on why the push_back() is allowed in addition to the increment.

```<code>for (std::string line; std::getline(in, line); text->push_back(line), ++ln) // why does this work?
{
  // do something
  std::istringstream iss(line);
  for (std::string word; iss>>word;) // why does this work?
    // do something
};
</code>```

text is a shared_ptr<vector<string>>.

答:
The for loop

```<code>for (A; B; C)
{
    D;
}
</code>```

is equivalent to

```<code>{
    A;
    while (B)
    {
        D;
        C;
    }
}
</code>```

and any of A, B, C, and D can be empty.

If those parts are syntactically correct in the while loop, they are also correct in the corresponding for loop.

So your nested loop is equivalent to

```<code>{

    std::string line;
    while (std::getline(in, line))
    {
        std::istringstream iss(line);
        {
            std::string word;
            while (iss>>word)
            {
                // do something
            }
        }
        text->push_back(line), ++ln;
    }
}
</code>```

Note that the push_back line uses the comma operator for sequencing because the semicolon is the delimiter in the for-loop header.

Body:
I compiled this nested for loop in C++. It works, however I don't understand why. Can you please explain the mechanics, and also any information on why the push_back() is allowed in addition to the increment.

for (std::string line; std::getline(in, line); text->push_back(line), ++ln) // why does this work?
{
  // do something
  std::istringstream iss(line);
  for (std::string word; iss>>word;) // why does this work?
    // do something
};

text is a shared_ptr<vector<string>>.

Body:
The for loop

for (A; B; C)
{
    D;
}

is equivalent to

{
    A;
    while (B)
    {
        D;
        C;
    }
}

and any of A, B, C, and D can be empty.

If those parts are syntactically correct in the while loop, they are also correct in the corresponding for loop.

So your nested loop is equivalent to

{

    std::string line;
    while (std::getline(in, line))
    {
        std::istringstream iss(line);
        {
            std::string word;
            while (iss>>word)
            {
                // do something
            }
        }
        text->push_back(line), ++ln;
    }
}

Note that the push_back line uses the comma operator for sequencing because the semicolon is the delimiter in the for-loop header.


问:
How to control transitions with multiple CSS class assignments from a single Javascript function?
I have one div, with buttons that trigger JS functions to add/remove CSS classes to the div. I understand this is a common way of doing simple animations ("transitions"). Try pressing the first two buttons, one after another. The red div will teleport up and become semi transparent, then fade in and slide back down. It always works.

The third button simply executes the same code as the first two buttons, but from one function. I expected it to have the same visible effect: the div immediately would jump up from the translate and be transparent, then during the course of 1 second it would slide back to its normal spot and fade in to full opacity. But it does not - the button has no visible effect.

Why? How can I make this work?

Here is the JS, see the whole thing at the codepen link.

```<code>const div = document.getElementById('red-box')

function translateUp() {
  div.classList.remove('no-translate');
  div.classList.add('translate-up');
}

function noTranslate() {
  div.classList.remove('translate-up');
  div.classList.add('no-translate');
}

//why does this function not show any transition animation?
function both() {
  translateUp();
  noTranslate();
}
</code>```

https://codepen.io/DMcCreepy/pen/BampPyB

No jQuery please :)

答:
You are relying on the div getting rerendered and all its properties being recomputed before switching the class again with the second function. I am not sure entirely what order things are done in under the hood, but I am sure you cannot rely on constructions like this working in general. It is true that switching classes is a common way to do animations and maybe it is possible to work out a solution like that, but I have provided a workaround using a CSS animation. You can read more about animations here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations

const div = document.getElementById('red-box')

div.addEventListener('animationend', reset);
function reset() {
  div.classList.remove('dropin');
}
function both() {
  div.classList.add('dropin');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  display: block;
}

.box {
  height: 70px;
  width: 80px;
  font-size: 50px;
  background-color: red;
  animation-duration: 1s;
  animation-fill-mode: forwards;
  animation-name: none;
}
.box.dropin {
  animation-name: dropin;
}
@keyframes dropin {
  from {
    transform: translate(0, -40px);
    opacity: 0.1;
  }
  to {
    transform: translate(0, 0);
    opacity: 1;
  }
}</code>```

div

<button onclick='both()'>Do Both</button>```

Body:
I have one div, with buttons that trigger JS functions to add/remove CSS classes to the div. I understand this is a common way of doing simple animations ("transitions"). Try pressing the first two buttons, one after another. The red div will teleport up and become semi transparent, then fade in and slide back down. It always works.

The third button simply executes the same code as the first two buttons, but from one function. I expected it to have the same visible effect: the div immediately would jump up from the translate and be transparent, then during the course of 1 second it would slide back to its normal spot and fade in to full opacity. But it does not - the button has no visible effect.

Why? How can I make this work?

Here is the JS, see the whole thing at the codepen link.

const div = document.getElementById('red-box')

function translateUp() {
  div.classList.remove('no-translate');
  div.classList.add('translate-up');
}

function noTranslate() {
  div.classList.remove('translate-up');
  div.classList.add('no-translate');
}

//why does this function not show any transition animation?
function both() {
  translateUp();
  noTranslate();
}

https://codepen.io/DMcCreepy/pen/BampPyB

No jQuery please :)

Body:
You are relying on the div getting rerendered and all its properties being recomputed before switching the class again with the second function. I am not sure entirely what order things are done in under the hood, but I am sure you cannot rely on constructions like this working in general. It is true that switching classes is a common way to do animations and maybe it is possible to work out a solution like that, but I have provided a workaround using a CSS animation. You can read more about animations here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations

const div = document.getElementById('red-box')

div.addEventListener('animationend', reset);
function reset() {
  div.classList.remove('dropin');
}
function both() {
  div.classList.add('dropin');
}

button {
  display: block;
}

.box {
  height: 70px;
  width: 80px;
  font-size: 50px;
  background-color: red;
  animation-duration: 1s;
  animation-fill-mode: forwards;
  animation-name: none;
}
.box.dropin {
  animation-name: dropin;
}
@keyframes dropin {
  from {
    transform: translate(0, -40px);
    opacity: 0.1;
  }
  to {
    transform: translate(0, 0);
    opacity: 1;
  }
}

<div id="red-box" class="box">div</div>

<button onclick='both()'>Do Both</button>


问:
Animate Child View in ExpandableList
I only have 1 child view for each group view, which is inflated from a layout .xml file. I wish to animate the child view so that when the child item is displayed, the list item below it slides down. I tries this with a number of animations, but the isse is that the height/ width of the child view is first made visible and then the view animates within that space. However, I want a child view to show between 2 list views by making the following group view slide down to make way for the chile view.

For exanple, I tried the following. The animation does happens, but not as I have described above. I have added the following to the getChildView(), just before I return the child view:

```<code>    Animation anim = AnimationUtils.loadAnimation(MyExpandableList.this,
                                                   R.anim.translate);
    v.setAnimation(anim);
</code>```

Here's is my translate.xml:

```<code>    <?xml version="1.0" encoding="utf-8"?>
       <translate xmlns:android="http://schemas.android.com/apk/res/android"
            android:fromYDelta="-50%p"
    android:toYDelta="0"
    android:duration="500"/>
</code>```

Thanks for your help.

Ani.

答:
You have to animate all child views below the currently added child view also.
Add all the Aniamtions to an AnimationSet and start the set.

Title: Animate Child View in ExpandableList

Body:
I only have 1 child view for each group view, which is inflated from a layout .xml file. I wish to animate the child view so that when the child item is displayed, the list item below it slides down. I tries this with a number of animations, but the isse is that the height/ width of the child view is first made visible and then the view animates within that space. However, I want a child view to show between 2 list views by making the following group view slide down to make way for the chile view.

For exanple, I tried the following. The animation does happens, but not as I have described above. I have added the following to the getChildView(), just before I return the child view:

    Animation anim = AnimationUtils.loadAnimation(MyExpandableList.this,
                                                   R.anim.translate);
    v.setAnimation(anim);

Here's is my translate.xml:

    <?xml version="1.0" encoding="utf-8"?>
       <translate xmlns:android="http://schemas.android.com/apk/res/android"
            android:fromYDelta="-50%p"
    android:toYDelta="0"
    android:duration="500"/>

Thanks for your help.

Ani.


问:
PhpStorm custom time to index files
I have a very, very large project in PhpStorm that is about 10 GB in size.

Unfortunately, every time I open this software, it starts scanning files.

Is it possible to set it to index at any time?
I did not find a section in the settings.

答:
Is it possible to set it to index at any time?

That is not possible.

The indexing is done on a start as the IDE works with your indexed/parsed code in order to offer code completion, find usages, refactoring and other stuff.

The indexing is slow on the first run as the IDE needs to actually scan and parse all the files. Subsequent project openings are much faster: the IDE scans the project files looking for changes and only re-indexes new/modified files.

If you open a project in a new IDE version or after invalidating the caches, the IDE  will re-index the whole thing again.

You can mark certain folders (that do not participate in code completion like logs, DB dumps, product images, user generated content, generated code files etc) as Excluded so they are not getting indexed (they still will be scanned/checked for changes but not parsed/indexed).

https://www.jetbrains.com/help/phpstorm/indexing.html

Title: PhpStorm custom time to index files


问:
How to design repository based on Entity Framework core?
I have created a Repository on top of Entity Framework Core, but have some issues with how it's done.

This is an example:

```<code>    public class StockPricesRepository : IStockPricesRepository
    {

        StockPricesDbContext _stockPricesDbContext;
        ILogger _logger;

        public StockPricesRepository(StockPricesDbContext stockPricesDbContext, ILogger logger)
        {
            _stockPricesDbContext = stockPricesDbContext;
            _logger = logger;
        }

        public void Add(StockPrice stockPrice)
        {
            _stockPricesDbContext.Add(stockPrice);
            _stockPricesDbContext.SaveChanges();
        }

        public void AddOrUpdate(StockPrice stockPrice)
        {
            if (!Exists(stockPrice))
                _stockPricesDbContext.Add(stockPrice);
            else
                _stockPricesDbContext.Update(stockPrice);
            _stockPricesDbContext.SaveChanges();
        }

        private bool Exists(StockPrice stockPrice)
        {
            StockPrice existingStockPrice = Get(stockPrice.Ticker, stockPrice.Exchange, stockPrice.Date, stockPrice.DataProvider);

            return (existingStockPrice != null);
        }

        public StockPrice Get(string ticker, string exchange, DateTime date, string providerName)
        {
            StockPrice stockPrice = null;

            stockPrice =
                (from sp in _stockPricesDbContext.StockPrices
                        where (
                        (sp.Ticker == ticker) &
                        (sp.Exchange == exchange) &
                        (sp.Date == date) &
                        (sp.DataProvider == providerName))
                    select sp).AsNoTracking().FirstOrDefault();

            return stockPrice;
        }

    }
}
</code>```

The StockPricesDbContext is injected into the constructur using dependency injection like this:

```<code>services.AddDbContext<StockPricesDbContext>(options => options.UseSqlServer(connectionString));
</code>```

The problem with the current design is that I get some issues with multiple calls into the repository within the lifetime of the StockPricesDbContext object (even if I have AsNoTracking() on the Get method):

```<code>System.InvalidOperationException: 'The instance of entity type 'StockPrice' cannot be tracked because another instance with the same key value for {'Date', 'Ticker', 'Exchange', 'DataProvider'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
</code>```

To avoid this problem I would maybe prefer to have each of the repository methods embedded in a using block like this:

```<code>using (var db = new StockPricesDbContext())
{
}
</code>```

The problem with this approach is that I don't get the StockPricesDbContext from dependency injection and the connection string from AddDbContext is lost.

One workaround for that might be to get the connection string from the constructor of the repository like this:

```<code>private string _connectionString;

public StockPricesRepository(StockPricesDbContext stockPricesDbContext, ILogger logger)
{
    _stockPricesDbContext = stockPricesDbContext;
    _connectionString = stockPricesDbContext.Database.GetDbConnection().ConnectionString;
    _logger = logger;
}
</code>```

I would also need to add this constructor in StockPricesDbContext:

```<code>public StockPricesDbContext(string connectionString)
{
    _connectionString = connectionString;
}
</code>```

and this would be the OnConfiguring method:

```<code>protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        if (_connectionString != null)
            optionsBuilder.UseSqlServer(_connectionString);
    }
}
</code>```

Then I could use it in the methods like this:

```<code>using (var db = new StockPricesDbContext(_connectionString))
{
}
</code>```

It kind of works, but seems a bit "unclean".

Has anyone else come across a good pattern for repositories built on top of Entity Framework Core?

答:
The common mistake that causes this error is having several async queries that have not been committed.

There is no problem saving multiple records in EF though.

There are multiple approaches to avoid your issue.

Using AddRange(),UpdateRange(),DeleteRange()

AddRange() can add list of objects to your db and you don't need to call .Add() more than once. Similarly you can update or delete a list of objects

EFCore.BulkExtensions

Bulk Extensions in EFCore

Both are extending DbContext with Bulk operations and have the same syntax call:

```<code>context.BulkInsert(stockPriceList);
context.BulkUpdate(stockPriceList);
context.BulkDelete(stockPriceList);
context.BulkInsertOrUpdate(stockPriceList);
</code>```

Body:
I have created a Repository on top of Entity Framework Core, but have some issues with how it's done.

This is an example:

    public class StockPricesRepository : IStockPricesRepository
    {

        StockPricesDbContext _stockPricesDbContext;
        ILogger _logger;

        public StockPricesRepository(StockPricesDbContext stockPricesDbContext, ILogger logger)
        {
            _stockPricesDbContext = stockPricesDbContext;
            _logger = logger;
        }

        public void Add(StockPrice stockPrice)
        {
            _stockPricesDbContext.Add(stockPrice);
            _stockPricesDbContext.SaveChanges();
        }

        public void AddOrUpdate(StockPrice stockPrice)
        {
            if (!Exists(stockPrice))
                _stockPricesDbContext.Add(stockPrice);
            else
                _stockPricesDbContext.Update(stockPrice);
            _stockPricesDbContext.SaveChanges();
        }

        private bool Exists(StockPrice stockPrice)
        {
            StockPrice existingStockPrice = Get(stockPrice.Ticker, stockPrice.Exchange, stockPrice.Date, stockPrice.DataProvider);

            return (existingStockPrice != null);
        }

        public StockPrice Get(string ticker, string exchange, DateTime date, string providerName)
        {
            StockPrice stockPrice = null;

            stockPrice =
                (from sp in _stockPricesDbContext.StockPrices
                        where (
                        (sp.Ticker == ticker) &
                        (sp.Exchange == exchange) &
                        (sp.Date == date) &
                        (sp.DataProvider == providerName))
                    select sp).AsNoTracking().FirstOrDefault();

            return stockPrice;
        }

    }
}

The StockPricesDbContext is injected into the constructur using dependency injection like this:

services.AddDbContext<StockPricesDbContext>(options => options.UseSqlServer(connectionString));

The problem with the current design is that I get some issues with multiple calls into the repository within the lifetime of the StockPricesDbContext object (even if I have AsNoTracking() on the Get method):

System.InvalidOperationException: 'The instance of entity type 'StockPrice' cannot be tracked because another instance with the same key value for {'Date', 'Ticker', 'Exchange', 'DataProvider'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'

To avoid this problem I would maybe prefer to have each of the repository methods embedded in a using block like this:

using (var db = new StockPricesDbContext())
{
}

The problem with this approach is that I don't get the StockPricesDbContext from dependency injection and the connection string from AddDbContext is lost.

One workaround for that might be to get the connection string from the constructor of the repository like this:

private string _connectionString;

public StockPricesRepository(StockPricesDbContext stockPricesDbContext, ILogger logger)
{
    _stockPricesDbContext = stockPricesDbContext;
    _connectionString = stockPricesDbContext.Database.GetDbConnection().ConnectionString;
    _logger = logger;
}

I would also need to add this constructor in StockPricesDbContext:

public StockPricesDbContext(string connectionString)
{
    _connectionString = connectionString;
}

and this would be the OnConfiguring method:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        if (_connectionString != null)
            optionsBuilder.UseSqlServer(_connectionString);
    }
}

Then I could use it in the methods like this:

using (var db = new StockPricesDbContext(_connectionString))
{
}

It kind of works, but seems a bit "unclean".

Has anyone else come across a good pattern for repositories built on top of Entity Framework Core?

Body:
The common mistake that causes this error is having several async queries that have not been committed.

There is no problem saving multiple records in EF though.

There are multiple approaches to avoid your issue.

Using AddRange(),UpdateRange(),DeleteRange()

AddRange() can add list of objects to your db and you don't need to call .Add() more than once. Similarly you can update or delete a list of objects

EFCore.BulkExtensions

Bulk Extensions in EFCore

Both are extending DbContext with Bulk operations and have the same syntax call:

context.BulkInsert(stockPriceList);
context.BulkUpdate(stockPriceList);
context.BulkDelete(stockPriceList);
context.BulkInsertOrUpdate(stockPriceList);


问:
A way to get chart context from subscribeVisibleTimeRangeChange
I got a groups of charts on my page and when the callback for chart.timeScale().subscribeVisibleTimeRangeChange goes off, I need to know what chart exactly fired the event.

The callback's params got only raw time range bounds without any info about the event's origin. Is there anything I'm missing? Or this is just impossible to achieve? Thaanks!

答:
The library doesn't provide this information in the callback, but you can handle it from your side easily by binding a chart to the callback, for example:

chart.timeScale().subscribeVisibleTimeRangeChange(callback.bind(null, chart));
```
<p>Alternatively you could wrap a callback function with another function and pass an argument to it:</p>
<pre class="lang-js prettyprint-override"><code>chart.timeScale().subscribeVisibleTimeRangeChange((...args) => callback(chart, ...args);
</code>```

Body:
The library doesn't provide this information in the callback, but you can handle it from your side easily by binding a chart to the callback, for example:

chart.timeScale().subscribeVisibleTimeRangeChange(callback.bind(null, chart));

Alternatively you could wrap a callback function with another function and pass an argument to it:

chart.timeScale().subscribeVisibleTimeRangeChange((...args) => callback(chart, ...args);


问:
Why does emacs intermittantly not use the alternate screen?
I use emacs with the -nw flag so that it runs in the terminal.  I don't run it inside screen or tmux or anything like that, just a plain terminal.  Often when I exit emacs I return to a view of my terminal that shows the emacs command I typed but no longer shows the file I was editing or the emacs menu bar or anything like that.  From this question I take it that this behavior is because emacs uses a so called "alternate screen" in my terminal.  This is the behavior I want.

Maybe 30% of the time when I exit emacs the file I was editing and the menu bar and such are still on the screen.  Why does this happen and how can I prevent it?

Based on this answer I tried the hacky solution of aliasing emacs to "tput smcup; emacs -nw".  That seemed to reduce the frequency of the problem down to maybe 5 or 10%, but it didn't fix it and I'm sure it's not the "right" thing to do anyway.  Any help would be appreciated.

答: IIUC this has been resolved for Emacs 29.  Refer to the NEWS.</p>


问:
using async/await insted of AJAX
I am going to use async await instead of AJAX in jsp file. How can I use async/await? This is my code:</p>
```<code>function setAcc(){
    var acc_ = getDOM("acc_").value
    AJAX.load({POST: {request: 'set_acc', async: false, acc_: acc_},
        onSuccess: function (result) {
            var objJSON = eval("(function(){return " + result + ";})()");
        go({});
        },
        onError: function (d) {
            alert_g(eval(d));
        }
    });
}
</code>```

答:
Instead of ajax you should use axios library for that and then use async and await accordingly for the Server request's.

Try this link for more understanding

async await using axios

Title: using async/await insted of AJAX

Body:
I am going to use async await instead of AJAX in jsp file. How can I use async/await? This is my code:

function setAcc(){
    var acc_ = getDOM("acc_").value
    AJAX.load({POST: {request: 'set_acc', async: false, acc_: acc_},
        onSuccess: function (result) {
            var objJSON = eval("(function(){return " + result + ";})()");
        go({});
        },
        onError: function (d) {
            alert_g(eval(d));
        }
    });
}


问:
AWS Quicksight: How to Get the latest Data from S3
My Quicksight currently takes everything in the S3 bucket

(S3 sample) https://i.stack.imgur.com/cO8kL.png

But S3 keep changing folder base on the date so 01/,02/,03/ and so on Is there a way to only take the latest data not all of it?

[this my current manifest:]

```<code>{
"fileLocations": [
    {
        "URIPrefixes": [
            "https://sample-S3bucket.amazonaws.com/"
        ]}
],
"globalUploadSettings": {
    "format": "JSON"
}
</code>```

}

There might be a simple solution that I might not know about.

答:
You could set Quicksight to read from another bucket and set a lambda that is triggered when a a new file is uploaded into your existing bucket. This lambda would:

Remove any files from the bucket which QuickSight is reading from

Copy over the latest file into the bucket

Creates a QuickSight SPICE ingestion via api.

Body:
My Quicksight currently takes everything in the S3 bucket

(S3 sample) https://i.stack.imgur.com/cO8kL.png

But S3 keep changing folder base on the date so 01/,02/,03/ and so on Is there a way to only take the latest data not all of it?

[this my current manifest:]

{
"fileLocations": [
    {
        "URIPrefixes": [
            "https://sample-S3bucket.amazonaws.com/"
        ]}
],
"globalUploadSettings": {
    "format": "JSON"
}

}

There might be a simple solution that I might not know about.


问:
SpawnObject for ak(Clone) (UnityEngine.GameObject), NetworkServer is not active. Cannot spawn objects without an active server
helloI'm making an object in Unity that gives players random weapons when they hover over it, but it always gives me this warning and doesn't create it.</p>
```<code>[ClientRpc]
public void spawnTime()
{
    StartCoroutine(spawn());
}
public IEnumerator spawn()
{
    Debug.Log("oldu");
    yield return new WaitForSeconds(1);
    int a = Random.Range(0, guns.Length);
    GameObject gun =Instantiate(guns[a], spawnPoint.position,Quaternion.identity);
    gun.transform.SetParent(transform);
    NetworkServer.Spawn(gun);
}
</code>```

答:
This is because of you are calling the spawn function from client. You should call it in server.

```<code>[Server]
public void spawnTime()
{
    StartCoroutine(spawn());
}

[Server]
public IEnumerator spawn()
{
    Debug.Log("oldu");
    yield return new WaitForSeconds(1);
    int a = Random.Range(0, guns.Length);
    GameObject gun =Instantiate(guns[a],
    spawnPoint.position,Quaternion.identity);
    gun.transform.SetParent(transform);
    NetworkServer.Spawn(gun);

    uint gunNetId = gun.GetComponent<NetworkIdentity>().netId;
    uint parentNetId = transform.root.GetComponent<NetworkIdentity>().netId;
    RpcSetParent(parentNetId, gunNetId);
}

[ClientRpc]
void RpcSetParent(uint parentNetId, uint childNetId)
{
    Transform child = NetworkClient.spawned[childNetId].transform;
    Transform parent = NetworkClient.spawned[parentNetId].transform;

    child.SetParent(parent);
}
</code>```

Be sure that you are calling the spawnTime() function from something running in server and networked object. You can filter it something like:

```<code>Start(){
    NetworkIdentity nid = transform.root.GetComponent<NetworkIdentity>();

    if(nid.isServer)
    {
        spawnTime();
    }
}
</code>```

Body:
helloI'm making an object in Unity that gives players random weapons when they hover over it, but it always gives me this warning and doesn't create it.

[ClientRpc]
public void spawnTime()
{
    StartCoroutine(spawn());
}
public IEnumerator spawn()
{
    Debug.Log("oldu");
    yield return new WaitForSeconds(1);
    int a = Random.Range(0, guns.Length);
    GameObject gun =Instantiate(guns[a], spawnPoint.position,Quaternion.identity);
    gun.transform.SetParent(transform);
    NetworkServer.Spawn(gun);
}

Body:
This is because of you are calling the spawn function from client. You should call it in server.

[Server]
public void spawnTime()
{
    StartCoroutine(spawn());
}

[Server]
public IEnumerator spawn()
{
    Debug.Log("oldu");
    yield return new WaitForSeconds(1);
    int a = Random.Range(0, guns.Length);
    GameObject gun =Instantiate(guns[a],
    spawnPoint.position,Quaternion.identity);
    gun.transform.SetParent(transform);
    NetworkServer.Spawn(gun);

    uint gunNetId = gun.GetComponent<NetworkIdentity>().netId;
    uint parentNetId = transform.root.GetComponent<NetworkIdentity>().netId;
    RpcSetParent(parentNetId, gunNetId);
}

[ClientRpc]
void RpcSetParent(uint parentNetId, uint childNetId)
{
    Transform child = NetworkClient.spawned[childNetId].transform;
    Transform parent = NetworkClient.spawned[parentNetId].transform;

    child.SetParent(parent);
}

Be sure that you are calling the spawnTime() function from something running in server and networked object. You can filter it something like:

Start(){
    NetworkIdentity nid = transform.root.GetComponent<NetworkIdentity>();

    if(nid.isServer)
    {
        spawnTime();
    }
}


问:
Open a text file containing a table with no clear separator
I have to open a text file which contain data that I want to open as a tibble or dataframe. The data are stored in a tbale with white space as separator (I suppose). The probleme is that whitespace is also used in the column "PI". I have no idea how to open it without doing any complicated script to scan all of it and parse it with regex.
Do you have any tips ? I think it was designed to have visualy aligned column when we open it as a text file.

here is a sample of the file.

```<code>  DAC                                                                PI    SPROF_DATE_UPDATE DATA_MODE      WMO CYCLE         PROFILE_DATE      LON     LAT        MPD_RAW      MPD_ADJ        Z_RAW       Z_ADJ
 aoml  STEPHEN RISER , KENNETH JOHNSON                                   2021-05-12 18:52:52         R  5903612   038  2012-07-04 01:15:50    8.651 -41.466     -89.313473          NaN     5.439052         NaN
 aoml  STEPHEN RISER , KENNETH JOHNSON                                   2020-12-03 02:03:33         R  5903717   138  2014-02-03 18:07:45 -164.533 -69.958     134.866767          NaN     7.884637         NaN
 aoml  STEPHEN RISER , KENNETH JOHNSON                                   2021-05-12 22:44:39         R  5903717   139  2014-02-10 20:05:49 -164.302 -70.061      99.848464          NaN     5.803396         NaN
 aoml  STEPHEN RISER , KENNETH JOHNSON                                   2021-05-12 22:44:53         R  5903717   140  2014-02-17 22:06:53 -164.146 -70.246     107.535752          NaN     6.260275         NaN
</code>```

答:
Read the file as lines of text

Replace multiple consecutive spaces with a custom and unique delimiter

Paste everything into a character vector

read from that data using the custom delimiter

Additional re-formatting like trimming and type conversion

```<code>library(tidyverse)
read_lines("data.txt") %>%
  map_chr(~ .x %>% str_replace_all("(  )+", ";")) %>%
  paste0(collapse = "\n") %>%
  read_delim(delim = ";", col_types = cols(.default = "character")) %>%
  mutate(across(everything(), str_trim)) %>%
  type_convert()
</code>```

Body:
I have to open a text file which contain data that I want to open as a tibble or dataframe. The data are stored in a tbale with white space as separator (I suppose). The probleme is that whitespace is also used in the column "PI". I have no idea how to open it without doing any complicated script to scan all of it and parse it with regex.
Do you have any tips ? I think it was designed to have visualy aligned column when we open it as a text file.

here is a sample of the file.

  DAC                                                                PI    SPROF_DATE_UPDATE DATA_MODE      WMO CYCLE         PROFILE_DATE      LON     LAT        MPD_RAW      MPD_ADJ        Z_RAW       Z_ADJ
 aoml  STEPHEN RISER , KENNETH JOHNSON                                   2021-05-12 18:52:52         R  5903612   038  2012-07-04 01:15:50    8.651 -41.466     -89.313473          NaN     5.439052         NaN
 aoml  STEPHEN RISER , KENNETH JOHNSON                                   2020-12-03 02:03:33         R  5903717   138  2014-02-03 18:07:45 -164.533 -69.958     134.866767          NaN     7.884637         NaN
 aoml  STEPHEN RISER , KENNETH JOHNSON                                   2021-05-12 22:44:39         R  5903717   139  2014-02-10 20:05:49 -164.302 -70.061      99.848464          NaN     5.803396         NaN
 aoml  STEPHEN RISER , KENNETH JOHNSON                                   2021-05-12 22:44:53         R  5903717   140  2014-02-17 22:06:53 -164.146 -70.246     107.535752          NaN     6.260275         NaN

Body:
Read the file as lines of text

Replace multiple consecutive spaces with a custom and unique delimiter

Paste everything into a character vector

read from that data using the custom delimiter

Additional re-formatting like trimming and type conversion

library(tidyverse)
read_lines("data.txt") %>%
  map_chr(~ .x %>% str_replace_all("(  )+", ";")) %>%
  paste0(collapse = "\n") %>%
  read_delim(delim = ";", col_types = cols(.default = "character")) %>%
  mutate(across(everything(), str_trim)) %>%
  type_convert()


问:
How to connect to cpanel mysql database from localhost
I am trying to connect to the mysql database from my express server in cpanel (the databse and server are both in cpanel) , I already added a user, and I'm trying to connect via localhost but this ain't working
below is the code:

```<code>const db = mysql.createPool({
  host: "localhost",
  user: \\user\\,
  password: \\password\\,
  database: "ts34mpr_SCMP",
  dateStrings: true,
});
</code>```

The request isn't reaching the databse although I added the user with all privileges and the user with password are 100% correct.
Any help please?
Thank you!

答:
Try this:</p>
```<code>const mysql = require('mysql');
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'cpanel'
});
</code>```

Body:
I am trying to connect to the mysql database from my express server in cpanel (the databse and server are both in cpanel) , I already added a user, and I'm trying to connect via localhost but this ain't working
below is the code:

const db = mysql.createPool({
  host: "localhost",
  user: \\user\\,
  password: \\password\\,
  database: "ts34mpr_SCMP",
  dateStrings: true,
});

The request isn't reaching the databse although I added the user with all privileges and the user with password are 100% correct.
Any help please?
Thank you!

Body:
Try this:

const mysql = require('mysql');
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'cpanel'
});


问:
Displaying website visitors on a map in real-time
I want to develop a webpage (in ASP.NET, C#) with a world map which can display pop-up bubbles whenever someone visits and logs in to our company's website. The bubbles should appear in real-time, and it should display the user's name and location.
Whenever the user logs in to our website, we have name and other personal information available in our database for that user.

Please suggest ways to implement this.

Thanks!

Updated:

By real-time update I mean a page with the map which gets refreshed as soon as any general public visits the home page, or one of our clients logs in to our website. These clients have login IDs provided by us to login to our website and they can be anywhere in the world.

Is there any way I can get to know when someone logs in to our website, and display the user's location on the map? Is it possible to do this without entering the login information in the database?

答: I did tried with Gmaps on this, though not exactly as you want. But all i could do was getting static images from Gmaps v2 APIs since i was using WinForms. But V3 APIs shall provide javascript stuffs which are interactive. Dont know about bing APIs. </p>


问:
How do I define schema directory in JAXB2 maven plugin version 2.4?
I am trying to define the directory for my schema in my pom.xml. I keep getting an error saying "Element schemaDirectory is not allowed here". I am guessing this element is not supported in this version. So how do define my schema directory in this version?

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <id>xjc</id>
            <goals>
                <goal>xjc</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <schemaDirectory>${project.basedir}src/main/resources</schemaDirectory>
        <outputDirectory>${project.basedir}src/main/java</outputDirectory>
    </configuration>
</plugin>
</code>```

Thanks in advance!

答:
For version 2.5.0

```<code>            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxb2-maven-plugin</artifactId>
            <version>2.5.0</version>
            <executions>
                <execution>
                    <id>xjc</id>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <sources>
                    <source>${project.basedir}/src/main/resources/${specify.xsd}</source>
                </sources>
                <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
                <clearOutputDir>false</clearOutputDir>
            </configuration>
        </plugin>
</code>```

Then run mvn compile

Body:
I am trying to define the directory for my schema in my pom.xml. I keep getting an error saying "Element schemaDirectory is not allowed here". I am guessing this element is not supported in this version. So how do define my schema directory in this version?

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <id>xjc</id>
            <goals>
                <goal>xjc</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <schemaDirectory>${project.basedir}src/main/resources</schemaDirectory>
        <outputDirectory>${project.basedir}src/main/java</outputDirectory>
    </configuration>
</plugin>

Thanks in advance!

Body:
For version 2.5.0

            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxb2-maven-plugin</artifactId>
            <version>2.5.0</version>
            <executions>
                <execution>
                    <id>xjc</id>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <sources>
                    <source>${project.basedir}/src/main/resources/${specify.xsd}</source>
                </sources>
                <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
                <clearOutputDir>false</clearOutputDir>
            </configuration>
        </plugin>

Then run mvn compile


问:
Make div bigger then its parent
is there any way how can I make div bigger then its parent? I know its bad practice.
Basically I have div that is small and I need to create div inside which will be through entire window. But cant find way how to do it.
Thanks for any help.</p>

答:
You need to "pop" that element from normal flow with position rule with specified dimensions. E.g. position: fixed;

.outer {
  width: 10vw;
  height: 10vh;
  position: relative;
  background: rgba(130, 130, 255, .3);
  border: 1px solid red;
}

.inner {
  width: 90vw;
  height: 90vh;
  position: absolute;
  left: 5px;
  top: 5px;
  background: rgba(130, 255, 130, .3);
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div class="inner"></div>
</div></code>```

Alternative

Have overflow: visible with specified dimensions

.outer {
  width: 10vw;
  height: 10vh;
  position: relative;
  background: rgba(130, 130, 255, .3);
  border: 1px solid red;
  overflow: visible;
  display: inline-block;
  vertical-align: top;
}

.inner {
  width: 90vw;
  height: 90vh;
  margin: 5px;
  margin: 5px;
  background: rgba(130, 255, 130, .3);
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div class="inner"></div>
</div></code>```

Title: Make div bigger then its parent

Body:
You need to "pop" that element from normal flow with position rule with specified dimensions. E.g. position: fixed;

.outer {
  width: 10vw;
  height: 10vh;
  position: relative;
  background: rgba(130, 130, 255, .3);
  border: 1px solid red;
}

.inner {
  width: 90vw;
  height: 90vh;
  position: absolute;
  left: 5px;
  top: 5px;
  background: rgba(130, 255, 130, .3);
  border: 1px solid green;
}

<div class="outer">
  <div class="inner"></div>
</div>

Alternative

Have overflow: visible with specified dimensions

.outer {
  width: 10vw;
  height: 10vh;
  position: relative;
  background: rgba(130, 130, 255, .3);
  border: 1px solid red;
  overflow: visible;
  display: inline-block;
  vertical-align: top;
}

.inner {
  width: 90vw;
  height: 90vh;
  margin: 5px;
  margin: 5px;
  background: rgba(130, 255, 130, .3);
  border: 1px solid green;
}

<div class="outer">
  <div class="inner"></div>
</div>


问:
KeyError Received unregistered task of type '' on celery while task is registered
I'm a bit new in celery configs.

I have a task named myapp.tasks.my_task for example.

I can see myapp.tasks.my_task in registered tasks of celery when I use celery inspect registered. doesn't it mean that the task is successfully registered? why it raises the following error for it:

```<code>KeyError celery.worker.consumer.consumer in on_task_received

Received unregistered task of type 'my_app.tasks.my_task'.
The message has been ignored and discarded.

Did you remember to import the module containing this task?
Or maybe you're using relative imports?

Please see
http://docs.celeryq.org/en/latest/internals/protocol.html
for more information.

The full contents of the message body was:
'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b)

</code>```

there are also other tasks in my_app.tasks and they work correctly but only this task does not work and gets KeyError:

```<code>@shared_task(queue='celery')
def other_task():
   """ WORKS """
   ...

@shared_task(queue='celery')
def my_task():
   """ DOES NOT WORK """
   ...

</code>```

答:
Another solution can be adding a name param in the shared_task decorator, i.e.,

@shared_task(queue='celery', name='other_task')
def other_task():
   """ WORKS """
   ...

@shared_task(queue='celery', name='my_task')
def my_task():
   """ DOES NOT WORK """
   ...
```

I see this in a full demo project https://github.com/melikesofta/django-dynamic-periodic-tasks, and the related code can be find here.

Body:
I'm a bit new in celery configs.

I have a task named myapp.tasks.my_task for example.

I can see myapp.tasks.my_task in registered tasks of celery when I use celery inspect registered. doesn't it mean that the task is successfully registered? why it raises the following error for it:

KeyError celery.worker.consumer.consumer in on_task_received

Received unregistered task of type 'my_app.tasks.my_task'.
The message has been ignored and discarded.

Did you remember to import the module containing this task?
Or maybe you're using relative imports?

Please see
http://docs.celeryq.org/en/latest/internals/protocol.html
for more information.

The full contents of the message body was:
'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b)

there are also other tasks in my_app.tasks and they work correctly but only this task does not work and gets KeyError:

@shared_task(queue='celery')
def other_task():
   """ WORKS """
   ...

@shared_task(queue='celery')
def my_task():
   """ DOES NOT WORK """
   ...

Body:
Another solution can be adding a name param in the shared_task decorator, i.e.,

@shared_task(queue='celery', name='other_task')
def other_task():
   """ WORKS """
   ...

@shared_task(queue='celery', name='my_task')
def my_task():
   """ DOES NOT WORK """
   ...

I see this in a full demo project https://github.com/melikesofta/django-dynamic-periodic-tasks, and the related code can be find here.


问:
How to compare if second object has some value in first object then return true?
I want to compare two objects as below:

First object:

```<code>const permissions = {
  "statistics":{"list":"1"},"audit":{"list":"1"}}
}
</code>```

Second object:

```<code>const userPermission =
{
  "audit":{"list":"1"}
}
</code>```

So, if the second object has some value the same as the first object then return true.
In this sample I want it return true.  Becuase, audit has same properties.

答:
```<code>var obj1 = {
name:'hello',
age:12,
fav: 'fav',
foo: 'foo'
}

var obj2 = {
name: 'hey',
say: 'say',
prop: 'prop',
top: 'top'
}

var common = Object.keys(obj1).filter(obj1item =>  Object.keys(obj2).indexOf(obj1item) !== -1 );

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

You can look into this > Is there a way to check and see if two objects have properties in common?

Body:
I want to compare two objects as below:

First object:

const permissions = {
  "statistics":{"list":"1"},"audit":{"list":"1"}}
}

Second object:

const userPermission =
{
  "audit":{"list":"1"}
}

So, if the second object has some value the same as the first object then return true.
In this sample I want it return true.  Becuase, audit has same properties.

Body:
var obj1 = {
name:'hello',
age:12,
fav: 'fav',
foo: 'foo'
}

var obj2 = {
name: 'hey',
say: 'say',
prop: 'prop',
top: 'top'
}

var common = Object.keys(obj1).filter(obj1item =>  Object.keys(obj2).indexOf(obj1item) !== -1 );

console.log(common);

You can look into this > Is there a way to check and see if two objects have properties in common?


问:
Gets icon prop and passing it into styled() function
I am getting icon prop and passing it to styled function to create a stylized icon based on it

```<code>const IconComponent = ({ isActive, icon }) => {
   const StyledIcons = styled(icon)`
      fill: #1f6ed4;
      & path {
         fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
      }
   `
   return <StyledIcons isActive={isActive} />
}
</code>```

it works, but I am getting warnings like below:

Is there any other way to create my StyledIcons component
and at the same time receive the icon prop ?

答:
You must move your StyledIcons outside the IconComponent component and use the as prop to pass your icon component:

```<code>const StyledIcons = styled.svg`
  fill: #1f6ed4;
  & path {
    fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
  }
`

const IconComponent = ({ isActive, icon }) => {

  return <StyledIcons as={icon} isActive={isActive} />
};
</code>```

Working example

And if you don't have control over the icon prop and want to avoid the second warning

Warning: React does not recognize the isActive prop on a DOM element...

you can prefix the isActive prop with a dollar sign ($), turning it into a transient prop:

```<code>const StyledIcons = styled.svg`
  fill: #1f6ed4;
  & path {
    fill: ${(props) => (props.$isActive ? "#1F6ED4" : "#232323")};
  }
`;

const IconComponent = ({ isActive, icon }) => {
  return <StyledIcons as={icon} $isActive={isActive} />;
};
</code>```

Body:
I am getting icon prop and passing it to styled function to create a stylized icon based on it

const IconComponent = ({ isActive, icon }) => {
   const StyledIcons = styled(icon)`
      fill: #1f6ed4;
      & path {
         fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
      }
   `
   return

Body:
You must move your StyledIcons outside the IconComponent component and use the as prop to pass your icon component:

const StyledIcons = styled.svg`
  fill: #1f6ed4;
  & path {
    fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
  }
`

const IconComponent = ({ isActive, icon }) => {

  return <StyledIcons as={icon} isActive={isActive} />
};

Working example

And if you don't have control over the icon prop and want to avoid the second warning

Warning: React does not recognize the isActive prop on a DOM element...

you can prefix the isActive prop with a dollar sign ($), turning it into a transient prop:

const StyledIcons = styled.svg`
  fill: #1f6ed4;
  & path {
    fill: ${(props) => (props.$isActive ? "#1F6ED4" : "#232323")};
  }
`;

const IconComponent = ({ isActive, icon }) => {
  return <StyledIcons as={icon} $isActive={isActive} />;
};


问:
React Native application doesn't show up on settings in iOS
My config:

```<code>react-native: 0.66.3
xcode: 13.2.1
</code>```

When deploying an application to the simulator, or to real device, I cannot access the settings page of the app in iOS.

I have a button that asks for user location, and I should at least see it on the settings page.

I tried to deploy the application on release variant, but same thing.
I checked some solution on the web, and I found a solution with many upvote but it still did not do the trick.

Maybe there is a way to generate a Settings.bundle with cocoa based to the permission that we have ?

答:
In my case, I came across this and I followed these instructions :

Adding the Settings Bundle Open your workspace inner ios folder with
xcode To add a Settings bundle to your Xcode project: Choose File >
New > New File. Under iOS, choose Resource, and then select the
Settings Bundle template. Name the file Settings.bundle.

My application was available on the Settings application on iOS, and I just updated the file with my permissions.

From now, the purpose of this file is to manually add some permission, or information (like the version code).

But the automatic permissions like geolocation will be added automatically.

Body:
My config:

react-native: 0.66.3
xcode: 13.2.1

When deploying an application to the simulator, or to real device, I cannot access the settings page of the app in iOS.

I have a button that asks for user location, and I should at least see it on the settings page.

I tried to deploy the application on release variant, but same thing.
I checked some solution on the web, and I found a solution with many upvote but it still did not do the trick.

Maybe there is a way to generate a Settings.bundle with cocoa based to the permission that we have ?


答:
Give a certain height & width to your parent.

Use % for the your .child element.

.parent {
  height: 40px;
  width: 40px;
  background: gray;
}

.child {
  height: 125%;
  width: 125%;
  background: transparent;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child"></div>
</div></code>```

Title: Make div bigger then its parent

Body:
is there any way how can I make div bigger then its parent? I know its bad practice.
Basically I have div that is small and I need to create div inside which will be through entire window. But cant find way how to do it.
Thanks for any help.

Body:
Give a certain height & width to your parent.

Use % for the your .child element.

.parent {
  height: 40px;
  width: 40px;
  background: gray;
}

.child {
  height: 125%;
  width: 125%;
  background: transparent;
  border: 1px solid green;
}

<div class="parent">
  <div class="child"></div>
</div>


问:
SQL replace a string enum in a column of a result set with another string
I apologize if the question is duplicated, but in my preliminary search I haven't found anything!

In my query extraction with SQL, I need to replace the result of a column with other string values.

In particular, I have an enum:

```<code>A1 -> started
A2 -> running
</code>```

In my database, I only save:

```<code>A1
B2
</code>```

So, my query returns the column including strings such as:

```<code>A1
B2
</code>```

I'd like obtaining:

```<code>started
running
</code>```

Is it possible with a query?

Thank you so much!

答:
You can do it with the CASE expression:

```<code>SELECT ...
,      CASE Column
         WHEN 'A1' THEN 'started'
         WHEN 'B2' THEN 'running'
         ... END AS Status
FROM Table
</code>```

Read https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-ver15

Body:
I apologize if the question is duplicated, but in my preliminary search I haven't found anything!

In my query extraction with SQL, I need to replace the result of a column with other string values.

In particular, I have an enum:

A1 -> started
A2 -> running

In my database, I only save:

A1
B2

So, my query returns the column including strings such as:

A1
B2

I'd like obtaining:

started
running

Is it possible with a query?

Thank you so much!

Body:
You can do it with the CASE expression:

SELECT ...
,      CASE Column
         WHEN 'A1' THEN 'started'
         WHEN 'B2' THEN 'running'
         ... END AS Status
FROM Table

Read https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-ver15


问:
Google OAuth - Is it possible to create an IP whitelist?
I'm using a Google Login component in my website that calls Google OAuth API. Is it possible to somehow define an IP whitelist together with the domains whitelist?

The expected result is that even if someone successfully identifies with a whitelisted-domain google account, it will still be rejected if their IP isn't whitelisted

答:
When a domain is used on the consent screen or in an OAuth client’s configuration, it must be pre-registered. If your app needs to go through verification, up need to the Google Search Console to check if your domains are authorized.

Domains used for a redirect uri when the app is set to production must also be verified domains.

You cant set a domain as an ip address and you wont be able to set your redirect uri as an ip address either.


问:
Replacing words inside the string with that of dictionary without using any kind of replace function

expected output = "Hello. My name is $xyz$. I am from $abc$.

# code
string = 'Hi. My name is #something1#. I am from #something2#. My company is #something3#.'
toReplace = {'something1':'xyz', 'something2': 'abc', 'something3': 'ttl'}
modified = list(string)
arr=[]
for i in range(len(string)):
    if string[i]=='#':
        arr.append(i)
#print(arr)

indices = []
for i in range(len(arr)):
    if i%2 != 0:
        continue
    else:
        indices.append(arr[i]+1)
#print(indices)

sources = []
l = 0
while l<len(arr):
    sources.append(string[arr[l]+1:arr[l+1]])
    #print(l, sources)
    l+=2
#print(sources)

targets = toReplace.values()
#print(targets)

for index, source, target in zip(indices, sources, targets):
    #print(index, source, target)
    if not string[index:].startswith(source):
        continue
    else:
        modified[index] = target
        #print(modified)
        for i in range(index+1,len(source)+index):
            modified[i] = ''

print("".join(modified))```

should get this without using replace() or re.replace() functions. it should not remove placeholders. only word inside dictionary to be replace but to be done without replace functions. Any ideas??

答:
Good day to you! I'm glad if the following code will help you in anyway. I have used regular expression to get the required output. Here you go,

```<code>import re
string = "Hello. My name is $something1$. I am from $something2$."
    dict = {'something1':'xyz', 'something2':'abc'}
    for k,v in zip(dict.keys(),dict.values()):
        string=re.sub(k,v,string)
    print(string)
</code>```

And Output is :

```<code>Hello. My name is $xyz$. I am from $abc$.
</code>```

I'm really glad for this opportunity to help you! Thank you!

Body:
expected output = "Hello. My name is $xyz$. I am from $abc$.

# code
string = 'Hi. My name is #something1#. I am from #something2#. My company is #something3#.'
toReplace = {'something1':'xyz', 'something2': 'abc', 'something3': 'ttl'}
modified = list(string)
arr=[]
for i in range(len(string)):
    if string[i]=='#':
        arr.append(i)
#print(arr)

indices = []
for i in range(len(arr)):
    if i%2 != 0:
        continue
    else:
        indices.append(arr[i]+1)
#print(indices)

sources = []
l = 0
while l<len(arr):
    sources.append(string[arr[l]+1:arr[l+1]])
    #print(l, sources)
    l+=2
#print(sources)

targets = toReplace.values()
#print(targets)

for index, source, target in zip(indices, sources, targets):
    #print(index, source, target)
    if not string[index:].startswith(source):
        continue
    else:
        modified[index] = target
        #print(modified)
        for i in range(index+1,len(source)+index):
            modified[i] = ''

print("".join(modified))

should get this without using replace() or re.replace() functions. it should not remove placeholders. only word inside dictionary to be replace but to be done without replace functions. Any ideas??

Body:
Good day to you! I'm glad if the following code will help you in anyway. I have used regular expression to get the required output. Here you go,

import re
string = "Hello. My name is $something1$. I am from $something2$."
    dict = {'something1':'xyz', 'something2':'abc'}
    for k,v in zip(dict.keys(),dict.values()):
        string=re.sub(k,v,string)
    print(string)

And Output is :

Hello. My name is $xyz$. I am from $abc$.

I'm really glad for this opportunity to help you! Thank you!