问:
NodeJS packing and unpacking as buffer slower than JSON
I wrote this simple test to compare the speeds of serializing an array of objects as binary and JSON.

```<code>const { performance } = require('perf_hooks');

let units = [];
let id = 0;
let CHUNK_SIZE = 23;

for (let i = 0; i < 50000; i++) {

  let r = Math.random();

  let u = {};
  u.id = id;
  u.rotation = Math.PI * 2 * Math.random();
  u.type = 0;
  u.x = i;
  u.y = i;
  u.size = r * 20 + 12;
  u.health = 1;
  u.int = 1;

  units.push(u);
}

[
  [
    "JSON",
    (units) => JSON.stringify(units.map(unit => [
      unit.id,
      unit.type,
      unit.x.toFixed(0),
      unit.y.toFixed(0),
      unit.rotation.toFixed(4),
      unit.health.toFixed(2),
      unit.size.toFixed(0),
      parseInt(unit.int)
    ])),
    (units) => JSON.parse(units)
  ],
  [
    "Binary",
    (units) => {
      return Buffer.concat(units.map(unit => {
        let buf = new Buffer(CHUNK_SIZE);

        buf.writeUInt32BE(unit.id);
        buf.writeUInt8(unit.type, 4);
        buf.writeInt32BE(unit.x, 5);
        buf.writeInt32BE(unit.y, 9);
        buf.writeFloatBE(unit.rotation, 13);
        buf.writeFloatBE(unit.health, 17);
        buf.writeUInt8(unit.size, 21);
        buf.writeUInt8(unit.attacking ? 1 : 0, 22);

        return buf;
      }));
    },
    (units) => {
      let u = units.buffer;
      let result = [];

      for (let offset = 0; offset < u.byteLength; offset += CHUNK_SIZE) {
        let view = new DataView(u, offset, CHUNK_SIZE);

        result.push([
          view.getUint32(0),
          view.getUint8(4),
          view.getInt32(5),
          view.getInt32(9),
          view.getFloat32(13),
          view.getFloat32(17),
          view.getUint8(21),
          view.getUint8(22)
        ]);
      }

      return result;
    }
  ]
].forEach(([name, compress, decompress]) => {
  console.log("Test: " + name);

  let t0 = performance.now();

  let compressed = compress(units);

  let t1 = performance.now();

  let decompressed = decompress(compressed);

  let t2 = performance.now();

  console.log(`Result: ${decompressed.length}`);
  console.log(`Compression took: ${t1 - t0}ms`);
  console.log(`Compressed length: ${compressed.byteLength || compressed.length}`);
  console.log(`Decompression took: ${t2 - t1}ms`);
  console.log(`Total time: ${t2 - t0}ms`);
  console.log("");
})
</code>```

Drop that into NodeJS and look at the results, here are mine

```<code>Test: JSON
Result: 50000
Compression took: 411.7958119995892ms
Compressed length: 2227781
Decompression took: 134.79507100209594ms
Total time: 546.5908830016851ms

Test: Binary
Result: 50000
Compression took: 612.1825229972601ms
Compressed length: 1150000
Decompression took: 191.14320900291204ms
Total time: 803.3257320001721ms
</code>```

I'm quite surprised to find that JSON is faster since it is doing considerably more work than the binary counterpart.

Why is that and how can it be improved?

答:
Hope I don't look like a weirdo answering, like a third consecutive, question I asked myself, but hopefully I'm providing content that could be useful for someone.

It appears as if I have been taking way too much advantage of convenience functions. Combine that with not knowing exactly what is happening "under the hood" and you get the results from the question.

Constructing a new buffer for each entry and then concatenating them seems like a costly thing to do. Instead create a single buffer and add to that:

```<code>(units) => {
  let buf = new Buffer(units.length * CHUNK_SIZE);

  units.forEach((unit, i) => {
    let offset = i * CHUNK_SIZE;

    buf.writeUInt32BE(unit.id, offset);
    buf.writeUInt8(unit.type, offset + 4);
    buf.writeInt32BE(unit.x, offset + 5);
    buf.writeInt32BE(unit.y, offset + 9);
    buf.writeFloatBE(unit.rotation, offset + 13);
    buf.writeFloatBE(unit.health, offset + 17);
    buf.writeUInt8(unit.size, offset + 21);
    buf.writeUInt8(unit.attacking ? 1 : 0, offset + 22);
  });

  return buf;
},
</code>```

Same goes on the unserializing part, instead of constructing a new DataView, which can mislead you to believe it would be more effective as it's constructor takes an offset and length, construct one and read off of it:

```<code>(units) => {
  let u = units.buffer;
  let result = [];
  let view = new DataView(u);

  for (let offset = 0; offset < u.byteLength; offset += CHUNK_SIZE) {

    result.push([
      view.getUint32(offset + 0),
      view.getUint8(offset + 4),
      view.getInt32(offset + 5),
      view.getInt32(offset + 9),
      view.getFloat32(offset + 13),
      view.getFloat32(offset + 17),
      view.getUint8(offset + 21),
      view.getUint8(offset + 22)
    ]);
  }

  return result;
}
</code>```

And now we've got more acceptable results:

```<code>Test: JSON
Result: 50000
Compression took: 284.3018040023744ms
Compressed length: 2934399
Decompression took: 197.91818399727345ms
Total time: 522.21998799964786ms

Test: Binary
Result: 50000
Compression took: 175.56888100132346ms
Compressed length: 1150000
Decompression took: 79.27483800053596ms
Total time: 254.84371900185943ms
</code>```

JSON length has increased because I removed the .toFixed calls from the compress function.

I'm interested if there are further improvements that can be done, as I'm sure there are plenty of people who are more competent than me out there.

Body:
I wrote this simple test to compare the speeds of serializing an array of objects as binary and JSON.

const { performance } = require('perf_hooks');

let units = [];
let id = 0;
let CHUNK_SIZE = 23;

for (let i = 0; i < 50000; i++) {

  let r = Math.random();

  let u = {};
  u.id = id;
  u.rotation = Math.PI * 2 * Math.random();
  u.type = 0;
  u.x = i;
  u.y = i;
  u.size = r * 20 + 12;
  u.health = 1;
  u.int = 1;

  units.push(u);
}

[
  [
    "JSON",
    (units) => JSON.stringify(units.map(unit => [
      unit.id,
      unit.type,
      unit.x.toFixed(0),
      unit.y.toFixed(0),
      unit.rotation.toFixed(4),
      unit.health.toFixed(2),
      unit.size.toFixed(0),
      parseInt(unit.int)
    ])),
    (units) => JSON.parse(units)
  ],
  [
    "Binary",
    (units) => {
      return Buffer.concat(units.map(unit => {
        let buf = new Buffer(CHUNK_SIZE);

        buf.writeUInt32BE(unit.id);
        buf.writeUInt8(unit.type, 4);
        buf.writeInt32BE(unit.x, 5);
        buf.writeInt32BE(unit.y, 9);
        buf.writeFloatBE(unit.rotation, 13);
        buf.writeFloatBE(unit.health, 17);
        buf.writeUInt8(unit.size, 21);
        buf.writeUInt8(unit.attacking ? 1 : 0, 22);

        return buf;
      }));
    },
    (units) => {
      let u = units.buffer;
      let result = [];

      for (let offset = 0; offset  {
  console.log("Test: " + name);

  let t0 = performance.now();

  let compressed = compress(units);

  let t1 = performance.now();

  let decompressed = decompress(compressed);

  let t2 = performance.now();

  console.log(`Result: ${decompressed.length}`);
  console.log(`Compression took: ${t1 - t0}ms`);
  console.log(`Compressed length: ${compressed.byteLength || compressed.length}`);
  console.log(`Decompression took: ${t2 - t1}ms`);
  console.log(`Total time: ${t2 - t0}ms`);
  console.log("");
})

Drop that into NodeJS and look at the results, here are mine

Test: JSON
Result: 50000
Compression took: 411.7958119995892ms
Compressed length: 2227781
Decompression took: 134.79507100209594ms
Total time: 546.5908830016851ms

Test: Binary
Result: 50000
Compression took: 612.1825229972601ms
Compressed length: 1150000
Decompression took: 191.14320900291204ms
Total time: 803.3257320001721ms

I'm quite surprised to find that JSON is faster since it is doing considerably more work than the binary counterpart.

Why is that and how can it be improved?

Body:
Hope I don't look like a weirdo answering, like a third consecutive, question I asked myself, but hopefully I'm providing content that could be useful for someone.

It appears as if I have been taking way too much advantage of convenience functions. Combine that with not knowing exactly what is happening "under the hood" and you get the results from the question.

Constructing a new buffer for each entry and then concatenating them seems like a costly thing to do. Instead create a single buffer and add to that:

(units) => {
  let buf = new Buffer(units.length * CHUNK_SIZE);

  units.forEach((unit, i) => {
    let offset = i * CHUNK_SIZE;

    buf.writeUInt32BE(unit.id, offset);
    buf.writeUInt8(unit.type, offset + 4);
    buf.writeInt32BE(unit.x, offset + 5);
    buf.writeInt32BE(unit.y, offset + 9);
    buf.writeFloatBE(unit.rotation, offset + 13);
    buf.writeFloatBE(unit.health, offset + 17);
    buf.writeUInt8(unit.size, offset + 21);
    buf.writeUInt8(unit.attacking ? 1 : 0, offset + 22);
  });

  return buf;
},

Same goes on the unserializing part, instead of constructing a new DataView, which can mislead you to believe it would be more effective as it's constructor takes an offset and length, construct one and read off of it:

(units) => {
  let u = units.buffer;
  let result = [];
  let view = new DataView(u);

  for (let offset = 0; offset < u.byteLength; offset += CHUNK_SIZE) {

    result.push([
      view.getUint32(offset + 0),
      view.getUint8(offset + 4),
      view.getInt32(offset + 5),
      view.getInt32(offset + 9),
      view.getFloat32(offset + 13),
      view.getFloat32(offset + 17),
      view.getUint8(offset + 21),
      view.getUint8(offset + 22)
    ]);
  }

  return result;
}

And now we've got more acceptable results:

Test: JSON
Result: 50000
Compression took: 284.3018040023744ms
Compressed length: 2934399
Decompression took: 197.91818399727345ms
Total time: 522.21998799964786ms

Test: Binary
Result: 50000
Compression took: 175.56888100132346ms
Compressed length: 1150000
Decompression took: 79.27483800053596ms
Total time: 254.84371900185943ms

JSON length has increased because I removed the .toFixed calls from the compress function.

I'm interested if there are further improvements that can be done, as I'm sure there are plenty of people who are more competent than me out there.


来源: stackexchange

问:
Android 9.+ API 29: /storage/emulated/0/Pictures/myPic.png open failed: EACCES (Permission Denied)
I am trying the source code of a very basic camera app on Android Studio 3.4.1 with Android Virtual Device (AVD) Nexus 7 (2012) API 29. I took a picture with the camera in the emulator and tried to save it as /storage/emulated/0/Pictures/myPic.png, but got an exception of /storage/emulated/0/Pictures/myPic.png open failed: EACCES (Permission Denied). I have tried all advice available online, for instance:

In AndroidManifest.xml, I have added:

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

</code>```

In MainActivity.java, I have added the following run-time permission check and request code:

```<code>public class MainActivity extends Activity {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public static void verifyStoragePermissions(Activity activity) {
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        boolean checkPermission = (permission == PackageManager.PERMISSION_GRANTED);

        Toast toastPermission = Toast.makeText(activity,
                "Is permission granted? " + checkPermission,
                Toast.LENGTH_SHORT);
        LinearLayout toastLayoutPermission = (LinearLayout) toastPermission.getView();
        TextView toastTVPermission = (TextView) toastLayoutPermission.getChildAt(0);
        toastTVPermission.setTextSize(30);
        toastPermission.show();

        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

</code>```

I then check and request permission in both onCreate and just before I wanted to save the picture as follows:

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        verifyStoragePermissions(this);

......

private void saveImageToFile(File file)
    {
        if (mCameraBitmap != null)
        {
            FileOutputStream outStream = null;

            verifyStoragePermissions(this);

            try
            {
                outStream = new FileOutputStream(file);

                ...

            }
            catch (Exception e)
            {
                Toast toastException = Toast.makeText(MainActivity.this,
                        "Exception: " + e.getMessage(),
                        Toast.LENGTH_SHORT);
                LinearLayout toastLayoutException = (LinearLayout) toastException.getView();
                TextView toastTVException = (TextView) toastLayoutException.getChildAt(0);
                toastTVException.setTextSize(30);
                toastException.show();
            }

...

</code>```

I also checked the Storage Permission manually in the emulator to make sure the access to the Storage was allowed.

However, NONE of the advice works!

The code threw an exception of

/storage/emulated/0/Pictures/myPic.png open failed: EACCES (Permission Denied)

when it reached the line of

```<code>outStream = new FileOutputStream(file);

</code>```

Any idea to further solve this? Thanks a lot.

答:
I also tried to use a camera and save the photo to ImageView and had problems with permissions. I changed API from 29 to 28 - didn't help, add

```<code>android:requestLegacyExternalStorage="true"
</code>```

didn't help.
I changed the method which I used to create a file to store the image from:

```<code>File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
</code>```

to:

```<code>File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
</code>```

And the problem gone. BTW I don't know why. Maybe because the first one was deprecated.

ContentLicense: CC BY-SA 4.0

Body:
I am trying the source code of a very basic camera app on Android Studio 3.4.1 with Android Virtual Device (AVD) Nexus 7 (2012) API 29. I took a picture with the camera in the emulator and tried to save it as /storage/emulated/0/Pictures/myPic.png, but got an exception of /storage/emulated/0/Pictures/myPic.png open failed: EACCES (Permission Denied). I have tried all advice available online, for instance:

In AndroidManifest.xml, I have added:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

In MainActivity.java, I have added the following run-time permission check and request code:

public class MainActivity extends Activity {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public static void verifyStoragePermissions(Activity activity) {
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        boolean checkPermission = (permission == PackageManager.PERMISSION_GRANTED);

        Toast toastPermission = Toast.makeText(activity,
                "Is permission granted? " + checkPermission,
                Toast.LENGTH_SHORT);
        LinearLayout toastLayoutPermission = (LinearLayout) toastPermission.getView();
        TextView toastTVPermission = (TextView) toastLayoutPermission.getChildAt(0);
        toastTVPermission.setTextSize(30);
        toastPermission.show();

        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

I then check and request permission in both onCreate and just before I wanted to save the picture as follows:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        verifyStoragePermissions(this);

......

private void saveImageToFile(File file)
    {
        if (mCameraBitmap != null)
        {
            FileOutputStream outStream = null;

            verifyStoragePermissions(this);

            try
            {
                outStream = new FileOutputStream(file);

                ...

            }
            catch (Exception e)
            {
                Toast toastException = Toast.makeText(MainActivity.this,
                        "Exception: " + e.getMessage(),
                        Toast.LENGTH_SHORT);
                LinearLayout toastLayoutException = (LinearLayout) toastException.getView();
                TextView toastTVException = (TextView) toastLayoutException.getChildAt(0);
                toastTVException.setTextSize(30);
                toastException.show();
            }

...

I also checked the Storage Permission manually in the emulator to make sure the access to the Storage was allowed.

However, NONE of the advice works!

The code threw an exception of

/storage/emulated/0/Pictures/myPic.png open failed: EACCES (Permission Denied)

when it reached the line of

outStream = new FileOutputStream(file);

Any idea to further solve this? Thanks a lot.

Body:
I also tried to use a camera and save the photo to ImageView and had problems with permissions. I changed API from 29 to 28 - didn't help, add

android:requestLegacyExternalStorage="true"

didn't help.
I changed the method which I used to create a file to store the image from:

File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

to:

File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

And the problem gone. BTW I don't know why. Maybe because the first one was deprecated.


问:
Boolean - is this bar 10 periods back from latest?
I want to use the last 10 bars in a chart for a counter. The counter uses true/false to start counting. Currently I'm manually inputting the bar's number and number of bars to the last. So if the last bar is number 1017, and I want to display the last 10 bars I'd use:

```<code>start_bar = 1007
no_of_bars = 10
cond = bar_index == start_bar
</code>```

However every time I go on a different chart I need to find the bar number of the latest bar, and manually input start_bar.

How can I do this programmatically? I tried using:

bar_index - 10 or bar_index[10]

barstate.islast ? bar_index - 10 :na

barssince(some boolean)

Then putting the result in a global variable to use in the boolean. No success. Thanks!

答:
If you need to make a calculation requiring only the last 10 bars then your best option is to use a loop.

```<code>for i = 0 to 9
</code>```

The result of interest would be displayed at the last bar. If what you need is just showing the last 10 bars of a series you need to use show_last = 10 in the plot function.

Body:
I want to use the last 10 bars in a chart for a counter. The counter uses true/false to start counting. Currently I'm manually inputting the bar's number and number of bars to the last. So if the last bar is number 1017, and I want to display the last 10 bars I'd use:

start_bar = 1007
no_of_bars = 10
cond = bar_index == start_bar

However every time I go on a different chart I need to find the bar number of the latest bar, and manually input start_bar.

How can I do this programmatically? I tried using:

bar_index - 10 or bar_index[10]

barstate.islast ? bar_index - 10 :na

barssince(some boolean)

Then putting the result in a global variable to use in the boolean. No success. Thanks!

Body:
If you need to make a calculation requiring only the last 10 bars then your best option is to use a loop.

for i = 0 to 9

The result of interest would be displayed at the last bar. If what you need is just showing the last 10 bars of a series you need to use show_last = 10 in the plot function.


问:
making 2 subplots into one figure matplotlib

Does anyone know how I can make a plot like the one shown above? I know how to make the plot after the 2 rows, but I'm not sure how I can add a vertical separator and then another 2 rows above it, as shown above.

By the way, I'm only referring to the STRUCTURE of the plot and not of the content.

Here's the code I can use for the portion after the first 2 rows:

```<code>import matplotlib.pyplot as plt
import numpy as np
f, axarr = plt.subplots(nrows=10, ncols=10,
                                figsize=(4,4),
                                gridspec_kw={'hspace': 0, 'wspace': 0})
for dim in range(10):
    samples = np.random.rand(10, 256, 256, 1)
    for sample_idx in range(10):
        axarr[dim][sample_idx].imshow(samples[sample_idx,:,:,0],
                                             cmap='gray')
        axarr[dim][sample_idx].set_axis_off()
plt.subplots_adjust(wspace=0.1, hspace=0.1, left=0, right=1, bottom=0, top=1)
plt.show()
</code>```

EDIT: I've tried some of the suggested solutions and here is what I got:

```<code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec

plt.subplots_adjust(hspace=0.01)

outer = gridspec.GridSpec(2, 1, height_ratios = [2, 10], hspace=.2)

gs1 = gridspec.GridSpecFromSubplotSpec(2, 10, subplot_spec=outer[0], hspace=0.01)
gs2 = gridspec.GridSpecFromSubplotSpec(10, 10, subplot_spec=outer[1], hspace=0.01)

for i in range(2):
    for j in range(10):
        ax = plt.subplot(gs1[i,j])
        ax.plot()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

for i in range(10):
    for j in range(10):
        ax = plt.subplot(gs2[i,j])
        ax.plot()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
plt.show()
</code>```

Overall, the structure is what I want but how can I get rid of those dark black lines in the 3 rows?

答:
Regarding to the overlapped lines, I tried with hspace=0.001 and it seems they are gone.

gs2 = gridspec.GridSpecFromSubplotSpec(10, 10, subplot_spec=outer[1], hspace=0.001)
```

<p><img src="https://i.stack.imgur.com/pPLZlm.png" alt="enter image description here"></p>

<p>To remove space between columns try with <code>wspace=0</code>.</p>

<pre class="lang-py prettyprint-override"><code>gs1 = gridspec.GridSpecFromSubplotSpec(2, 10, subplot_spec=outer[0], hspace=0.01, wspace=0)
gs2 = gridspec.GridSpecFromSubplotSpec(10, 10, subplot_spec=outer[1], hspace=0.001, wspace=0)
</code>```

Body:
Does anyone know how I can make a plot like the one shown above? I know how to make the plot after the 2 rows, but I'm not sure how I can add a vertical separator and then another 2 rows above it, as shown above.

By the way, I'm only referring to the STRUCTURE of the plot and not of the content.

Here's the code I can use for the portion after the first 2 rows:

import matplotlib.pyplot as plt
import numpy as np
f, axarr = plt.subplots(nrows=10, ncols=10,
                                figsize=(4,4),
                                gridspec_kw={'hspace': 0, 'wspace': 0})
for dim in range(10):
    samples = np.random.rand(10, 256, 256, 1)
    for sample_idx in range(10):
        axarr[dim][sample_idx].imshow(samples[sample_idx,:,:,0],
                                             cmap='gray')
        axarr[dim][sample_idx].set_axis_off()
plt.subplots_adjust(wspace=0.1, hspace=0.1, left=0, right=1, bottom=0, top=1)
plt.show()

EDIT: I've tried some of the suggested solutions and here is what I got:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec

plt.subplots_adjust(hspace=0.01)

outer = gridspec.GridSpec(2, 1, height_ratios = [2, 10], hspace=.2)

gs1 = gridspec.GridSpecFromSubplotSpec(2, 10, subplot_spec=outer[0], hspace=0.01)
gs2 = gridspec.GridSpecFromSubplotSpec(10, 10, subplot_spec=outer[1], hspace=0.01)

for i in range(2):
    for j in range(10):
        ax = plt.subplot(gs1[i,j])
        ax.plot()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

for i in range(10):
    for j in range(10):
        ax = plt.subplot(gs2[i,j])
        ax.plot()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
plt.show()

Overall, the structure is what I want but how can I get rid of those dark black lines in the 3 rows?

Body:
Regarding to the overlapped lines, I tried with hspace=0.001 and it seems they are gone.

gs2 = gridspec.GridSpecFromSubplotSpec(10, 10, subplot_spec=outer[1], hspace=0.001)

To remove space between columns try with wspace=0.

gs1 = gridspec.GridSpecFromSubplotSpec(2, 10, subplot_spec=outer[0], hspace=0.01, wspace=0)
gs2 = gridspec.GridSpecFromSubplotSpec(10, 10, subplot_spec=outer[1], hspace=0.001, wspace=0)


问:
How can I start mysql by command service mysql start
I can start mysql by following command

```<code>/etc/init.d/mysql.server start
</code>```

But I want to start it by command "service mysql start"

Server is debian 10.

Mariadb, which was originally installed, was uninstalled and mysql 5.5 was reinstalled.

答:
The proper way for debian10 is now:</p>

```<code>systemctl start mysql.service
</code>```

Body:
I can start mysql by following command

/etc/init.d/mysql.server start

But I want to start it by command "service mysql start"

Server is debian 10.

Mariadb, which was originally installed, was uninstalled and mysql 5.5 was reinstalled.

Body:
The proper way for debian10 is now:

systemctl start mysql.service


问:
Does pthread_once_t variable need a mutex?
we use One-Time initialization for pthreads like this:

```<code>/* define a statically initialized pthread_once_t variable */
pthread_once_t once_var = PTHREAD_ONCE_INIT;

/* we call pthread_once function in threads */
int pthread_once(pthread_once_t *once_control, void (*init)(void));
</code>```

when more than one thread is going to change the state of pthread_once_t variable, do we need a mutex for protecting it?

答:
No, you don't need a mutex for this. The pthread_once call (link here) is guaranteed to be executed once and once only, even if multiple threads try it at the same time.

It's the once_var that's protecting the call from being executed more than once. It will work as expected, provided that you:

initialise the once_var to PTHREAD_ONCE_INIT; and

ensure that once_var is not of automatic storage duration (eg, on the stack); and

have all threads use the same once_var variable.

ContentLicense: CC BY-SA 3.0

Body:
we use One-Time initialization for pthreads like this:

/* define a statically initialized pthread_once_t variable */
pthread_once_t once_var = PTHREAD_ONCE_INIT;

/* we call pthread_once function in threads */
int pthread_once(pthread_once_t *once_control, void (*init)(void));

when more than one thread is going to change the state of pthread_once_t variable, do we need a mutex for protecting it?


问:
Trying to connect Huawei IAP SDK for Inapp payments - 6003 error
I'm trying to connect Huawei IAP SDK for Inapp payments. After adding an app in developer console and some inapp items, I tried to run Iap.getIapClient(activity).isBillingSupported method, but got com.huawei.hms.support.api.iap.json.IapApiException: 6003 error. Can't get any information about that status code, what does it mean. Does anybody know something about it?

答:
I had the same problem and here is the fix. The error clearly says that 6003 -> StatusCode.CERT_FINGERPRINT_ERROR. It looks like Huawei can't validate the originality of the app, because of the missing certificate.

You either didn't added agconnect to your project or you're running in a different build type (like debug, that was my issue because I added agconnect several days ago).

If you didn't added the agconnect to your project, make sure you add it. There is an official tutorial how to add it, but here is it in a nutshell:

First of all you need to add the agconnect dependency to your project, download the agconnect-services.json file from Huawei's Developer (from your App). You need to obtain a SHA256 fingerprint with keytool and add this long fingerprint to your Huawei's Developer field.
https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/iap-configuring-appGallery-connect#certificate

If you added agconnect (like I did several days ago) and the error persisted, it was because you were running in debug or any other build type which is different than what your official release. If you're running in debug make sure you add the signing certificate to your debug build type.

```<code>signingConfigs {
    release {
        storeFile file('C:\\path-to-your\project\signing-certificate.jks')
        keyAlias 'aliasOfYourCertificate'
        keyPassword 'theKeyPasswordOfCertificate'
        storePassword 'theStorePasswordOfCertificate'
    }
}
buildTypes {
    release {
        signingConfig signingConfigs.release
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
    debug {
        signingConfig signingConfigs.release
    }
}
</code>```

So the key here is adding the signingConfig to your debug build type (if you're running in debug).

Body:
I had the same problem and here is the fix. The error clearly says that 6003 -> StatusCode.CERT_FINGERPRINT_ERROR. It looks like Huawei can't validate the originality of the app, because of the missing certificate.

You either didn't added agconnect to your project or you're running in a different build type (like debug, that was my issue because I added agconnect several days ago).

If you didn't added the agconnect to your project, make sure you add it. There is an official tutorial how to add it, but here is it in a nutshell:

First of all you need to add the agconnect dependency to your project, download the agconnect-services.json file from Huawei's Developer (from your App). You need to obtain a SHA256 fingerprint with keytool and add this long fingerprint to your Huawei's Developer field.
https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/iap-configuring-appGallery-connect#certificate

If you added agconnect (like I did several days ago) and the error persisted, it was because you were running in debug or any other build type which is different than what your official release. If you're running in debug make sure you add the signing certificate to your debug build type.

signingConfigs {
    release {
        storeFile file('C:\\path-to-your\project\signing-certificate.jks')
        keyAlias 'aliasOfYourCertificate'
        keyPassword 'theKeyPasswordOfCertificate'
        storePassword 'theStorePasswordOfCertificate'
    }
}
buildTypes {
    release {
        signingConfig signingConfigs.release
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
    debug {
        signingConfig signingConfigs.release
    }
}

So the key here is adding the signingConfig to your debug build type (if you're running in debug).


问:
Docker Registry 2.0 - how to delete unused images?
We updated our private docker registry to the official Registry 2.0. This version can now delete docker images identified by a hashtag (see https://docs.docker.com/registry/spec/api/#deleting-an-image) but I still don't see a way to cleanup old images.

As our CI server is continously producing new images, I would need a method to delete all images from the private registry which are no longer identified by a named tag.

If there's no built-in way to achieve this, I think a custom script could possibly work, but I don't see a v2 API method either to list all stored hashtags of an image..

How can I keep my private registry clean? Any hints?

答:
For removing unsed images, three steps manually on these sequence:

docker rmi -f **imageid**

rm -Rf /home/**homedirectory**/docker-registry/data/docker/registry/v2/repositories/**yoursystemname**/**yourimagename**/_manifests/tags/**image version**/

docker exec $(docker ps -q) bin/registry garbage-collect /etc/docker/registry/config.yml -m

*Pay attention:

** You must execute those commands (above) in test environment, because if you commit any mistake or didn't understand any step, you don't damage your production environment.

** You can schedule those commands (above) using crontab as root. In the step 3) you must execute removing "-it", as result: docker exec $(docker ps -q) bin/registry garbage-collect /etc/docker/registry/config.yml -m`.

It works for me for more than 6 months.


问:
How does the kernel track which processes receive data from an interrupt?
In a preemptive kernel (say Linux), say process A makes a call to getc on stdin, so it's blocked waiting for a character. I feel like I have a fundamental misunderstanding of how the kernel knows then to wake process A at this point and deliver the data after it's received.

My understanding is then this process can be put into a suspended state while the scheduler schedules other processes/threads to run, or it gets preempted. When the keypress happens, through polling/interrupts depending on the implementation, the OS runs a device driver that decodes the key that was pressed. However it's possible (and likely) that my process A isn't currently running. At this point, I'm confused on how my process that was blocked waiting on I/O is now queued to run again, especially how it knows which process is waiting for what. It seems like the device drivers hold some form of a wait queue.

Similarly, and I'm not sure if this is exactly related to the above, but if my browser window, for example, is in focus, it seems to receive key presses but not other windows. Does every window/process have the ability to "listen" for keyboard events even if they're not in focus, but just don't for user experience sake?

So I'm curious how kernels (or how some) keep track of what processes are waiting on which events, and when those events come in, how it determines which processes to schedule to run?

答:
The events that processes wait on are abstract software events, such as a particular queue is not empty, rather than concrete hardware events, such as a interrupt 4635 occurring.

Some configuration ( perhaps guided by a hardware description like device tree ) identifies interrupt 4635 as being a signal from a given serial device with a given address.  The serial device driver configures itself so it can access the device registers of this serial port, and attaches its interrupt handler to the given interrupt identifier (4635).

Once configured, when an interrupt from the serial device is raised, the lowest level of the kernel invokes this serial device's interrupt handler.  In turn, when the handler sees a new character arriving, it places it in the input queue of that device.   As it enqueues the character, it may notice that some process(es) are waiting for that queue to be non-empty, and cause them to be run.

That approximately describes the situation using condition variables as the signalling mechanism between interrupts and processes, as was established in UNIX-y kernels 44 years ago.  Other approaches involve releasing a semaphore on each character in the queue; or replying with messages for each character.   There are many forms of synchronization that can be used.

Common to all such mechanisms, is that the caller chooses to suspend itself to wait for io to complete; and does so by associating its suspension with the instance of the object which it is expecting input from.

What happens next can vary; typically the waiting process, which is now running, reattempts to remove a character from the input queue.  It is possible some other process got to it first, in which case, it merely goes back to waiting for the queue to become non empty.

So, the OS doesn't explicitly route the character from the device to the application; a series of implicit and indirect steps does.


问:
UseSelector State is Undefined
The page does not render, citing TypeError: state is undefined, tracing back to this line in SelectForm.js: const filter = useSelector(state => state.filter);.

I've spent hours trying to figure out what I'm doing wrong. I've tried createSelector but that didn't work. I've tried dispatching a "Fetch Initial State" action, and that didn't work. The component is wrapped in provider tags. I'm not sure why I don't have access to the state. At this point I'm unable to see any flaws I've been looking at it for so long.

Code Snippets

reducer.js

```<code>let initialState = {
    filter: {
        country: null,
        state: null,
        level: null,
        team: null
    },

    isDBConnecting: false,
    isDBConnected: false,
    isDBError: false
}

const SelectorReducer = (state=initialState, action) => {
    switch (action.type) {
        case 'DB_CONNECT_INIT':
            return {
                ...state,
                isDBConnecting: true,
                isDBConnected: false,
                isDBError: false,
            };
...
...
}

export default SelectorReducer;
</code>```

actions.js

```<code>export const initializeDBConnection = () => {
    return {
        type: 'DB_CONNECT_INIT'
    }
};
</code>```

ParentComponent.js

```<code>import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux'; //import provider to provide component access to the state

//Component imports
import SelectForm from './components/SelectForm'
import SelectorReducer from '.../reducer.js'

const SelectorStore = createStore(SelectorReducer);

const ParentComponent = () => {

    return (
        <div className="page-container">
            <div id="carousel">
                <div id="wrapper">
                    <Provider store={SelectorStore}>
                        <SelectForm />
                    </Provider>
                </div>
            </div>
    </div>
    )
}
</code>```

SelectForm.js (Child Component, wrapped in Provider tags above)

```<code>//IMPORTS
import React from 'react'; //import react
import { useSelector, useDispatch } from 'react-redux';

//COMPONENT IMPORTS
import FormGroup from '../FormGroup';
import { * as actions } from '.../actions.js';

const SelectForm = (props) => {

    //STATEFUL IMPORTS
    //filter
    const filter = useSelector(state => state.filter);
</code>```

答:
Credit to @NicholasTower for the answer in the comments. My reducer did not have a default case in which

```<code>default: return state
</code>```

Putting that in solved the issue.

Title: UseSelector State is Undefined

Body:
The page does not render, citing TypeError: state is undefined, tracing back to this line in SelectForm.js: const filter = useSelector(state => state.filter);.

I've spent hours trying to figure out what I'm doing wrong. I've tried createSelector but that didn't work. I've tried dispatching a "Fetch Initial State" action, and that didn't work. The component is wrapped in provider tags. I'm not sure why I don't have access to the state. At this point I'm unable to see any flaws I've been looking at it for so long.

Code Snippets

reducer.js

let initialState = {
    filter: {
        country: null,
        state: null,
        level: null,
        team: null
    },

    isDBConnecting: false,
    isDBConnected: false,
    isDBError: false
}

const SelectorReducer = (state=initialState, action) => {
    switch (action.type) {
        case 'DB_CONNECT_INIT':
            return {
                ...state,
                isDBConnecting: true,
                isDBConnected: false,
                isDBError: false,
            };
...
...
}

export default SelectorReducer;

actions.js

export const initializeDBConnection = () => {
    return {
        type: 'DB_CONNECT_INIT'
    }
};

ParentComponent.js

import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux'; //import provider to provide component access to the state

//Component imports
import SelectForm from './components/SelectForm'
import SelectorReducer from '.../reducer.js'

const SelectorStore = createStore(SelectorReducer);

const ParentComponent = () => {

    return (

                    <Provider store={SelectorStore}>
                        <SelectForm />
                    </Provider>

    )
}

SelectForm.js (Child Component, wrapped in Provider tags above)

//IMPORTS
import React from 'react'; //import react
import { useSelector, useDispatch } from 'react-redux';

//COMPONENT IMPORTS
import FormGroup from '../FormGroup';
import { * as actions } from '.../actions.js';

const SelectForm = (props) => {

    //STATEFUL IMPORTS
    //filter
    const filter = useSelector(state => state.filter);

Body:
Credit to @NicholasTower for the answer in the comments. My reducer did not have a default case in which

default: return state

Putting that in solved the issue.


问:
How do you print superscript in Python?
I am aware of the \xb function in python, but it does not seem to work for me. I am aware that I may need to download a third party module to accomplish this, if so, which one would be best?

I am currently writing a binomial expansion solver, to try and use skills which I am teaching myself. The problem arises when I attempt to display the user input-ed expansion to the use for confirmation. Currently I am having to print the expression like so:

```<code>var1 = input("Enter a: ")
var2 = input("Enter b: ")
exponent = input("Enter n: ")

a = int(var1)
b = int(var2)
n = int(exponent)

expression = ('(%(1)dx%(2)d)^%(3)d') %\
{'1' : a, '2' : b, '3' : n}

print(expression)

confirmation = input(str("Is this correctt? Y/N "))
</code>```

This prints (2x4)^5, whereas I'd prefer the index to be printed as superscript. How can this be done?

Title: How do you print superscript in Python?

Body:
I am aware of the \xb function in python, but it does not seem to work for me. I am aware that I may need to download a third party module to accomplish this, if so, which one would be best?

I am currently writing a binomial expansion solver, to try and use skills which I am teaching myself. The problem arises when I attempt to display the user input-ed expansion to the use for confirmation. Currently I am having to print the expression like so:

var1 = input("Enter a: ")
var2 = input("Enter b: ")
exponent = input("Enter n: ")

a = int(var1)
b = int(var2)
n = int(exponent)

expression = ('(%(1)dx%(2)d)^%(3)d') %\
{'1' : a, '2' : b, '3' : n}

print(expression)

confirmation = input(str("Is this correctt? Y/N "))

This prints (2x4)^5, whereas I'd prefer the index to be printed as superscript. How can this be done?

Body:
You can use this:

def conv_to_super(n):
    super=list(map(chr,[8304,185,178,179,8308,8309,8310,8311,8312,8313]))
    st=""
    for i in str(n):
        st+=super[int(i)]
    return(st)


问:
Logic app Error FTP server xxx.xxx.xxx is currently unavaible
I am using logic app to upload some files from the blob storage to FTP. Most of the time my logic app fails states that Error FTP server xxx.xxx.xxx  is currently unavailable. Sometimes it went successfull.

```<code>{
  "error": {
    "code": 502,
    "source": "logic-apis-eastus.azure-apim.net",
    "clientRequestId": "xxxxxxxxxxxxxxx",
    "message": "BadGateway",
    "innerError": {
      "status": 502,
      "message": "The FTP server 'xxxxxxxxxxxxxxx' is currently unavailable. Please verify server logs to troubleshoot connection issues.\r\nclientRequestId: xxxxxxxxxxxxxxxxx",
      "error": {
        "message": "The FTP server 'xxxxxxxxxxxxxx' is currently unavailable. Please verify server logs to troubleshoot connection issues."
      },
      "source": "ftp-eus.azconn-eus.p.azurewebsites.net"
    }
  }
}
</code>```

I am not sure why this is happening my number of records 2500 or more than that.

Can anyone advice on that what can be the issue?

答:
502 Bad gateway is due to connectivity or network failures. If the transmission takes more than 110 seconds also we will get this error. Its better to check FTP server logs during that time and perhaps check fiddler traces too.
If nothing worked you can raise a support request to Microsoft. </p>

Body:
I am using logic app to upload some files from the blob storage to FTP. Most of the time my logic app fails states that Error FTP server xxx.xxx.xxx  is currently unavailable. Sometimes it went successfull.

{
  "error": {
    "code": 502,
    "source": "logic-apis-eastus.azure-apim.net",
    "clientRequestId": "xxxxxxxxxxxxxxx",
    "message": "BadGateway",
    "innerError": {
      "status": 502,
      "message": "The FTP server 'xxxxxxxxxxxxxxx' is currently unavailable. Please verify server logs to troubleshoot connection issues.\r\nclientRequestId: xxxxxxxxxxxxxxxxx",
      "error": {
        "message": "The FTP server 'xxxxxxxxxxxxxx' is currently unavailable. Please verify server logs to troubleshoot connection issues."
      },
      "source": "ftp-eus.azconn-eus.p.azurewebsites.net"
    }
  }
}

I am not sure why this is happening my number of records 2500 or more than that.

Can anyone advice on that what can be the issue?


问:
Prevent variable update after page refresh without javascript
A friend of mine is developing a web application that's more of an online learning facility. On each page is a set of questions. He wants that when the use has answered all the questions on a page and submitted (and taken to the next page for the next set of questions), he shouldn't be able to go back to answer and resubmit those questions again. The idea is that "opportunity comes but once".

He doesn't want to use javascript because it can be disabled which leaves him with server-side coding. He uses PHP.

Is there a solution?

答: Unless you want to use some sort of database, the easiest way would be to set cookies for the user with PHP. You'd store which questions have already been answered and check that cookie server-side.</p>


问:
Angular cli for existing github project
I'm new to Angular 2 CLI. As per tutorial, there is command provided called ng create <project_name>. My scenario is creating project in existing directory.

It throws error like below:

Directory 'angular-basic' already exists.

答: If your directory structure is: grandParent/parent/yourProject, go to the parent folder in CLI. and do ng new yourProject. It will create the project in the existing directory without creating additional one. (Tried with CLI Version 6.3 and 9.1)

Title: Angular cli for existing github project


问:
Qnx-neutrino can't format my partitions with fdisc, process freezes
I'm trying to format my HDD 250Gb in QNX-neutrino OS running on Oracle VM in Windows 10. I mounted my HDD and everything looks fine. I run command

```<code>fdisk /dev/hd1
</code>```

And create 4 partitions with next sizes:

```<code>1325, 124684, 17265, 47496 MB
</code>```

After that I run command:

```<code>mount -e /dev/hd1
</code>```

And when I tried to format created partitions with commands:

```<code>mkqnx6fs –q –b4096 /dev/hd1t177

mkqnx6fs –q –b4096 /dev/hd1t178

mkqnx6fs –q –b4096 /dev/hd1t179

mkqnx6fs –q –b4096 /dev/hd1t180
</code>```

the process starts and never end. Terminal is just frezees. What can I do to fix it? Or there is another way to format my partitions in this system?

答: I had the same issue when used VM Oracle after markup my HDD. Then I tried VM Ware and this issue was resolved.</p>

Body:
I'm trying to format my HDD 250Gb in QNX-neutrino OS running on Oracle VM in Windows 10. I mounted my HDD and everything looks fine. I run command

fdisk /dev/hd1

And create 4 partitions with next sizes:

1325, 124684, 17265, 47496 MB

After that I run command:

mount -e /dev/hd1

And when I tried to format created partitions with commands:

mkqnx6fs –q –b4096 /dev/hd1t177

mkqnx6fs –q –b4096 /dev/hd1t178

mkqnx6fs –q –b4096 /dev/hd1t179

mkqnx6fs –q –b4096 /dev/hd1t180

the process starts and never end. Terminal is just frezees. What can I do to fix it? Or there is another way to format my partitions in this system?


问:
GUI is not responding after unittests are started
I have written some unittests that use Selenium and created a Tkinter GUI for it.

script.py is:

```<code>from selenium import webdriver
import unittest

class LaunchChrome(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Chrome(r"C:\Users\USERNAME\PycharmProjects\First\Drivers\chromedriver.exe")
        cls.driver.maximize_window()
        cls.driver.get('https://facebook.com')

if __name__ == '__main__':
    unittest.main()
</code>```

interface.py is:

```<code>from tkinter import Button
from tkinter.ttk import *
import unittest
from ex import LaunchChrome

class HomeApplication:

    def init_page(self):

        self.buStart = Button(self, text="Start", width=60)
        self.buStart.grid(row=4, column=0, columnspan=3)
        self.buStart.config(command=self.start_app)
    def run(self):
        Launch_Chrome = unittest.TestLoader().loadTestsFromTestCase(LaunchChrome)
        test_suite = unittest.TestSuite([Launch_Chrome])
        unittest.TextTestRunner(verbosity=2).run(test_suite)
    def start_app(self):
        print("run")
        self.run()
</code>```

After I open the GUI and click on the "Start" button, unittests work fine but the GUI stops to respond (Not Responding):

How can I use multiprocessing is this code?

答:
The tests are running in the main thread. The Tkinter mainloop waits for the start_app method to return, which does not happen until the tests finish execution.

To solve the problem, you can spawn a separate thread or process specifically for the tests.

For example, replace interface.py with the following:

```<code>import unittest
import tkinter as tk
import tkinter.ttk as ttk
from threading import Thread

from ex import LaunchChrome

class HomeApplication(tk.Tk):
    def __init__(self):
        super().__init__()

        ttk.Button(self, text="Start", width=60, command=self.start_app)\
                     .grid(row=4, column=0, columnspan=3)

    def run_tests(self):
        test_suite = unittest.TestSuite([unittest.TestLoader()\
                                         .loadTestsFromTestCase(LaunchChrome)])
        unittest.TextTestRunner(verbosity=2).run(test_suite)

    def start_app(self):
        Thread(target=self.run_tests, daemon=True).start()

if __name__ == "__main__":
    HomeApplication().mainloop()
</code>```

Body:
I have written some unittests that use Selenium and created a Tkinter GUI for it.

script.py is:

from selenium import webdriver
import unittest

class LaunchChrome(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Chrome(r"C:\Users\USERNAME\PycharmProjects\First\Drivers\chromedriver.exe")
        cls.driver.maximize_window()
        cls.driver.get('https://facebook.com')

if __name__ == '__main__':
    unittest.main()

interface.py is:

from tkinter import Button
from tkinter.ttk import *
import unittest
from ex import LaunchChrome

class HomeApplication:

    def init_page(self):

        self.buStart = Button(self, text="Start", width=60)
        self.buStart.grid(row=4, column=0, columnspan=3)
        self.buStart.config(command=self.start_app)
    def run(self):
        Launch_Chrome = unittest.TestLoader().loadTestsFromTestCase(LaunchChrome)
        test_suite = unittest.TestSuite([Launch_Chrome])
        unittest.TextTestRunner(verbosity=2).run(test_suite)
    def start_app(self):
        print("run")
        self.run()

After I open the GUI and click on the "Start" button, unittests work fine but the GUI stops to respond (Not Responding):

How can I use multiprocessing is this code?

Body:
The tests are running in the main thread. The Tkinter mainloop waits for the start_app method to return, which does not happen until the tests finish execution.

To solve the problem, you can spawn a separate thread or process specifically for the tests.

For example, replace interface.py with the following:

import unittest
import tkinter as tk
import tkinter.ttk as ttk
from threading import Thread

from ex import LaunchChrome

class HomeApplication(tk.Tk):
    def __init__(self):
        super().__init__()

        ttk.Button(self, text="Start", width=60, command=self.start_app)\
                     .grid(row=4, column=0, columnspan=3)

    def run_tests(self):
        test_suite = unittest.TestSuite([unittest.TestLoader()\
                                         .loadTestsFromTestCase(LaunchChrome)])
        unittest.TextTestRunner(verbosity=2).run(test_suite)

    def start_app(self):
        Thread(target=self.run_tests, daemon=True).start()

if __name__ == "__main__":
    HomeApplication().mainloop()


问:
Kubernetes pod definition file issue
I can run the Docker container for wso2 ei with following command.

```<code>docker run -it -p 8280:8280 -p 8243:8243 -p 9443:9443 -v wso2ei:/home/wso2carbon --name integrator wso2/wso2ei-integrator
</code>```

I'm trying to create the pod definition file for the same. I don't know how to do port mapping and volume mapping in pod definition file. The following is the file I have created up to now. How can I complete the rest?

```<code>apiVersion: v1
kind: Pod
metadata:
    name: ei-pod
    labels:
        type: ei
        version: 6.6.0
spec:
    containers:
        - name: integrator
          image: wso2/wso2ei-integrator
</code>```

答:
Here is YAML content which might work:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: ei-pod
  labels:
    type: ei
    version: 6.6.0
spec:
  containers:
  - name: integrator
    image: wso2/wso2ei-integrator
    ports:
    - containerPort: 8280
    volumeMounts:
    - mountPath: /wso2carbon
      name: wso2ei
  volumes:
  - name: wso2ei
    hostPath:
      # directory location on host
      path: /home/wso2carbon
</code>```

While the above YAML content is just a basic example, it's not recommended for production usage because of two reasons:

Use deployment or statefulset or daemonset instead of pods directly.

hostPath volume is not sharable between nodes. So use external volumes such as NFS or Block and mount it into the pod. Also look at dynamic volume provisioning using storage class.

Title: Kubernetes pod definition file issue

Body:
I can run the Docker container for wso2 ei with following command.

docker run -it -p 8280:8280 -p 8243:8243 -p 9443:9443 -v wso2ei:/home/wso2carbon --name integrator wso2/wso2ei-integrator

I'm trying to create the pod definition file for the same. I don't know how to do port mapping and volume mapping in pod definition file. The following is the file I have created up to now. How can I complete the rest?

apiVersion: v1
kind: Pod
metadata:
    name: ei-pod
    labels:
        type: ei
        version: 6.6.0
spec:
    containers:
        - name: integrator
          image: wso2/wso2ei-integrator

Body:
Here is YAML content which might work:

apiVersion: v1
kind: Pod
metadata:
  name: ei-pod
  labels:
    type: ei
    version: 6.6.0
spec:
  containers:
  - name: integrator
    image: wso2/wso2ei-integrator
    ports:
    - containerPort: 8280
    volumeMounts:
    - mountPath: /wso2carbon
      name: wso2ei
  volumes:
  - name: wso2ei
    hostPath:
      # directory location on host
      path: /home/wso2carbon

While the above YAML content is just a basic example, it's not recommended for production usage because of two reasons:

Use deployment or statefulset or daemonset instead of pods directly.

hostPath volume is not sharable between nodes. So use external volumes such as NFS or Block and mount it into the pod. Also look at dynamic volume provisioning using storage class.


问:
Comparator and PriorityQueue
```<code>        int points[][] = { { 0, 1 }, { 1, 0 }, {3,3},{5,-1},{-2,4}}, k = 2;
        Queue<int[]> pq = new PriorityQueue<>((a, b) -> ((b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1])));
        for (int[] e : points) {
            pq.add(e);`
             if (pq.size() > k)
                pq.remove();
        }
</code>```

Can anybody please explain to me the working of this code?
Thanks for your help

答:
I have never had the need to use PriorityQueue so I can't authoritatively comment on the above method of achieving the desired goal.

It seems to me that adding and removing in a loop is not very efficient.  By reversing the Comparator (instead of (a,b)-> use (b,a)->) the same result could have been achieved doing the following.

```<code>int points[][] = { { 0, 1 }, { 1, 0 }, {3,3},{5,-1},{-2,4}}, k = 2;
Queue<int[]> pq = new PriorityQueue<>((b,a) -> ((b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1])));

for (int[] p : points) {
   pq.add(p);
}

while (k-- > 0) {
    System.out.println(Arrays.toString(pq.poll()));
}
</code>```

One observation is that for extremely large arrays of data, the intermittent removal of items would keep the PriorityQueue size to a minimum.

Title: Comparator and PriorityQueue

Body:
        int points[][] = { { 0, 1 }, { 1, 0 }, {3,3},{5,-1},{-2,4}}, k = 2;
        Queue<int[]> pq = new PriorityQueue<>((a, b) -> ((b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1])));
        for (int[] e : points) {
            pq.add(e);`
             if (pq.size() > k)
                pq.remove();
        }

Can anybody please explain to me the working of this code?
Thanks for your help

Body:
I have never had the need to use PriorityQueue so I can't authoritatively comment on the above method of achieving the desired goal.

It seems to me that adding and removing in a loop is not very efficient.  By reversing the Comparator (instead of (a,b)-> use (b,a)->) the same result could have been achieved doing the following.

int points[][] = { { 0, 1 }, { 1, 0 }, {3,3},{5,-1},{-2,4}}, k = 2;
Queue<int[]> pq = new PriorityQueue<>((b,a) -> ((b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1])));

for (int[] p : points) {
   pq.add(p);
}

while (k-- > 0) {
    System.out.println(Arrays.toString(pq.poll()));
}

One observation is that for extremely large arrays of data, the intermittent removal of items would keep the PriorityQueue size to a minimum.


问:
UIBarButtonItem isn't shown in combination with large title inside navigation bar
I want to show an UIBarButtonItem as the rightBarButtonItem in my navigation bar. To achieve this, I'm using the code below. Unfortunately it doesn't work.

```<code>private func configureBarButtons() {
    let upButton = UIBarButtonItem(image: UIImage(systemName: "arrow.up"), style: .plain, target: self, action: #selector(handleUpButtonTapped))
    navigationController!.navigationItem.rightBarButtonItem = upButton
}
</code>```

The method from above is called in viewDidLoad().
Until now I haven't found an existing question which solves my problem here on SA...

Thanks for your help!

As it looks right now:

答:
You should not set navigation item of NavigationController rather you should set the navigation item of your ViewController which has embedded UINavigationController to it.

So in your ViewController's viewDidLoad write

```<code>   override func viewDidLoad() {
        super.viewDidLoad()
        let upButton = UIBarButtonItem(image: UIImage(systemName: "arrow.up"), style: .plain, target: self, action: #selector(handleUpButtonTapped))
        self.navigationItem.rightBarButtonItem = upButton
   }
</code>```

Or in your case, simply write

```<code>private func configureBarButtons() {
    let upButton = UIBarButtonItem(image: UIImage(systemName: "arrow.up"), style: .plain, target: self, action: #selector(handleUpButtonTapped))
    self.navigationItem.rightBarButtonItem = upButton
}
</code>```

Body:
I want to show an UIBarButtonItem as the rightBarButtonItem in my navigation bar. To achieve this, I'm using the code below. Unfortunately it doesn't work.

private func configureBarButtons() {
    let upButton = UIBarButtonItem(image: UIImage(systemName: "arrow.up"), style: .plain, target: self, action: #selector(handleUpButtonTapped))
    navigationController!.navigationItem.rightBarButtonItem = upButton
}

The method from above is called in viewDidLoad().
Until now I haven't found an existing question which solves my problem here on SA...

Thanks for your help!

As it looks right now:

Body:
You should not set navigation item of NavigationController rather you should set the navigation item of your ViewController which has embedded UINavigationController to it.

So in your ViewController's viewDidLoad write

   override func viewDidLoad() {
        super.viewDidLoad()
        let upButton = UIBarButtonItem(image: UIImage(systemName: "arrow.up"), style: .plain, target: self, action: #selector(handleUpButtonTapped))
        self.navigationItem.rightBarButtonItem = upButton
   }

Or in your case, simply write

private func configureBarButtons() {
    let upButton = UIBarButtonItem(image: UIImage(systemName: "arrow.up"), style: .plain, target: self, action: #selector(handleUpButtonTapped))
    self.navigationItem.rightBarButtonItem = upButton
}


问:
React context: how to transfer function?
How can I pass the addToCard function from the ShoppingBasketProvider component via context to run it in another component? And how right is it in the component to keep the functions in the component using the context. Thank you for your help.

I have a component:

```<code>export const ShoppingBasketContext = React.createContext();

export default class ShoppingBasketProvider extends Component {

  addToCard = (event) => {
    console.log(event);
  }

  render() {
    const { shoppingBasketItems } = `this.state`;

    return (
      <ShoppingBasketContext.Provider
        value={{
          shoppingBasketItems,

        }}>
        {this.props.children}
      </ShoppingBasketContext.Provider>
    )
 }
}
</code>```

答:
You can pass on the function as a value to Context provider.

```<code>export const ShoppingBasketContext = React.createContext();

export default class ShoppingBasketProvider extends Component {

  addToCard = (event) => {
    console.log(event);
  }

  render() {
    const { shoppingBasketItems } = `this.state`;

    return (
      <ShoppingBasketContext.Provider
        value={{
          shoppingBasketItems,
          addToCard: this.addToCard
        }}>
        {this.props.children}
      </ShoppingBasketContext.Provider>
    )
 }
}
</code>```

You can keep function in the ContextProvider and allow other component to use the function from context and call it.

Body:
How can I pass the addToCard function from the ShoppingBasketProvider component via context to run it in another component? And how right is it in the component to keep the functions in the component using the context. Thank you for your help.

I have a component:

export const ShoppingBasketContext = React.createContext();

export default class ShoppingBasketProvider extends Component {

  addToCard = (event) => {
    console.log(event);
  }

  render() {
    const { shoppingBasketItems } = `this.state`;

    return (
      <ShoppingBasketContext.Provider
        value={{
          shoppingBasketItems,

        }}>
        {this.props.children}
      </ShoppingBasketContext.Provider>
    )
 }
}

Body:
You can pass on the function as a value to Context provider.

export const ShoppingBasketContext = React.createContext();

export default class ShoppingBasketProvider extends Component {

  addToCard = (event) => {
    console.log(event);
  }

  render() {
    const { shoppingBasketItems } = `this.state`;

    return (
      <ShoppingBasketContext.Provider
        value={{
          shoppingBasketItems,
          addToCard: this.addToCard
        }}>
        {this.props.children}
      </ShoppingBasketContext.Provider>
    )
 }
}

You can keep function in the ContextProvider and allow other component to use the function from context and call it.


问:
How to print runs scored by a batsmen in a scoreboard format webelements through CSS selector using Selenium and Java
I want to just print runs scored by all batsman during the cricket match in selenium using CSS selector. All rows have same classname and the runs are in 3rd row so I used CSS selector to select 3rd row only, but I am not able to print runs. Here is my code:</p>

```<code>package SomeBasicAutomationPractice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class tableGrid_Practice {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "G:\\AutomationPractice\\src\\drivers\\chromedriver.exe");
        WebDriver driver= new ChromeDriver();
        driver.get("http://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017");
        Thread.sleep(5000);
        WebElement table=driver.findElement(By.cssSelector("div[class='cb-col cb-col-100 cb-ltst-wgt-hdr']"));

        int count=table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).size();
        System.out.println(count);
        for(int i=0;i<count;i++)
        {
            //table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).get(i);
            System.out.println(table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).get(i));

        }
    }
}
</code>```

答:
In the above snippet, you are actually printing WebElement. findElements method returns List and get method on this list will return ith  webelement. In order to print runs, you have to use getText() or getAttribute("attribute_name") on webelement, according to HTML structure of the page.
You can modify your code something like this:

```<code>List<WebElement> list=table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)"));
for(int i=0; i<list.size(); i++){
    System.out.println(list.get(i).getText());
}
</code>```

Please modify your script accordingly and you will be able to print the runs.

Thanks!

Body:
I want to just print runs scored by all batsman during the cricket match in selenium using CSS selector. All rows have same classname and the runs are in 3rd row so I used CSS selector to select 3rd row only, but I am not able to print runs. Here is my code:

package SomeBasicAutomationPractice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class tableGrid_Practice {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "G:\\AutomationPractice\\src\\drivers\\chromedriver.exe");
        WebDriver driver= new ChromeDriver();
        driver.get("http://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017");
        Thread.sleep(5000);
        WebElement table=driver.findElement(By.cssSelector("div[class='cb-col cb-col-100 cb-ltst-wgt-hdr']"));

        int count=table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).size();
        System.out.println(count);
        for(int i=0;i<count;i++)
        {
            //table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).get(i);
            System.out.println(table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).get(i));

        }
    }
}

Body:
In the above snippet, you are actually printing WebElement. findElements method returns List and get method on this list will return ith  webelement. In order to print runs, you have to use getText() or getAttribute("attribute_name") on webelement, according to HTML structure of the page.
You can modify your code something like this:

List<WebElement> list=table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)"));
for(int i=0; i<list.size(); i++){
    System.out.println(list.get(i).getText());
}

Please modify your script accordingly and you will be able to print the runs.

Thanks!


问:
How to find in specific date interval
I have problem in Mongodb to find wanted documents and fragment of list field. So I have following document:

```<code>{
  "_id": "5ed38e5d2a6e74567c7a579c",
  "id": "AAA",
  "events": [
{
  "dayTypeId": "5e71e1918ee9a326ebdf1611",
  "startDate": {
    "$date": "2020-06-01T00:00:00.000Z"
  },
  "endDate": {
    "$date": "2020-06-04T00:00:00.000Z"
  },
  "stared": false,
  "userId": "XXX",
  "mixing": "wjk0ra1v7m88p0x5aaxwndkmwmlxx4pn92hzjlgpl34u8ojx855m8e8spp1v7l57omtoc4qxbv0g22nybqubd3hq5skuff8ezbzdum2a92itwco64tbi5y2p5mboznxiuwynv0rb8eqk9d80ib65cve6ab9p1d1divee3wbywc2st1lkjruqvgu42zgx8mjtsnb8gyeqtxycl4ujpllgxpshdu8o97iiw347bjqv4mrv6jgwq4r21zp5rm4dw6a1"
},
{
  "dayTypeId": "5e71e1918ee9a326ebdf1611",
  "startDate": {
    "$date": "2020-06-10T00:00:00.000Z"
  },
  "endDate": {
    "$date": "2020-06-10T00:00:00.000Z"
  },
  "stared": false,
  "userId": "XXX",
  "mixing": "wjk0ra1v7m88p0x5aaxwndkmwmlxx4pn92hzjlgpl34u8ojx855m8e8spp1v7l57omtoc4qxbv0g22nybqubd3hq5skuff8ezbzdum2a92itwco64tbi5y2p5mboznxiuwynv0rb8eqk9d80ib65cve6ab9p1d1divee3wbywc2st1lkjruqvgu42zgx8mjtsnb8gyeqtxycl4ujpllgxpshdu8o97iiw347bjqv4mrv6jgwq4r21zp5rm4dw6a1"
},
{
  "dayTypeId": "5e71d8628ee9a326e7df160d",
  "startDate": {
    "$date": "2020-06-05T00:00:00.000Z"
  },
  "endDate": {
    "$date": "2020-06-09T00:00:00.000Z"
  },
  "stared": false,
  "userId": "XXX",
  "mixing": "wjk0ra1v7m88p0x5aaxwndkmwmlxx4pn92hzjlgpl34u8ojx855m8e8spp1v7l57omtoc4qxbv0g22nybqubd3hq5skuff8ezbzdum2a92itwco64tbi5y2p5mboznxiuwynv0rb8eqk9d80ib65cve6ab9p1d1divee3wbywc2st1lkjruqvgu42zgx8mjtsnb8gyeqtxycl4ujpllgxpshdu8o97iiw347bjqv4mrv6jgwq4r21zp5rm4dw6a1"
    },
{
  "dayTypeId": "5e71d8628ee9a326e7df160d",
  "startDate": {
    "$date": "2020-07-13T00:00:00.000Z"
  },
  "endDate": {
    "$date": "2020-07-21T00:00:00.000Z"
  },
  "stared": false,
  "userId": "XXXX",
  "mixing": "wjk0ra1v7m88p0x5aaxwndkmwmlxx4pn92hzjlgpl34u8ojx855m8e8spp1v7l57omtoc4qxbv0g22nybqubd3hq5skuff8ezbzdum2a92itwco64tbi5y2p5mboznxiuwynv0rb8eqk9d80ib65cve6ab9p1d1divee3wbywc2st1lkjruqvgu42zgx8mjtsnb8gyeqtxycl4ujpllgxpshdu8o97iiw347bjqv4mrv6jgwq4r21zp5rm4dw6a1"
    }
  ]
}
</code>```

I want to get fragment of "events" list where either the startDate or the endDate is in the range of 02.06.2020-11.06.2020.

For example out of my sample data I want all but the last element to be returned.

答:
You can use $filter to filter out any events that do not match your conditions:</p>

```<code>db.collection.aggregate([
    {
        $match: {
            $or: [
                {
                    "events.startDate": {$gte: new Date("2020-06-02"), $lte: new Date("2020-06-11")}
                },
                {
                    "events.endDate": {$gte: new Date("2020-06-02"), $lte: new Date("2020-06-11")}
                }
            ]
        }
    },
    {
        $project: {
           events: {
               $filter: {
                   input: "$events",
                   as: "event",
                   cond: {
                       $or: [
                           {
                               $and: [
                                   {$gte: ["$$event.startDate", new Date("2020-06-02")]},
                                   {$lte: ["$$event.startDate", new Date("2020-06-11")]},
                               ]
                           },
                           {
                               $and: [
                                   {$gte: ["$$event.endDate", new Date("2020-06-02")]},
                                   {$lte: ["$$event.endDate", new Date("2020-06-11")]},
                               ]
                           }
                       ]
                   }
               }
           }
        }
    }
])
</code>```

Title: How to find in specific date interval

Body:
I have problem in Mongodb to find wanted documents and fragment of list field. So I have following document:

{
  "_id": "5ed38e5d2a6e74567c7a579c",
  "id": "AAA",
  "events": [
{
  "dayTypeId": "5e71e1918ee9a326ebdf1611",
  "startDate": {
    "$date": "2020-06-01T00:00:00.000Z"
  },
  "endDate": {
    "$date": "2020-06-04T00:00:00.000Z"
  },
  "stared": false,
  "userId": "XXX",
  "mixing": "wjk0ra1v7m88p0x5aaxwndkmwmlxx4pn92hzjlgpl34u8ojx855m8e8spp1v7l57omtoc4qxbv0g22nybqubd3hq5skuff8ezbzdum2a92itwco64tbi5y2p5mboznxiuwynv0rb8eqk9d80ib65cve6ab9p1d1divee3wbywc2st1lkjruqvgu42zgx8mjtsnb8gyeqtxycl4ujpllgxpshdu8o97iiw347bjqv4mrv6jgwq4r21zp5rm4dw6a1"
},
{
  "dayTypeId": "5e71e1918ee9a326ebdf1611",
  "startDate": {
    "$date": "2020-06-10T00:00:00.000Z"
  },
  "endDate": {
    "$date": "2020-06-10T00:00:00.000Z"
  },
  "stared": false,
  "userId": "XXX",
  "mixing": "wjk0ra1v7m88p0x5aaxwndkmwmlxx4pn92hzjlgpl34u8ojx855m8e8spp1v7l57omtoc4qxbv0g22nybqubd3hq5skuff8ezbzdum2a92itwco64tbi5y2p5mboznxiuwynv0rb8eqk9d80ib65cve6ab9p1d1divee3wbywc2st1lkjruqvgu42zgx8mjtsnb8gyeqtxycl4ujpllgxpshdu8o97iiw347bjqv4mrv6jgwq4r21zp5rm4dw6a1"
},
{
  "dayTypeId": "5e71d8628ee9a326e7df160d",
  "startDate": {
    "$date": "2020-06-05T00:00:00.000Z"
  },
  "endDate": {
    "$date": "2020-06-09T00:00:00.000Z"
  },
  "stared": false,
  "userId": "XXX",
  "mixing": "wjk0ra1v7m88p0x5aaxwndkmwmlxx4pn92hzjlgpl34u8ojx855m8e8spp1v7l57omtoc4qxbv0g22nybqubd3hq5skuff8ezbzdum2a92itwco64tbi5y2p5mboznxiuwynv0rb8eqk9d80ib65cve6ab9p1d1divee3wbywc2st1lkjruqvgu42zgx8mjtsnb8gyeqtxycl4ujpllgxpshdu8o97iiw347bjqv4mrv6jgwq4r21zp5rm4dw6a1"
    },
{
  "dayTypeId": "5e71d8628ee9a326e7df160d",
  "startDate": {
    "$date": "2020-07-13T00:00:00.000Z"
  },
  "endDate": {
    "$date": "2020-07-21T00:00:00.000Z"
  },
  "stared": false,
  "userId": "XXXX",
  "mixing": "wjk0ra1v7m88p0x5aaxwndkmwmlxx4pn92hzjlgpl34u8ojx855m8e8spp1v7l57omtoc4qxbv0g22nybqubd3hq5skuff8ezbzdum2a92itwco64tbi5y2p5mboznxiuwynv0rb8eqk9d80ib65cve6ab9p1d1divee3wbywc2st1lkjruqvgu42zgx8mjtsnb8gyeqtxycl4ujpllgxpshdu8o97iiw347bjqv4mrv6jgwq4r21zp5rm4dw6a1"
    }
  ]
}

I want to get fragment of "events" list where either the startDate or the endDate is in the range of 02.06.2020-11.06.2020.

For example out of my sample data I want all but the last element to be returned.

Body:
You can use $filter to filter out any events that do not match your conditions:

db.collection.aggregate([
    {
        $match: {
            $or: [
                {
                    "events.startDate": {$gte: new Date("2020-06-02"), $lte: new Date("2020-06-11")}
                },
                {
                    "events.endDate": {$gte: new Date("2020-06-02"), $lte: new Date("2020-06-11")}
                }
            ]
        }
    },
    {
        $project: {
           events: {
               $filter: {
                   input: "$events",
                   as: "event",
                   cond: {
                       $or: [
                           {
                               $and: [
                                   {$gte: ["$$event.startDate", new Date("2020-06-02")]},
                                   {$lte: ["$$event.startDate", new Date("2020-06-11")]},
                               ]
                           },
                           {
                               $and: [
                                   {$gte: ["$$event.endDate", new Date("2020-06-02")]},
                                   {$lte: ["$$event.endDate", new Date("2020-06-11")]},
                               ]
                           }
                       ]
                   }
               }
           }
        }
    }
])


问:
No need for the operator () in std::generate?
Why we don't add the operator () in std::generate (myvector.begin(), myvector.end(), RandomNumber)? Being something like this: std::generate (myvector.begin(), myvector.end(), RandomNumber()).

Code taken from cplusplus:

```<code>int RandomNumber () { return (std::rand()%100); }

int main () {
  std::srand ( unsigned ( std::time(0) ) );

  std::vector<int> myvector (8);

  std::generate (myvector.begin(), myvector.end(), RandomNumber);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
</code>```

答:
Function pointers and functors are not the same thing

RandomNumber is the name of a function. It'll decay to a function pointer here. That's one way to pass a callable to algorithms like std::generate.

Another way is to create a type, a class, a functor, which has a call operator (operator()). We can also pass an instance of this type to algorithms like std::generate, and the algorithm will "call the object like a function" instead of using a function pointer.

When we do that, we sometimes instantiate it as a temporary, for brevity. So, for example, this:

```<code>Type obj;
f(obj);
</code>```

is much like this:

```<code>f(Type());
</code>```

(except that would be suspectible to the most vexing parse in this simple example; just ignore that :P)

So, the () you're looking for is a class instantiation, which just isn't relevant when you pass a function pointer instead of a functor.

If you wrote RandomNumber(), you'd simply be calling the function RandomNumber and passing its result to std::generate, which is not what you want.

Body:
Why we don't add the operator () in std::generate (myvector.begin(), myvector.end(), RandomNumber)? Being something like this: std::generate (myvector.begin(), myvector.end(), RandomNumber()).

Code taken from cplusplus:

int RandomNumber () { return (std::rand()%100); }

int main () {
  std::srand ( unsigned ( std::time(0) ) );

  std::vector<int> myvector (8);

  std::generate (myvector.begin(), myvector.end(), RandomNumber);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;

Body:
Function pointers and functors are not the same thing

RandomNumber is the name of a function. It'll decay to a function pointer here. That's one way to pass a callable to algorithms like std::generate.

Another way is to create a type, a class, a functor, which has a call operator (operator()). We can also pass an instance of this type to algorithms like std::generate, and the algorithm will "call the object like a function" instead of using a function pointer.

When we do that, we sometimes instantiate it as a temporary, for brevity. So, for example, this:

Type obj;
f(obj);

is much like this:

f(Type());

(except that would be suspectible to the most vexing parse in this simple example; just ignore that :P)

So, the () you're looking for is a class instantiation, which just isn't relevant when you pass a function pointer instead of a functor.

If you wrote RandomNumber(), you'd simply be calling the function RandomNumber and passing its result to std::generate, which is not what you want.


问:
During a function call how can I use rest parameters in Typescript?
I am working on nestjs and I want to retrieve data from DB on the basis of name property, which I am passing in a method of services code. The issue is when am passing {"name": "item1"} in postman, am getting item1 related data, but when am passing {"name":"item1","name":"item2"} in postman, I am getting data related to item2 only.I want to retrieve data of both item1, item2, and so on. To overcome this issue I thought rest parameters would be a good choice, but I don't know how to pass rest parameters and how to call rest parameters in postman. The main problem is I don't know how to deal with rest parameters in postman and code too.

Here is the code of services:

```<code>async individual(...name:any){
    const ind= await this.usersmodel.find({'name':{$in:name}})
    return ind
}
</code>```

Here is the code of controller:

```<code>@Post('ind')
async ind(@Body('name')name){
    return this.usersService.individual(name)
}
</code>```

screenshot of postman:

screenshot of error am getting by using this method:

答:
Your question isn't well formulated but i will pretend you are trying to find in your schema a number of values that you will provide trought your API.

Thinking that way, you can use a POST to sendo an Array inside your body, like that:

```<code>"name": ["item2", "item3", "item4"]
</code>```

Inside your service file you receive that array and can still use find(), but that way:

```<code>await this.usersmodel.find({
'name': { $in: name }
}
</code>```

Body:
I am working on nestjs and I want to retrieve data from DB on the basis of name property, which I am passing in a method of services code. The issue is when am passing {"name": "item1"} in postman, am getting item1 related data, but when am passing {"name":"item1","name":"item2"} in postman, I am getting data related to item2 only.I want to retrieve data of both item1, item2, and so on. To overcome this issue I thought rest parameters would be a good choice, but I don't know how to pass rest parameters and how to call rest parameters in postman. The main problem is I don't know how to deal with rest parameters in postman and code too.

Here is the code of services:

async individual(...name:any){
    const ind= await this.usersmodel.find({'name':{$in:name}})
    return ind
}

Here is the code of controller:

@Post('ind')
async ind(@Body('name')name){
    return this.usersService.individual(name)
}

screenshot of postman:

screenshot of error am getting by using this method:

Body:
Your question isn't well formulated but i will pretend you are trying to find in your schema a number of values that you will provide trought your API.

Thinking that way, you can use a POST to sendo an Array inside your body, like that:

"name": ["item2", "item3", "item4"]

Inside your service file you receive that array and can still use find(), but that way:

await this.usersmodel.find({
'name': { $in: name }
}


问:
How to get SQL COUNT to include results of zero?
I'm trying to count the number of students in each class. The idea here is that there's different subjects at a school, and I want to view the numbers in each Photography class.

Enrolments is used to enrol a student into a class, so counting the students with a confirmed enrolment in each class returns the number of students in that class.

Classnumber is the unique ID of a class, studentnumber is unique to each student.

However, the count function i'm using doesn't return the classes which have no students. Is there an easy, or better way of achieving this?

Here's what I'm doing:

```<code>SELECT enrolment.classnumber, COUNT(studentnumber) AS "Students" FROM enrolment
JOIN class ON enrolment.classnumber=class.classnumber
WHERE enrolmentstatus='Confirmed'
AND classtype='Photography'
GROUP BY enrolment.classnumber
</code>```

But it only returns the following:

```<code>CLASS NUMBER         Students
------------         --------
6                    5
</code>```

Rather than including the other 3 empty photography classes. Any ideas?

答:
You want a left join:

```<code>SELECT c.classnumber, COUNT(e.studentnumber) AS Students
FROM class c LEFT JOIN
     enrolment e
     ON e.classnumber = c.classnumber AND
        e.enrolmentstatus = 'Confirmed'
WHERE c.classtype = 'Photography'
GROUP BY c.classnumber;
</code>```

The idea is to start with class because that defines all the rows you want in the result set.  Then use LEFT JOIN to bring in matching rows.  Conditions on the second table (such as status) need to be in the ON clause.

Body:
I'm trying to count the number of students in each class. The idea here is that there's different subjects at a school, and I want to view the numbers in each Photography class.

Enrolments is used to enrol a student into a class, so counting the students with a confirmed enrolment in each class returns the number of students in that class.

Classnumber is the unique ID of a class, studentnumber is unique to each student.

However, the count function i'm using doesn't return the classes which have no students. Is there an easy, or better way of achieving this?

Here's what I'm doing:

SELECT enrolment.classnumber, COUNT(studentnumber) AS "Students" FROM enrolment
JOIN class ON enrolment.classnumber=class.classnumber
WHERE enrolmentstatus='Confirmed'
AND classtype='Photography'
GROUP BY enrolment.classnumber

But it only returns the following:

CLASS NUMBER         Students
------------         --------
6                    5

Rather than including the other 3 empty photography classes. Any ideas?

Body:
You want a left join:

SELECT c.classnumber, COUNT(e.studentnumber) AS Students
FROM class c LEFT JOIN
     enrolment e
     ON e.classnumber = c.classnumber AND
        e.enrolmentstatus = 'Confirmed'
WHERE c.classtype = 'Photography'
GROUP BY c.classnumber;

The idea is to start with class because that defines all the rows you want in the result set.  Then use LEFT JOIN to bring in matching rows.  Conditions on the second table (such as status) need to be in the ON clause.


问:
Is there a Transformation engine or library using .NET?
We're looking for a Transformation library or engine which can read any input (EDIfact files, CSV, XML, stuff like that. So files (or webservices results) that contain data which must be transformed to a known business object structure.)  This data should  be transformed this to a existing business object using custom rules. XSLT is both to complex (to learn) and to simple (not enough features)

Can anybody recommend a C# library or engine? I have seen Altova MapForce but would like something I can send out to dozens of people who will build / design their own transformations without having to pay dozens of Altova licenses.

答: Microsoft BizTalk Server does a very good job of this.</p>

OwnerDisplayName: Edoode

LastEditorDisplayName: Edoode

OwnerDisplayName: John Hunter

ContentLicense: CC BY-SA 2.5


问:
Finishing all activities started before the activity
I want to finish all the activities which are running in the application means want to remove all the parent activities from stack.

I want to implement logout functionality locally in my application so what I was thinking, I will finish all the activities started before and will start login activity again..

答:
I should let you know this is not a recommended behavior in android since you should let itself to manage life circles of activities.

However if you really need to do this, you can use FLAG_ACTIVITY_CLEAR_TOP

I give you some sample code here, where MainActivity is the first activity in the application:

```<code>public static void home(Context ctx) {
    if (!(ctx instanceof MainMenuActivity)) {
        Intent intent = new Intent(ctx, MainMenuActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ctx.startActivity(intent);
    }
}
</code>```

If you want to quit whole application, you can use the following code and check in the MainActivity to quit the application completely:

```<code>    public static void clearAndExit(Context ctx) {
    if (!(ctx instanceof MainMenuActivity)) {
        Intent intent = new Intent(ctx, MainMenuActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bundle = new Bundle();
        bundle.putBoolean("exit", true);
        intent.putExtras(bundle);
        ctx.startActivity(intent);
    } else {
        ((Activity) ctx).finish();
    }
}
</code>```

Hope this helps.

Body:
I should let you know this is not a recommended behavior in android since you should let itself to manage life circles of activities.

However if you really need to do this, you can use FLAG_ACTIVITY_CLEAR_TOP

I give you some sample code here, where MainActivity is the first activity in the application:

public static void home(Context ctx) {
    if (!(ctx instanceof MainMenuActivity)) {
        Intent intent = new Intent(ctx, MainMenuActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ctx.startActivity(intent);
    }
}

If you want to quit whole application, you can use the following code and check in the MainActivity to quit the application completely:

    public static void clearAndExit(Context ctx) {
    if (!(ctx instanceof MainMenuActivity)) {
        Intent intent = new Intent(ctx, MainMenuActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bundle = new Bundle();
        bundle.putBoolean("exit", true);
        intent.putExtras(bundle);
        ctx.startActivity(intent);
    } else {
        ((Activity) ctx).finish();
    }
}

Hope this helps.


问:
How to pass lambda function by pointer?
I am a new in c++ maybe I miss something, but actually what I need to do is: I have a class that processing something in other thread, during this processing I need that it invoke a callback for progress.

How I see I can do it, I need to declarate pointer (maybe shared_ptr) for my callback function as a class member, than I have a setter in order to pass pointer to callback and then I can use it. A few issues here are how to pass it correctly? How to invoke pointer on function?

My implementation is:

```<code>class RobocopyCopy
{
    //Public members
public:
    typedef std::function<void(int)> TVoidIntCallback;

    RobocopyCopy * set_monitoring_done_callback(TVoidIntCallback monitoring_done_callback)
    {
       m_pMonitoring_done_callback = &monitoring_done_callback;
       return this;
    }

    //This method executes in background
    void execute()
    {
        ...
        //and here I need to invoke my callback
        (TVoidIntCallback *)m_pMonitoring_done_callback(777); //but this is not correct

private:
    TVoidIntCallback * m_pMonitoring_done_callback;

...
}
</code>```

and final implementation of this should be like this (I think) :

```<code>RobocopyCopy robocopy;
    robocopy.set_monitoring_done_callback([this](int my_progress) {
        printf("Progress is :: %d", my_progress);
    });
</code>```

So, as I mentioned above questions is :

how to pass this function callback as a lambda and save in Robocopy class as a pointer

How to invoke this function correctly, because this (TVoidIntCallback *)m_pMonitoring_done_callback(777); doesn't work.

答:
I am using VC++ I hope this code will be successful for you.</p>

```<code>class RobocopyCopy
{
   typedef std::function<void(int)> TVoidIntCallback;
   TVoidIntCallback evnt;
   public:

   RobocopyCopy* set_monitoring_done_callback(TVoidIntCallback
   monitoring_done_callback)
   {
     //set callBack function from out side.
     evnt = monitoring_done_callback;
     return this;
   }

    void execute() {
       //invoke your callBack
      evnt(1000000);
    }
};

int main()
{
   RobocopyCopy obj;
   obj.set_monitoring_done_callback([](int data) {
    std::cout << data << "\n";
    })->execute();
}
</code>```

Title: How to pass lambda function by pointer?

Body:
I am a new in c++ maybe I miss something, but actually what I need to do is: I have a class that processing something in other thread, during this processing I need that it invoke a callback for progress.

How I see I can do it, I need to declarate pointer (maybe shared_ptr) for my callback function as a class member, than I have a setter in order to pass pointer to callback and then I can use it. A few issues here are how to pass it correctly? How to invoke pointer on function?

My implementation is:

class RobocopyCopy
{
    //Public members
public:
    typedef std::function<void(int)> TVoidIntCallback;

    RobocopyCopy * set_monitoring_done_callback(TVoidIntCallback monitoring_done_callback)
    {
       m_pMonitoring_done_callback = &monitoring_done_callback;
       return this;
    }

    //This method executes in background
    void execute()
    {
        ...
        //and here I need to invoke my callback
        (TVoidIntCallback *)m_pMonitoring_done_callback(777); //but this is not correct

private:
    TVoidIntCallback * m_pMonitoring_done_callback;

...
}

and final implementation of this should be like this (I think) :

RobocopyCopy robocopy;
    robocopy.set_monitoring_done_callback([this](int my_progress) {
        printf("Progress is :: %d", my_progress);
    });

So, as I mentioned above questions is :

how to pass this function callback as a lambda and save in Robocopy class as a pointer

How to invoke this function correctly, because this (TVoidIntCallback *)m_pMonitoring_done_callback(777); doesn't work.

Body:
I am using VC++ I hope this code will be successful for you.

class RobocopyCopy
{
   typedef std::function<void(int)> TVoidIntCallback;
   TVoidIntCallback evnt;
   public:

   RobocopyCopy* set_monitoring_done_callback(TVoidIntCallback
   monitoring_done_callback)
   {
     //set callBack function from out side.
     evnt = monitoring_done_callback;
     return this;
   }

    void execute() {
       //invoke your callBack
      evnt(1000000);
    }
};

int main()
{
   RobocopyCopy obj;
   obj.set_monitoring_done_callback([](int data) {
    std::cout << data << "\n";
    })->execute();
}


问:
My perfectly working Java code throws an exception in IntelliJ IDEA
I've been using eclipse and OnlineGDB for my Java works. I recently started to use IntelliJ IDEA and I'm enjoying this a lot. But i tried to work one of my simple projects in IntelliJ IDEA about file operations. But it gives me an error during running. I'm experiencing no problem in OnlineGDB with the exact same codes.

```<code>import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;

public class Main

{
    static void createFile() throws Exception
    {
        PrintWriter output = new PrintWriter(new File("input.txt"));
        output.print("2.5");
        output.close();
    }

public static void main(String[] args) throws Exception
{
    Scanner input = new Scanner(System.in);
    Circle[] circles = new Circle[3];

    circles[0] = new Circle(1.0);

    System.out.print("Radius of the second circle => ");
    circles[1] = new Circle(input.nextFloat());
    input.close();

    createFile();
    input = new Scanner(new File("input.txt"));
    circles[2] = new Circle(input.nextFloat());
    input.close();

    for (int i = 0; i<=circles.length-1; i++)
    {
        System.out.println( "c(" + i + ") radius = " + circles[i].getRadius()
        + " area = " + circles[i].area() );
    }

    float total = 0;
    for (int i = 0; i<3; i++)
    {
        total +=circles[i].getRadius();
    }
    System.out.println("Total radius of the circles = " + total );

    total = 0;
    for (int i = 0; i<3; i++)
    {
        total+= circles[i].area();
    }
    System.out.println("Total area of the circles = " + total);
}
}
</code>```

```<code>    public class Circle
{
    private double radius;

    public Circle (double radius)
    {
        this.radius = radius;
    }

    public double getRadius()
    {
        return radius;
    }

    public double area()
    {
        return(Math.PI * radius * radius);
    }
}
</code>```

It gives me the "java.util.InputMismatchException" error during these lines:

```<code>System.out.print("Radius of the second circle => ");
        circles[1] = new Circle(input.nextFloat());
        input.close();
</code>```

答:
```<code>System.out.print("Radius of the second circle => ");
circles[1] = new Circle(input.nextFloat());
input.close();
</code>```

I changed  input.nextInt() to input.nextFloat()
Change part of code that expects integer to read float(or double, if you wish). You should be able to enter values like 2.5 and not get any error.

I explained in comment why you get error if you enter 2.5

Sample output:

```<code>Radius of the second circle => 2.5
c(0) radius = 1.0 area = 3.141592653589793
c(1) radius = 2.5 area = 19.634954084936208
c(2) radius = 2.5 area = 19.634954084936208
Total radius of the circles = 6.0
Total area of the circles = 42.4115
</code>```

Body:
I've been using eclipse and OnlineGDB for my Java works. I recently started to use IntelliJ IDEA and I'm enjoying this a lot. But i tried to work one of my simple projects in IntelliJ IDEA about file operations. But it gives me an error during running. I'm experiencing no problem in OnlineGDB with the exact same codes.

import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;

public class Main

{
    static void createFile() throws Exception
    {
        PrintWriter output = new PrintWriter(new File("input.txt"));
        output.print("2.5");
        output.close();
    }

public static void main(String[] args) throws Exception
{
    Scanner input = new Scanner(System.in);
    Circle[] circles = new Circle[3];

    circles[0] = new Circle(1.0);

    System.out.print("Radius of the second circle => ");
    circles[1] = new Circle(input.nextFloat());
    input.close();

    createFile();
    input = new Scanner(new File("input.txt"));
    circles[2] = new Circle(input.nextFloat());
    input.close();

    for (int i = 0; i<=circles.length-1; i++)
    {
        System.out.println( "c(" + i + ") radius = " + circles[i].getRadius()
        + " area = " + circles[i].area() );
    }

    float total = 0;
    for (int i = 0; i<3; i++)
    {
        total +=circles[i].getRadius();
    }
    System.out.println("Total radius of the circles = " + total );

    total = 0;
    for (int i = 0; i<3; i++)
    {
        total+= circles[i].area();
    }
    System.out.println("Total area of the circles = " + total);
}
}

    public class Circle
{
    private double radius;

    public Circle (double radius)
    {
        this.radius = radius;
    }

    public double getRadius()
    {
        return radius;
    }

    public double area()
    {
        return(Math.PI * radius * radius);
    }
}

It gives me the "java.util.InputMismatchException" error during these lines:

System.out.print("Radius of the second circle => ");
        circles[1] = new Circle(input.nextFloat());
        input.close();

Body:
System.out.print("Radius of the second circle => ");
circles[1] = new Circle(input.nextFloat());
input.close();

I changed  input.nextInt() to input.nextFloat()
Change part of code that expects integer to read float(or double, if you wish). You should be able to enter values like 2.5 and not get any error.

I explained in comment why you get error if you enter 2.5

Sample output:

Radius of the second circle => 2.5
c(0) radius = 1.0 area = 3.141592653589793
c(1) radius = 2.5 area = 19.634954084936208
c(2) radius = 2.5 area = 19.634954084936208
Total radius of the circles = 6.0
Total area of the circles = 42.4115