问:
osx - How to get a process id (PID) programmatically?
How can I get a process' ID? I require the ID in order to kill that process. I know the name of the process.

Thanks!

答:
First of all, process name is not uniquely identify the process. There could be many processes with the same name, or processes can even change their name as you see them (i.e. PostgreSQL server is forking and changing argv[0] so you can see who is master, who is working process etc). But anyway, you will need an API to list processes and get their details - procps will do it for you.

UPDATE: Oh, I didn't notice OSX the first time. For OS X, you have to use NetBSD API (don't ask). Please see KVM (Kernel Data Access Library) documentation. The API is different, the idea is still the same.


来源: stackexchange

问:
Create a DB Browser style QHeaderview in PyQt5
I would like to create a QHeaderView in PyQt5 like the one that is used in this project (DB Browser for SQLite). The problem is that I don't know C++ and I don't understand how the classes and widgets are created from the source code that is on GitHub. Does anybody how to emulate this filter header in python?

https://github.com/sqlitebrowser/sqlitebrowser/blob/master/src/FilterTableHeader.h

答:
This is a very basic implementation of that approach.

The concept is to provide a correct sizeHint for the header (the default hint of the header plus the height of the line edit) and use setViewportMargins to ensure that the header has a bottom margin which is used by the text fields.

```<code>class Header(QtWidgets.QHeaderView):
    filterChanged = QtCore.pyqtSignal(int, str)
    fieldsVisible = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields = []
        self.sectionCountChanged.connect(self.generateFields)
        self.sectionResized.connect(self.updateFields)
        self.parent().horizontalScrollBar().valueChanged.connect(self.updateFields)
        self.parent().verticalScrollBar().valueChanged.connect(self.updateFields)

    def setFieldsVisible(self, visible):
        if visible == self.fieldsVisible:
            return
        self.fieldsVisible = visible
        self.generateFields()

    def generateFields(self):
        while self.fields:
            self.fields.pop().deleteLater()
        if self.fieldsVisible:
            for s in range(self.count()):
                edit = QtWidgets.QLineEdit(self)
                edit.show()
                self.fields.append(edit)
                edit.textChanged.connect(lambda text, s=s: self.filterChanged.emit(s, text))
            self.updateFields()
        self.updateGeometries()

    def updateFields(self):
        offset = self.offset()
        y = QtWidgets.QHeaderView.sizeHint(self).height()
        for section, field in enumerate(self.fields):
            field.move(self.sectionPosition(section) - offset, y)
            field.resize(self.sectionSize(section), field.sizeHint().height())

    def updateGeometries(self):
        if self.fields:
            self.setViewportMargins(0, 0, 0, self.fields[0].sizeHint().height())
        else:
            self.setViewportMargins(0, 0, 0, 0)
        super().updateGeometries()
        # ensure that the parent view updates correctly
        self.parent().updateGeometries()
        self.updateFields()

    def sizeHint(self):
        hint = super().sizeHint()
        if self.fields:
            hint.setHeight(hint.height() + self.fields[0].sizeHint().height())
        return hint

class SearchTable(QtWidgets.QTableView):
    def __init__(self):
        super().__init__()
        model = QtGui.QStandardItemModel()
        for row in range(8):
            model.appendRow([QtGui.QStandardItem('Item {} {}'.format(row, i)) for i in range(8)])
        self.setModel(model)
        self.setHorizontalHeader(Header(QtCore.Qt.Horizontal, self))
</code>```

Note that this example does not take into account the possibility of moving sections, and if you want to implement a multi-column filter you'll need a subclass of QSortFilterProxyModel (for example, the one provided here). I provided a basic signal (filterChanged) which will return the section and the text changed.

ContentLicense: CC BY-SA 4.0

Body:
This is a very basic implementation of that approach.

The concept is to provide a correct sizeHint for the header (the default hint of the header plus the height of the line edit) and use setViewportMargins to ensure that the header has a bottom margin which is used by the text fields.

class Header(QtWidgets.QHeaderView):
    filterChanged = QtCore.pyqtSignal(int, str)
    fieldsVisible = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields = []
        self.sectionCountChanged.connect(self.generateFields)
        self.sectionResized.connect(self.updateFields)
        self.parent().horizontalScrollBar().valueChanged.connect(self.updateFields)
        self.parent().verticalScrollBar().valueChanged.connect(self.updateFields)

    def setFieldsVisible(self, visible):
        if visible == self.fieldsVisible:
            return
        self.fieldsVisible = visible
        self.generateFields()

    def generateFields(self):
        while self.fields:
            self.fields.pop().deleteLater()
        if self.fieldsVisible:
            for s in range(self.count()):
                edit = QtWidgets.QLineEdit(self)
                edit.show()
                self.fields.append(edit)
                edit.textChanged.connect(lambda text, s=s: self.filterChanged.emit(s, text))
            self.updateFields()
        self.updateGeometries()

    def updateFields(self):
        offset = self.offset()
        y = QtWidgets.QHeaderView.sizeHint(self).height()
        for section, field in enumerate(self.fields):
            field.move(self.sectionPosition(section) - offset, y)
            field.resize(self.sectionSize(section), field.sizeHint().height())

    def updateGeometries(self):
        if self.fields:
            self.setViewportMargins(0, 0, 0, self.fields[0].sizeHint().height())
        else:
            self.setViewportMargins(0, 0, 0, 0)
        super().updateGeometries()
        # ensure that the parent view updates correctly
        self.parent().updateGeometries()
        self.updateFields()

    def sizeHint(self):
        hint = super().sizeHint()
        if self.fields:
            hint.setHeight(hint.height() + self.fields[0].sizeHint().height())
        return hint

class SearchTable(QtWidgets.QTableView):
    def __init__(self):
        super().__init__()
        model = QtGui.QStandardItemModel()
        for row in range(8):
            model.appendRow([QtGui.QStandardItem('Item {} {}'.format(row, i)) for i in range(8)])
        self.setModel(model)
        self.setHorizontalHeader(Header(QtCore.Qt.Horizontal, self))

Note that this example does not take into account the possibility of moving sections, and if you want to implement a multi-column filter you'll need a subclass of QSortFilterProxyModel (for example, the one provided here). I provided a basic signal (filterChanged) which will return the section and the text changed.


问:
Clickhouse: sum of arrays based on another array
Say you have the following table:

```<code>ID  COUNTRIES                   UNITS
1   ['UK', 'Italy', 'France']   [2000, 1000, 1000]
1   ['France', 'Italy', 'UK']   [3000, 4000, 2000]
1   ['Italy']                   [2000]
</code>```

Is there a way in ClickHouse to add up the RATIOS column for each country in the COUNTRIES column? Something like sum(UNITS) group by COUNTRIES

Expected result:

```<code>ID  COUNTRIES                   TOTAL_UNITS
1   ['UK', 'Italy', 'France']   [4000, 4000, 7000]
</code>```

Reprex code:

```<code>SELECT data.1 ID, data.2 COUNTRIES, data.3 UNITS
FROM (
    SELECT arrayJoin([(1, ['UK', 'Italy', 'France'], [2000, 1000, 1000]),
                    (1, ['France', 'Italy', 'UK'], [3000, 4000, 2000]),
                    (1, ['Italy'], [2000])]) data);
</code>```

答:
```<code>select sumMap(COUNTRIES, UNITS) from (

SELECT data.1 ID, data.2 COUNTRIES, data.3 UNITS
FROM (
    SELECT arrayJoin([(1, ['UK', 'Italy', 'France'], [2000, 1000, 1000]),
                    (1, ['France', 'Italy', 'UK'], [3000, 4000, 2000]),
                    (1, ['Italy'], [2000])]) data)

)

┌─sumMap(COUNTRIES, UNITS)───────────────────┐
│ (['France','Italy','UK'],[4000,7000,4000]) │
└────────────────────────────────────────────┘

select (sumMap(COUNTRIES, UNITS) as x).1 a , x.2  b from (

SELECT data.1 ID, data.2 COUNTRIES, data.3 UNITS
FROM (
    SELECT arrayJoin([(1, ['UK', 'Italy', 'France'], [2000, 1000, 1000]),
                    (1, ['France', 'Italy', 'UK'], [3000, 4000, 2000]),
                    (1, ['Italy'], [2000])]) data)

)
┌─a───────────────────────┬─b────────────────┐
│ ['France','Italy','UK'] │ [4000,7000,4000] │
└─────────────────────────┴──────────────────┘

select groupArray(COUNTRY) COUNTRIES, groupArray(s) UNITS from (
select sum(UNIT) s, COUNTRY from (

SELECT data.1 ID, data.2 COUNTRIES, data.3 UNITS
FROM (
    SELECT arrayJoin([(1, ['UK', 'Italy', 'France'], [2000, 1000, 1000]),
                    (1, ['France', 'Italy', 'UK'], [3000, 4000, 2000]),
                    (1, ['Italy'], [2000])]) data)
) array join UNITS as UNIT, COUNTRIES as COUNTRY
group by COUNTRY)

┌─COUNTRIES───────────────┬─UNITS────────────┐
│ ['France','Italy','UK'] │ [4000,7000,4000] │
└─────────────────────────┴──────────────────┘
</code>```

Body:
Say you have the following table:

ID  COUNTRIES                   UNITS
1   ['UK', 'Italy', 'France']   [2000, 1000, 1000]
1   ['France', 'Italy', 'UK']   [3000, 4000, 2000]
1   ['Italy']                   [2000]

Is there a way in ClickHouse to add up the RATIOS column for each country in the COUNTRIES column? Something like sum(UNITS) group by COUNTRIES

Expected result:

ID  COUNTRIES                   TOTAL_UNITS
1   ['UK', 'Italy', 'France']   [4000, 4000, 7000]

Reprex code:

SELECT data.1 ID, data.2 COUNTRIES, data.3 UNITS
FROM (
    SELECT arrayJoin([(1, ['UK', 'Italy', 'France'], [2000, 1000, 1000]),
                    (1, ['France', 'Italy', 'UK'], [3000, 4000, 2000]),
                    (1, ['Italy'], [2000])]) data);


问:
How do I set a mock date in Jest?
I'm using moment.js to do most of my date logic in a helper file for my React components but I haven't been able to figure out how to mock a date in Jest a la sinon.useFakeTimers().

The Jest docs only speak about timer functions like setTimeout, setInterval etc but don't help with setting a date and then checking that my date functions do what they're meant to do.

Here is some of my JS file:

var moment = require('moment');

var DateHelper = {

  DATE_FORMAT: 'MMMM D',
  API_DATE_FORMAT: 'YYYY-MM-DD',

  formatDate: function(date) {
    return date.format(this.DATE_FORMAT);
  },

  isDateToday: function(date) {
    return this.formatDate(date) === this.formatDate(moment());
  }
};

module.exports = DateHelper;
```
<p>and here is what I've set up using Jest:</p>
<pre class="lang-js prettyprint-override"><code>jest.dontMock('../../../dashboard/calendar/date-helper')
    .dontMock('moment');

describe('DateHelper', function() {
  var DateHelper = require('../../../dashboard/calendar/date-helper'),
      moment = require('moment'),
      DATE_FORMAT = 'MMMM D';

  describe('formatDate', function() {

    it('should return the date formatted as DATE_FORMAT', function() {
      var unformattedDate = moment('2014-05-12T00:00:00.000Z'),
          formattedDate = DateHelper.formatDate(unformattedDate);

      expect(formattedDate).toEqual('May 12');
    });

  });

  describe('isDateToday', function() {

    it('should return true if the passed in date is today', function() {
      var today = moment();

      expect(DateHelper.isDateToday(today)).toEqual(true);
    });

  });

});
</code>```

Now these tests pass because I'm using moment and my functions use moment but it seems a bit unstable and I would like to set the date to a fixed time for the tests.

Any idea on how that could be accomplished?

答:
Here are a few readable ways for different use cases. I prefer using spies over saving references to the original objects, which can be accidentally overwritten in some other code.

One-off mocking

jest
  .spyOn(global.Date, 'now')
  .mockImplementationOnce(() => Date.parse('2020-02-14'));
```
<h2>A few tests</h2>
<pre class="lang-js prettyprint-override"><code>let dateSpy;

beforeAll(() => {
  dateSpy = jest
    .spyOn(global.Date, 'now')
    .mockImplementation(() => Date.parse('2020-02-14'));
});

afterAll(() => {
  dateSpy.mockRestore();
});
</code>```

Title: How do I set a mock date in Jest?

Body:
I'm using moment.js to do most of my date logic in a helper file for my React components but I haven't been able to figure out how to mock a date in Jest a la sinon.useFakeTimers().

The Jest docs only speak about timer functions like setTimeout, setInterval etc but don't help with setting a date and then checking that my date functions do what they're meant to do.

Here is some of my JS file:

var moment = require('moment');

var DateHelper = {

  DATE_FORMAT: 'MMMM D',
  API_DATE_FORMAT: 'YYYY-MM-DD',

  formatDate: function(date) {
    return date.format(this.DATE_FORMAT);
  },

  isDateToday: function(date) {
    return this.formatDate(date) === this.formatDate(moment());
  }
};

module.exports = DateHelper;

and here is what I've set up using Jest:

jest.dontMock('../../../dashboard/calendar/date-helper')
    .dontMock('moment');

describe('DateHelper', function() {
  var DateHelper = require('../../../dashboard/calendar/date-helper'),
      moment = require('moment'),
      DATE_FORMAT = 'MMMM D';

  describe('formatDate', function() {

    it('should return the date formatted as DATE_FORMAT', function() {
      var unformattedDate = moment('2014-05-12T00:00:00.000Z'),
          formattedDate = DateHelper.formatDate(unformattedDate);

      expect(formattedDate).toEqual('May 12');
    });

  });

  describe('isDateToday', function() {

    it('should return true if the passed in date is today', function() {
      var today = moment();

      expect(DateHelper.isDateToday(today)).toEqual(true);
    });

  });

});

Now these tests pass because I'm using moment and my functions use moment but it seems a bit unstable and I would like to set the date to a fixed time for the tests.

Any idea on how that could be accomplished?

Body:
Here are a few readable ways for different use cases. I prefer using spies over saving references to the original objects, which can be accidentally overwritten in some other code.

One-off mocking

jest
  .spyOn(global.Date, 'now')
  .mockImplementationOnce(() => Date.parse('2020-02-14'));

A few tests

let dateSpy;

beforeAll(() => {
  dateSpy = jest
    .spyOn(global.Date, 'now')
    .mockImplementation(() => Date.parse('2020-02-14'));
});

afterAll(() => {
  dateSpy.mockRestore();
});


问:
How can I get DNS records for a domain in python?
How do I get the DNS records for a zone in python?  I'm looking for data similar to the output of dig.

答:
You can use python's socket library to get the DNS records from ip address or domain name

```<code>import socket

# if ip address is available
DNS_record = socket.gethostbyaddr("66.249.65.189")

# if domain name is available
DNS_record = socket.gethostbyname("google.com")
</code>```

For more info:

socket.gethostbyaddr()

socket.gethostbyname()

ContentLicense: CC BY-SA 2.5

Body:
You can use python's socket library to get the DNS records from ip address or domain name

import socket

# if ip address is available
DNS_record = socket.gethostbyaddr("66.249.65.189")

# if domain name is available
DNS_record = socket.gethostbyname("google.com")

For more info:

socket.gethostbyaddr()

socket.gethostbyname()


问:
Using tf.keras.utils.Sequence with model.fit_generator with use_multiprocessing=True generated warning
This is the warning I got:

```<code>WARNING:tensorflow:multiprocessing can interact badly with TensorFlow, causing nondeterministic deadlocks. For high performance data pipelines tf.data is recommended.
</code>```

The Sequence subclass I wrote strictly perform load and read I/O jpg files. I guess as long as no 2 threads do it simultaneously on the same file, things should be ok.

I trained for a few epoch and so far, there's no error. But would like to get feedback if there's something potentially bad that could happen.

答:
Initially in the TensorFlow 2.0 Version, there were issues with the keras.utils.Sequence with multiprocessing=True was causing a hang due to deadlock. Later in Tensorflow 2.1 this Warning was added to address this concern.

```<code># use_multiprocessing=False works.
# use_multiprocessing=True hangs in a deadlock situation.
model.fit_generator(generator, use_multiprocessing=True, workers=2)
</code>```

You can ignore this warning since you are not doing any processing which will create deadlock situation.

Body:
This is the warning I got:

WARNING:tensorflow:multiprocessing can interact badly with TensorFlow, causing nondeterministic deadlocks. For high performance data pipelines tf.data is recommended.

The Sequence subclass I wrote strictly perform load and read I/O jpg files. I guess as long as no 2 threads do it simultaneously on the same file, things should be ok.

I trained for a few epoch and so far, there's no error. But would like to get feedback if there's something potentially bad that could happen.

Body:
Initially in the TensorFlow 2.0 Version, there were issues with the keras.utils.Sequence with multiprocessing=True was causing a hang due to deadlock. Later in Tensorflow 2.1 this Warning was added to address this concern.

# use_multiprocessing=False works.
# use_multiprocessing=True hangs in a deadlock situation.
model.fit_generator(generator, use_multiprocessing=True, workers=2)

You can ignore this warning since you are not doing any processing which will create deadlock situation.


问:
Bug in Numpy ndarray min/max method
I'm assuming I'm doing something wrong here, but I'm working on a project in Pycharm, which notified me when using the ndarray.max() function that initial was undefined (parameter 'initial' unfilled). Looking at the documentation, it does show that there is no default value for initial argument.

When ctrl-clicking the ndarray.max() function in Pycharm, opens the following function:

```<code>    def max(self, axis=None, out=None, keepdims=False, initial, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
    """
    a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)

        Return the maximum along a given axis.

        Refer to `numpy.amax` for full documentation.

        See Also
        --------
        numpy.amax : equivalent function
    """
    pass
</code>```

Which appears to not even do anything. Either way, the code works, only an IDE error is given.

Am I using the wrong function? I know there's amax and max, as well as the package level numpy.max, but the above seems to be unwanted behaviour.

If this is a bug, I wouldn't know how to report it / start an issue or whatever, haha.

答:
it appears empty because it's not implemented in python, probably C/C++, as you can figure out from # real signature unknown; NOTE: unreliably restored from __doc__ - it's just a hint for you what parameter this function has. It's not even valid python ;)

Basing on documentation of amax:

initial scalar, optional

The minimum value of an output element. Must be present to allow computation on empty slice. See reduce for details.

You'd better pass something to initial

Title: Bug in Numpy ndarray min/max method

Body:
I'm assuming I'm doing something wrong here, but I'm working on a project in Pycharm, which notified me when using the ndarray.max() function that initial was undefined (parameter 'initial' unfilled). Looking at the documentation, it does show that there is no default value for initial argument.

When ctrl-clicking the ndarray.max() function in Pycharm, opens the following function:

    def max(self, axis=None, out=None, keepdims=False, initial, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
    """
    a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)

        Return the maximum along a given axis.

        Refer to `numpy.amax` for full documentation.

        See Also
        --------
        numpy.amax : equivalent function
    """
    pass

Which appears to not even do anything. Either way, the code works, only an IDE error is given.

Am I using the wrong function? I know there's amax and max, as well as the package level numpy.max, but the above seems to be unwanted behaviour.

If this is a bug, I wouldn't know how to report it / start an issue or whatever, haha.


问:
Python and performance of list comprehensions
Suppose you have got a list comprehension in python, like

```<code>Values = [ f(x) for x in range( 0, 1000 ) ]
</code>```

with f being just a function without side effects. So all the entries can be computed independently.

Is Python able to increase the performance of this list comprehension compared with the "obvious" implementation; e.g. by shared-memory-parallelization on multicore CPUs?

答:
In Python 3.2 they added concurrent.futures, a nice library for solving problems concurrently. Consider this example:

```<code>import math, time
from concurrent import futures

PRIMES = [112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419, 112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def bench(f):
    start = time.time()
    f()
    elapsed = time.time() - start
    print("Completed in {} seconds".format(elapsed))

def concurrent():
    with futures.ProcessPoolExecutor() as executor:
        values = list(executor.map(is_prime, PRIMES))

def listcomp():
    values = [is_prime(x) for x in PRIMES]
</code>```

Results on my quad core:

```<code>>>> bench(listcomp)
Completed in 14.463825941085815 seconds
>>> bench(concurrent)
Completed in 3.818351984024048 seconds
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose you have got a list comprehension in python, like

Values = [ f(x) for x in range( 0, 1000 ) ]

with f being just a function without side effects. So all the entries can be computed independently.

Is Python able to increase the performance of this list comprehension compared with the "obvious" implementation; e.g. by shared-memory-parallelization on multicore CPUs?

Body:
In Python 3.2 they added concurrent.futures, a nice library for solving problems concurrently. Consider this example:

import math, time
from concurrent import futures

PRIMES = [112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419, 112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def bench(f):
    start = time.time()
    f()
    elapsed = time.time() - start
    print("Completed in {} seconds".format(elapsed))

def concurrent():
    with futures.ProcessPoolExecutor() as executor:
        values = list(executor.map(is_prime, PRIMES))

def listcomp():
    values = [is_prime(x) for x in PRIMES]

Results on my quad core:

>>> bench(listcomp)
Completed in 14.463825941085815 seconds
>>> bench(concurrent)
Completed in 3.818351984024048 seconds


问:
Intercept AWS S3 requests
Hi I am looking to implement a workflow like this

Input-files => S3 (regular/multipart) uploader => My-processing-server => Output-files => S3 (regular/multipart) uploader => AWS-S3-server

In other words, the Input-files are expected to be uploaded to My-processing-server as S3 requests so that My-processing-server can process Input-files to generate Output-files, which are then uploaded to the AWS-S3-server.

I would like to know how I can setup an in-house My-processing-server, which can accept Input-files via S3 APIs.

Note: I noticed the client configuration allows configuration of proxy* fields. But if I understood correctly, it simply lets the traffic to be passed via proxy server without introducing any processing steps on the proxy server or changing the file sizes etc.

答:
You can't really intercept API calls to S3 (if I'm understanding what you're asking) and have your own API receive the calls - the ability to do that would break the trust chain for S3's API call.

You have two options here for doing something similar to what you're asking:

Create your own API, and have users upload to your API to process the files. This has the benefit of being more synchronous for your users (I.e., your processing happens immediately on upload, before the file is available on S3), however it has the downside of forcing you to handle all scaling of the service that's doing the transformation. If you mess up that scaling, user file uploads will fail in times of heavy load. This could looks like plain old ec2 server, an ECS container, a lambda+api gateway, etc. There are myriad ways to host a web server.

Create an SQS queue that listens for S3 files that are uploaded to S3. Your users would then upload the file directly to S3 (make sure you look up signed URLs for this if it's a non-trusted user), and you'd listen to the SQS queue for understanding when to process a message (creating your output file). In this case, you'd likely want to store your output file into a separate S3 bucket to avoid a processing loop. This has the benefit of allowing you to rely on S3's built-in scaling to handle times of large load, but it has the downside that your processing is asynchronous from your users. If they upload a file, they wouldn't see it immediately as an output.

There are other soft things that could impact your design (such as whether or not you allow upload of really large files, which would push you to solution #2), but those are the two common design patterns for what you're asking for.

Title: Intercept AWS S3 requests


问:
protoc-gen-go-grpc: program not found or is not executable
go version: go version go1.14 linux/amd64

go.mod

```<code>module [redacted]

go 1.14

require (
    github.com/golang/protobuf v1.4.0-rc.2
    google.golang.org/grpc v1.27.1
    google.golang.org/protobuf v1.20.0 // indirect
)
</code>```

I am running the following command:

```<code>protoc -I ./src/pbdefs/protos/ --go-grpc_out=. src/pbdefs/protos/*.proto
</code>```

to generate my GRPC output files from .proto files, with I am getting  an error

```<code>protoc-gen-go-grpc: program not found or is not executable
Please specify a program using absolute path or make sure the program is available in your PATH system variable
--go-grpc_out: protoc-gen-go-grpc: Plugin failed with status code 1.
</code>```

答:
the missing plugin has been implemented at https://github.com/grpc/grpc-go.

command below should fix it

```<code>go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
</code>```

Body:
go version: go version go1.14 linux/amd64

go.mod

module [redacted]

go 1.14

require (
    github.com/golang/protobuf v1.4.0-rc.2
    google.golang.org/grpc v1.27.1
    google.golang.org/protobuf v1.20.0 // indirect
)

I am running the following command:

protoc -I ./src/pbdefs/protos/ --go-grpc_out=. src/pbdefs/protos/*.proto

to generate my GRPC output files from .proto files, with I am getting  an error

protoc-gen-go-grpc: program not found or is not executable
Please specify a program using absolute path or make sure the program is available in your PATH system variable
--go-grpc_out: protoc-gen-go-grpc: Plugin failed with status code 1.

Body:
the missing plugin has been implemented at https://github.com/grpc/grpc-go.

command below should fix it

go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest


问:
Time limit exceeded when list with large number of elements used?
Function fails performance test when run with a large number of elements: Time limit exceeded .
    How to pass Performance Test ?</p>

```<code> //Function finds indices of two elements whose sum is equal to as passed in the parameter
 public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
 {
     for (int i = 0; i < list.Count; i++)
     {
         int sum2 = sum - list[i];
         int index = list.IndexOf(sum2);
         if (index > 0 )
         {
             return new Tuple<int, int>(i, index);
         }
     }
     return null;
 }

 //Main function to call FindTwoSum method
 public static void Main(string[] args)
 {
  Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 },12);
  Console.WriteLine(indices.Item1 + " " + indices.Item2);
 }
</code>```

答:
I solved the problem using a similar approach. It is as fast as the other solutions, because it goes through the list only once, considering that the access to the dictionary is O (1) the solution will have complexity of O (n).

You can test the code here: TESTDOME - Two sum

```<code>public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
    if (list == null)
        return null;

    var listSet = new Dictionary<int, int>();
    int i = 0;
    // O(n)
    foreach (var elem in list)
    {
        if (listSet.Count > 0) {
            var search = sum - elem;
            if (listSet.ContainsKey(search)) {
                var index = listSet[search];
                if (i != index) {
                    return new Tuple<int, int>(i, index);
                }
            }
        }
        listSet[elem] = i++;
    }
    return null;
}
</code>```

Body:
Function fails performance test when run with a large number of elements: Time limit exceeded .
    How to pass Performance Test ?

 //Function finds indices of two elements whose sum is equal to as passed in the parameter
 public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
 {
     for (int i = 0; i < list.Count; i++)
     {
         int sum2 = sum - list[i];
         int index = list.IndexOf(sum2);
         if (index > 0 )
         {
             return new Tuple<int, int>(i, index);
         }
     }
     return null;
 }

 //Main function to call FindTwoSum method
 public static void Main(string[] args)
 {
  Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 },12);
  Console.WriteLine(indices.Item1 + " " + indices.Item2);
 }

Body:
I solved the problem using a similar approach. It is as fast as the other solutions, because it goes through the list only once, considering that the access to the dictionary is O (1) the solution will have complexity of O (n).

You can test the code here: TESTDOME - Two sum

public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
    if (list == null)
        return null;

    var listSet = new Dictionary<int, int>();
    int i = 0;
    // O(n)
    foreach (var elem in list)
    {
        if (listSet.Count > 0) {
            var search = sum - elem;
            if (listSet.ContainsKey(search)) {
                var index = listSet[search];
                if (i != index) {
                    return new Tuple<int, int>(i, index);
                }
            }
        }
        listSet[elem] = i++;
    }
    return null;
}


问:
How can i change dynamically button variable name in a loop with java
i want to create multiple buttons varibales with different names in a lopp with java, what can i do to get this code automatically?

```<code>GridPane button_grid = new GridPane();
         Button sound_button = new Button("Lire livre N°");
         Button sound_button2 = new Button("Lire livre N°1");
         Button sound_button3 = new Button("Lire livre N°2");
         Button sound_button4 = new Button("Lire livre N°3");
         Button sound_button5 = new Button("Lire livre N°4");
         Button sound_button6 = new Button("Lire livre N°5");
         Button sound_button7 = new Button("Lire livre N°6");
         Button sound_button8 = new Button("Lire livre N°7");
         Button sound_button9 = new Button("Lire livre N°8");
         Button sound_button10 = new Button("Lire livre N°9");
button_grid.add(sound_button, 1,1);
        button_grid.add(sound_button2, 2,1);
        button_grid.add(sound_button3, 3,1);
        button_grid.add(sound_button4, 4,1);
        button_grid.add(sound_button5, 5,1);
        button_grid.add(sound_button6, 6,1);
        button_grid.add(sound_button7, 7,1);
        button_grid.add(sound_button8, 8,1);
        button_grid.add(sound_button9, 9,1);
        button_grid.add(sound_button10,10,1);
</code>```

My objective, is to insert a gridPane into a scrollPane into a VBox, this is my code

```<code>public class controller {

     ScrollPane scrollPane = new ScrollPane();
     GridPane button_grid = new GridPane();
     @FXML private VBox vbox;

     public void initialize() {

         Button sound_button = new Button("Lire livre N°1");
         Button sound_button2 = new Button("Lire livre N°2");

        button_grid.add(sound_button, 1,1);
        button_grid.add(sound_button, 2,1);//<================the ERROR is Here

        scrollPane.setContent(button_grid);
        scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        vbox.getChildren().add(scrollPane);
     }
</code>```

Unfortunatelly i get an error with that code: Children: duplicate children added.
The only way to do this correctly is to have a different button's variables names
sound_button & sound_button2 etc... inserted into button_grid.
How can i have a different button's variable name inside a loop?

Best regards

答:
You can't generate the name of a variable dynamically in this way in Java. Note that in your code, the reference variables for the button are scoped to the body of the loop anyway; since you can't access those variables outside the loop, it doesn't matter what they're called and you may as well let them all have the same name.

The "duplicate children" error you encounter in your code is because you are adding the same button to the grid pane multiple times. The variable you are using to reference the button is irrelevant.

All that actually matters is that you create a new button each time, and add it to the grid pane.

So this code fails, because it adds the same button twice:

```<code>GridPane buttonGrid = new GridPane();
Button soundButton ;

soundButton = new Button("Lire livre N°1");
buttonGrid.add(soundButton, 1, 1);
buttonGrid.add(soundButton, 2, 1); // adds same button: "duplicate children" error
</code>```

And this code also fails, for the same reason, even though it uses different variables:

```<code>GridPane buttonGrid = new GridPane();
Button soundButton1 ;
Button soundButton2 ;

soundButton1 = new Button("Lire livre N°1");
buttonGrid.add(soundButton1, 1, 1);

soundButton2 = soundButton1 ; // second variable refers to same button
buttonGrid.add(soundButton2, 2, 1); // "duplicate children" error
</code>```

Of course, this code succeeds, because it adds two different buttons:

```<code>GridPane buttonGrid = new GridPane();
Button soundButton1 ;
Button soundButton2 ;

soundButton1 = new Button("Lire livre N°1");
buttonGrid.add(soundButton1, 1, 1);

soundButton2 = new Button("Lire livre N°2"); // second variable refers to different button
buttonGrid.add(soundButton2, 2, 1); // succeeds
</code>```

and this also succeed, because it also adds two different buttons, even though it uses the same variable twice:

```<code>GridPane buttonGrid = new GridPane();
Button soundButton ;

soundButton = new Button("Lire livre N°1");
buttonGrid.add(soundButton, 1, 1);

soundButton = new Button("Lire livre N°2"); // update variable to refer to different button
buttonGrid.add(soundButton, 2, 1); // succeeds
</code>```

So in your long-hand, repetitive code, you could achieve this with a single variable:

```<code>GridPane buttonGrid = new GridPane();
Button soundButton ;

soundButton = new Button("Lire livre N°1");
buttonGrid.add(soundButton, 1, 1);

soundButton = new Button("Lire livre N°2");
buttonGrid.add(soundButton, 2, 1);

soundButton = new Button("Lire livre N°3");
buttonGrid.add(soundButton, 3, 1);

soundButton = new Button("Lire livre N°4");
buttonGrid.add(soundButton, 4, 1);

// etc. etc.
</code>```

But of course you can also do this with a loop:

```<code>for (int r = 1; r <= 10; r++) {
    Button soundButton = new Button("Lire livre N°"+r);
    buttonGrid.add(soundButton, r, 1);
}
</code>```

Here is a complete runnable example:

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ButtonGrid extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        ScrollPane scrollPane = new ScrollPane();
        GridPane buttonGrid = new GridPane();
        VBox vbox = new VBox();

        for (int r = 1; r <= 10; r++) {
            Button soundButton = new Button("Lire livre N°" + r);
            buttonGrid.add(soundButton, 1, r);
        }

        scrollPane.setContent(buttonGrid);
        scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        vbox.getChildren().add(scrollPane);

        Scene scene = new Scene(vbox);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        Application.launch(args);
    }

}
</code>```

Body:
i want to create multiple buttons varibales with different names in a lopp with java, what can i do to get this code automatically?

GridPane button_grid = new GridPane();
         Button sound_button = new Button("Lire livre N°");
         Button sound_button2 = new Button("Lire livre N°1");
         Button sound_button3 = new Button("Lire livre N°2");
         Button sound_button4 = new Button("Lire livre N°3");
         Button sound_button5 = new Button("Lire livre N°4");
         Button sound_button6 = new Button("Lire livre N°5");
         Button sound_button7 = new Button("Lire livre N°6");
         Button sound_button8 = new Button("Lire livre N°7");
         Button sound_button9 = new Button("Lire livre N°8");
         Button sound_button10 = new Button("Lire livre N°9");
button_grid.add(sound_button, 1,1);
        button_grid.add(sound_button2, 2,1);
        button_grid.add(sound_button3, 3,1);
        button_grid.add(sound_button4, 4,1);
        button_grid.add(sound_button5, 5,1);
        button_grid.add(sound_button6, 6,1);
        button_grid.add(sound_button7, 7,1);
        button_grid.add(sound_button8, 8,1);
        button_grid.add(sound_button9, 9,1);
        button_grid.add(sound_button10,10,1);

My objective, is to insert a gridPane into a scrollPane into a VBox, this is my code

public class controller {

     ScrollPane scrollPane = new ScrollPane();
     GridPane button_grid = new GridPane();
     @FXML private VBox vbox;

     public void initialize() {

         Button sound_button = new Button("Lire livre N°1");
         Button sound_button2 = new Button("Lire livre N°2");

        button_grid.add(sound_button, 1,1);
        button_grid.add(sound_button, 2,1);//<================the ERROR is Here

        scrollPane.setContent(button_grid);
        scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        vbox.getChildren().add(scrollPane);
     }

Unfortunatelly i get an error with that code: Children: duplicate children added.
The only way to do this correctly is to have a different button's variables names
sound_button & sound_button2 etc... inserted into button_grid.
How can i have a different button's variable name inside a loop?

Best regards

Body:
You can't generate the name of a variable dynamically in this way in Java. Note that in your code, the reference variables for the button are scoped to the body of the loop anyway; since you can't access those variables outside the loop, it doesn't matter what they're called and you may as well let them all have the same name.

The "duplicate children" error you encounter in your code is because you are adding the same button to the grid pane multiple times. The variable you are using to reference the button is irrelevant.

All that actually matters is that you create a new button each time, and add it to the grid pane.

So this code fails, because it adds the same button twice:

GridPane buttonGrid = new GridPane();
Button soundButton ;

soundButton = new Button("Lire livre N°1");
buttonGrid.add(soundButton, 1, 1);
buttonGrid.add(soundButton, 2, 1); // adds same button: "duplicate children" error

And this code also fails, for the same reason, even though it uses different variables:

GridPane buttonGrid = new GridPane();
Button soundButton1 ;
Button soundButton2 ;

soundButton1 = new Button("Lire livre N°1");
buttonGrid.add(soundButton1, 1, 1);

soundButton2 = soundButton1 ; // second variable refers to same button
buttonGrid.add(soundButton2, 2, 1); // "duplicate children" error

Of course, this code succeeds, because it adds two different buttons:

GridPane buttonGrid = new GridPane();
Button soundButton1 ;
Button soundButton2 ;

soundButton1 = new Button("Lire livre N°1");
buttonGrid.add(soundButton1, 1, 1);

soundButton2 = new Button("Lire livre N°2"); // second variable refers to different button
buttonGrid.add(soundButton2, 2, 1); // succeeds

and this also succeed, because it also adds two different buttons, even though it uses the same variable twice:

GridPane buttonGrid = new GridPane();
Button soundButton ;

soundButton = new Button("Lire livre N°1");
buttonGrid.add(soundButton, 1, 1);

soundButton = new Button("Lire livre N°2"); // update variable to refer to different button
buttonGrid.add(soundButton, 2, 1); // succeeds

So in your long-hand, repetitive code, you could achieve this with a single variable:

GridPane buttonGrid = new GridPane();
Button soundButton ;

soundButton = new Button("Lire livre N°1");
buttonGrid.add(soundButton, 1, 1);

soundButton = new Button("Lire livre N°2");
buttonGrid.add(soundButton, 2, 1);

soundButton = new Button("Lire livre N°3");
buttonGrid.add(soundButton, 3, 1);

soundButton = new Button("Lire livre N°4");
buttonGrid.add(soundButton, 4, 1);

// etc. etc.

But of course you can also do this with a loop:

for (int r = 1; r <= 10; r++) {
    Button soundButton = new Button("Lire livre N°"+r);
    buttonGrid.add(soundButton, r, 1);
}

Here is a complete runnable example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ButtonGrid extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        ScrollPane scrollPane = new ScrollPane();
        GridPane buttonGrid = new GridPane();
        VBox vbox = new VBox();

        for (int r = 1; r <= 10; r++) {
            Button soundButton = new Button("Lire livre N°" + r);
            buttonGrid.add(soundButton, 1, r);
        }

        scrollPane.setContent(buttonGrid);
        scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        vbox.getChildren().add(scrollPane);

        Scene scene = new Scene(vbox);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        Application.launch(args);
    }

}


问:
Problem with last card flipping over in memory game
I created a memory card game and I am having an issue that the last card is not flipping over before the alert is coming up that they have finished the game. I have been stuck on thios for a while now and I have inserted my js code below. I'm pretty new to all of this so any help would be great.

```<code>const badges = document.querySelectorAll(".badge-card");

//Declaring the variables
let hasFlippedCard = false;
let isBoardLocked = true;
let cardOne, cardTwo;
let noOfMatches = 0;

//Funtion to randomise the cards
(function randomiseCards() {
  badges.forEach((card) => {
    let ramdomPos = Math.floor(Math.random() * 16);
    card.style.order = ramdomPos;
  });
})();

badges.forEach((card) => card.addEventListener("click", flipCard));

//Funtion to flip the cards
function flipCard() {
  if (isBoardLocked) return;
  if (this === cardOne) return;

  this.classList.add("flip");

  if (!hasFlippedCard) {
    hasFlippedCard = true;
    cardOne = this;
    return;
  }
  cardTwo = this;
  isBoardLocked = true;
  checkForMatch();
}

//Funtion to check for matches
function checkForMatch() {
  let isMatch = cardOne.dataset.framework === cardTwo.dataset.framework;

  if (isMatch) {
    countMatches();
    disableCards();

  } else {
    unflipCards();
  }
}

//Funtion to count matches of cards
function countMatches() {
  noOfMatches = noOfMatches + 1;
  if (foundAllMatches()) {
    alert("Congratulations you got all " + noOfMatches + " matches");
    stopGame();
  }
}

//Funtion to check if user has found all matches
function foundAllMatches() {
  if (noOfMatches == badges.length / 2) {
    return true;
  } else {
    return false;
  }
}

//Funtion to disbale the cards
function disableCards() {
  cardOne.removeEventListener("click", flipCard);
  cardTwo.removeEventListener("click", flipCard);

  resetBoard();
}

//Funtion to unflip the cards
function unflipCards() {
  setTimeout(() => {
    cardOne.classList.remove("flip");
    cardTwo.classList.remove("flip");

    //time to flip card back over
    resetBoard();
  }, 900);
}

//Funtion to reset the board
function resetBoard() {
  hasFlippedCard = false;
  isBoardLocked = false;
  cardOne = null;
  cardTwo = null;
}

//Funtion to unflip cards at end of game
function unflipAllcards() {
  $(".flip").removeClass('flip');
}

//Timer and start game button
  let timeContainer = $('#timer-value');
  let startButton2 = $('#start-game')
  let timer = 0;
  let maxTime = 60;
  let timeout = null;

  function count() {
    timeout = setTimeout(function () {
      if (timer < maxTime) {
        timer++;
        $(timeContainer).text(timer)
        count();
      } else {
        alert("Time's up! You got " + noOfMatches + " matches");
        startButton2.show()
        stopGame();
      }
    }, 1000);
  }

  //Start game button
  function startGame() {
    if (timeout) {
      clearTimeout(timeout);
    }
    timer = 0;
    $(timeContainer).text(timer)
    startButton2.hide()
    count();
    isBoardLocked = false;
  }

  //Funtion for stopping the game
  function stopGame() {
    if (timeout) {
      clearTimeout(timeout);
      startButton2.show()
    }
    timer = 0;
    $(timeContainer).text(timer)
    isBoardLocked = true;
    unflipAllcards();
  }
</code>```

If anyone has any questions please let me know.

答:
An alert stops further javascript execution.
You can either wait until the last card has flipped before firing the alert or create your own popup modal that appears when the memory has been solved.</p>

Body:
I created a memory card game and I am having an issue that the last card is not flipping over before the alert is coming up that they have finished the game. I have been stuck on thios for a while now and I have inserted my js code below. I'm pretty new to all of this so any help would be great.

const badges = document.querySelectorAll(".badge-card");

//Declaring the variables
let hasFlippedCard = false;
let isBoardLocked = true;
let cardOne, cardTwo;
let noOfMatches = 0;

//Funtion to randomise the cards
(function randomiseCards() {
  badges.forEach((card) => {
    let ramdomPos = Math.floor(Math.random() * 16);
    card.style.order = ramdomPos;
  });
})();

badges.forEach((card) => card.addEventListener("click", flipCard));

//Funtion to flip the cards
function flipCard() {
  if (isBoardLocked) return;
  if (this === cardOne) return;

  this.classList.add("flip");

  if (!hasFlippedCard) {
    hasFlippedCard = true;
    cardOne = this;
    return;
  }
  cardTwo = this;
  isBoardLocked = true;
  checkForMatch();
}

//Funtion to check for matches
function checkForMatch() {
  let isMatch = cardOne.dataset.framework === cardTwo.dataset.framework;

  if (isMatch) {
    countMatches();
    disableCards();

  } else {
    unflipCards();
  }
}

//Funtion to count matches of cards
function countMatches() {
  noOfMatches = noOfMatches + 1;
  if (foundAllMatches()) {
    alert("Congratulations you got all " + noOfMatches + " matches");
    stopGame();
  }
}

//Funtion to check if user has found all matches
function foundAllMatches() {
  if (noOfMatches == badges.length / 2) {
    return true;
  } else {
    return false;
  }
}

//Funtion to disbale the cards
function disableCards() {
  cardOne.removeEventListener("click", flipCard);
  cardTwo.removeEventListener("click", flipCard);

  resetBoard();
}

//Funtion to unflip the cards
function unflipCards() {
  setTimeout(() => {
    cardOne.classList.remove("flip");
    cardTwo.classList.remove("flip");

    //time to flip card back over
    resetBoard();
  }, 900);
}

//Funtion to reset the board
function resetBoard() {
  hasFlippedCard = false;
  isBoardLocked = false;
  cardOne = null;
  cardTwo = null;
}

//Funtion to unflip cards at end of game
function unflipAllcards() {
  $(".flip").removeClass('flip');
}

//Timer and start game button
  let timeContainer = $('#timer-value');
  let startButton2 = $('#start-game')
  let timer = 0;
  let maxTime = 60;
  let timeout = null;

  function count() {
    timeout = setTimeout(function () {
      if (timer < maxTime) {
        timer++;
        $(timeContainer).text(timer)
        count();
      } else {
        alert("Time's up! You got " + noOfMatches + " matches");
        startButton2.show()
        stopGame();
      }
    }, 1000);
  }

  //Start game button
  function startGame() {
    if (timeout) {
      clearTimeout(timeout);
    }
    timer = 0;
    $(timeContainer).text(timer)
    startButton2.hide()
    count();
    isBoardLocked = false;
  }

  //Funtion for stopping the game
  function stopGame() {
    if (timeout) {
      clearTimeout(timeout);
      startButton2.show()
    }
    timer = 0;
    $(timeContainer).text(timer)
    isBoardLocked = true;
    unflipAllcards();
  }

If anyone has any questions please let me know.


问:
Open “Add reminder” dialog for mail item by Close event
I would like to get the dialog box for a follow-up flag and CategoriesDialog box to set a reminder when I close the mailitem.

I tried to modify the code from here. When I close a mailitem, all things remain normal and I get the category dialog. I can not get the dialog box for follow-up flag like this. There is no error message popup.

```<code>Public WithEvents objInspector As Outlook.Inspector
Public WithEvents colInspectors As Outlook.Inspectors

Private Sub Application_Startup()
    Init_colInspectorsEvent
End Sub

Private Sub Application_ItemLoad(ByVal Item As Object)
    Init_colInspectorsEvent
End Sub

Private Sub Init_colInspectorsEvent()
    'Initialize the inspectors events handler
    Set colInspectors = Outlook.Inspectors
End Sub

Private Sub colInspectors_NewInspector(ByVal NewInspector As Inspector)
    If NewInspector.CurrentItem.Class = olMail Then MsgBox "New mail inspector is opened"
    If NewInspector.CurrentItem.Class = olTask Then MsgBox "New Task inspector is opened"
    If NewInspector.CurrentItem.Class = olContact Then MsgBox "New Contact inspector is opened"
    Set objInspector = NewInspector
End Sub

Private Sub objInspector_Close()
If objInspector.CurrentItem.Class = olMail Then 'MsgBox "Mail inspector is closing"
    objInspector.CurrentItem.ShowCategoriesDialog
    objInspector.CommandBars.ExecuteMso ("AddReminder") 'No error but not work
    objInspector.CurrentItem.Save
End If
End Sub
</code>```

答:
The Outlook object model doesn't provide any property or method for displaying the Add Reminder... dialog.

The best what you can do is to execute a built-in control programmatically:

```<code>CommandBars.ExecuteMso ("AddReminder")
</code>```

But I don't think the Close event handler is the right place for such things.

Body:
I would like to get the dialog box for a follow-up flag and CategoriesDialog box to set a reminder when I close the mailitem.

I tried to modify the code from here. When I close a mailitem, all things remain normal and I get the category dialog. I can not get the dialog box for follow-up flag like this. There is no error message popup.

Public WithEvents objInspector As Outlook.Inspector
Public WithEvents colInspectors As Outlook.Inspectors

Private Sub Application_Startup()
    Init_colInspectorsEvent
End Sub

Private Sub Application_ItemLoad(ByVal Item As Object)
    Init_colInspectorsEvent
End Sub

Private Sub Init_colInspectorsEvent()
    'Initialize the inspectors events handler
    Set colInspectors = Outlook.Inspectors
End Sub

Private Sub colInspectors_NewInspector(ByVal NewInspector As Inspector)
    If NewInspector.CurrentItem.Class = olMail Then MsgBox "New mail inspector is opened"
    If NewInspector.CurrentItem.Class = olTask Then MsgBox "New Task inspector is opened"
    If NewInspector.CurrentItem.Class = olContact Then MsgBox "New Contact inspector is opened"
    Set objInspector = NewInspector
End Sub

Private Sub objInspector_Close()
If objInspector.CurrentItem.Class = olMail Then 'MsgBox "Mail inspector is closing"
    objInspector.CurrentItem.ShowCategoriesDialog
    objInspector.CommandBars.ExecuteMso ("AddReminder") 'No error but not work
    objInspector.CurrentItem.Save
End If
End Sub

Body:
The Outlook object model doesn't provide any property or method for displaying the Add Reminder... dialog.

The best what you can do is to execute a built-in control programmatically:

CommandBars.ExecuteMso ("AddReminder")

But I don't think the Close event handler is the right place for such things.


问:
performance/efficiency regarding multiple small Entity Framework queries in 1 method
I'm a relatively new programming student, who's in the middle of writing some validation to check data integrity for an "adminSiteUser" entity in EF Core before updating said user with new info (I'm using a microsoft sql-server).

My code looks like this:

AdminSiteUserServices.cs

```<code>    /// <summary>
    /// Edits an admin site user
    /// </summary>
    /// <exception cref="System.NullReferenceException">thrown if user ID or department name doesn't match anything in DB</exception>
    /// <param name="editedAdminSiteUser"></param>
    public void EditAdminSiteUser(AdminSiteUserDTO editedAdminSiteUser)
    {
        //Gets user to be updated. If not found, throw new NullReferenceException
        AdminSiteUser adminSiteUser = _context.AdminSiteUsers.Include(asu => asu.adminSiteUserDepartments).FirstOrDefault(asu => asu.AdminSiteUserID == editedAdminSiteUser.UserID)
            ?? throw new NullReferenceException("Could not find admin site user in the database");

        List<AdminSiteUserDepartment> adminSiteUserDepartments = new List<AdminSiteUserDepartment>();

        //Gets the new departments the admin site user will be a member of. If not found, throw new NullReferenceException
        foreach (string item in editedAdminSiteUser.Departments)
        {
            Department department = _context.Departments.FirstOrDefault(d => d.DepartmentName == item)
                ?? throw new NullReferenceException("Could not find department in the database");

            //Many-to-Many relation between admin site users and departments
            adminSiteUserDepartments.Add(new AdminSiteUserDepartment
            {
                AdminSiteUser = adminSiteUser,
                Department = department
            });
        }

        adminSiteUser.adminSiteUserDepartments = adminSiteUserDepartments;
        adminSiteUser.FirstName = editedAdminSiteUser.FirstName;
        adminSiteUser.LastName = editedAdminSiteUser.LastName;
        adminSiteUser.Username = editedAdminSiteUser.Username;

        _context.Update(adminSiteUser);
    }
</code>```

Now, as far as I understand regarding EF Core, when I iterate through the foreach, EF should be making 1 query per iteration. What I'm wondering is how much influence something like this would have in performance in general against something like 1 query that checked through them all in 1 go.

I should add that this operation will only happen once in a while, since updating an admin site user won't happen so often, but I just got curious how much something like this could potentially influence performance, because I have another method (completely unrelated to this piece of code I'm currently showing) that only runs 1 query per method call, but will be called on average around 300-400 times a day, which I could more easily keep data integrity on if I add another query in the method, but I'm afraid of the impact on performance it could cause.

答:
You want to avoid RBAR (Row by Agonizing Row) as much as possible.  The less round trips to the database, the better.

Taking a closer look at your foreach loop, you can make some significant improvements.

```<code>var departments = _context.Departments.Where(d => editAdminSiteUser
                     .Departments.Contains(d.DepartmentName)).ToList(); //query executes once here

//There is no query execution in the loop
foreach (string item in editedAdminSiteUser.Departments)
{
    departments.FirstOrDefault(d => d.DepartmentName == item)
            ?? throw new NullReferenceException("Could not find department in the database");

        //Many-to-Many relation between admin site users and departments
        adminSiteUserDepartments.Add(new AdminSiteUserDepartment
        {
            AdminSiteUser = adminSiteUser,
            Department = department
        });
}
</code>```

You have all the information to only get the departments you need, so no need to make multiple trips to the database.

Body:
I'm a relatively new programming student, who's in the middle of writing some validation to check data integrity for an "adminSiteUser" entity in EF Core before updating said user with new info (I'm using a microsoft sql-server).

My code looks like this:

AdminSiteUserServices.cs

    ///
    /// Edits an admin site user
    ///
    /// <exception cref="System.NullReferenceException">thrown if user ID or department name doesn't match anything in DB</exception>
    /// <param name="editedAdminSiteUser"></param>
    public void EditAdminSiteUser(AdminSiteUserDTO editedAdminSiteUser)
    {
        //Gets user to be updated. If not found, throw new NullReferenceException
        AdminSiteUser adminSiteUser = _context.AdminSiteUsers.Include(asu => asu.adminSiteUserDepartments).FirstOrDefault(asu => asu.AdminSiteUserID == editedAdminSiteUser.UserID)
            ?? throw new NullReferenceException("Could not find admin site user in the database");

        List<AdminSiteUserDepartment> adminSiteUserDepartments = new List<AdminSiteUserDepartment>();

        //Gets the new departments the admin site user will be a member of. If not found, throw new NullReferenceException
        foreach (string item in editedAdminSiteUser.Departments)
        {
            Department department = _context.Departments.FirstOrDefault(d => d.DepartmentName == item)
                ?? throw new NullReferenceException("Could not find department in the database");

            //Many-to-Many relation between admin site users and departments
            adminSiteUserDepartments.Add(new AdminSiteUserDepartment
            {
                AdminSiteUser = adminSiteUser,
                Department = department
            });
        }

        adminSiteUser.adminSiteUserDepartments = adminSiteUserDepartments;
        adminSiteUser.FirstName = editedAdminSiteUser.FirstName;
        adminSiteUser.LastName = editedAdminSiteUser.LastName;
        adminSiteUser.Username = editedAdminSiteUser.Username;

        _context.Update(adminSiteUser);
    }

Now, as far as I understand regarding EF Core, when I iterate through the foreach, EF should be making 1 query per iteration. What I'm wondering is how much influence something like this would have in performance in general against something like 1 query that checked through them all in 1 go.

I should add that this operation will only happen once in a while, since updating an admin site user won't happen so often, but I just got curious how much something like this could potentially influence performance, because I have another method (completely unrelated to this piece of code I'm currently showing) that only runs 1 query per method call, but will be called on average around 300-400 times a day, which I could more easily keep data integrity on if I add another query in the method, but I'm afraid of the impact on performance it could cause.

Body:
You want to avoid RBAR (Row by Agonizing Row) as much as possible.  The less round trips to the database, the better.

Taking a closer look at your foreach loop, you can make some significant improvements.

var departments = _context.Departments.Where(d => editAdminSiteUser
                     .Departments.Contains(d.DepartmentName)).ToList(); //query executes once here

//There is no query execution in the loop
foreach (string item in editedAdminSiteUser.Departments)
{
    departments.FirstOrDefault(d => d.DepartmentName == item)
            ?? throw new NullReferenceException("Could not find department in the database");

        //Many-to-Many relation between admin site users and departments
        adminSiteUserDepartments.Add(new AdminSiteUserDepartment
        {
            AdminSiteUser = adminSiteUser,
            Department = department
        });
}

You have all the information to only get the departments you need, so no need to make multiple trips to the database.


问:
jsonpCallback function not working
UPDATE 1:

I've just upgraded from jquery 1.4.4 to 1.6.1.  How does that effect the script in the original question?

ORIGINAL QUESTION:

Just as I test, I did:

```<code>$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }

    function jsonpCallback(data){
        alert("jsonpCallback");
    }
});
</code>```

I was expecting to get 2 alerts, the first showing success and the second showing jsonpCallback.  But I am only getting the first alert success.  Why is the second alert not showing up?

答:
You should change:

```<code>jsonp: 'callback',
</code>```

to

```<code>jsonp: false
</code>```

to override the default callback value.

See: http://api.jquery.com/jQuery.ajax/

Title: jsonpCallback function not working

Body:
UPDATE 1:

I've just upgraded from jquery 1.4.4 to 1.6.1.  How does that effect the script in the original question?

ORIGINAL QUESTION:

Just as I test, I did:

$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }

    function jsonpCallback(data){
        alert("jsonpCallback");
    }
});

I was expecting to get 2 alerts, the first showing success and the second showing jsonpCallback.  But I am only getting the first alert success.  Why is the second alert not showing up?

Body:
You should change:

jsonp: 'callback',

to

jsonp: false

to override the default callback value.

See: http://api.jquery.com/jQuery.ajax/


问:
Slide in text when icon is hovered
I've been trying to get an effect where:

Icon Font is shown, text beside it is hidden.

when hover on an icon, slide in the text that is hidden. Slide in from the right.

Here is what I've tried so far:

(Since it will take to much time, replaced icons with some random keyboard symbols)
http://jsfiddle.net/h9EX9/

```<code>ul li { display: inline-block; list-style-type: none; margin-right: 10px; background: #eee; }
ul li span { display: inline-block; }
ul li a { display: inline-block; width: 0; height: 0; overflow: hidden;  }
ul li:hover a  { transition: all 1s ease-out; width: 100%; height: auto; }
</code>```

This is the effect I'm trying to accomplish. Text and and width of comment slides from the right. But there are other icons besides this one. I hope its also possible to slide those when the width of the background expands.

So is this possible, if so how?

答:
I know this is an old post, but this might help new people coming here...

This is a fix and improvement on [@SeekingKnowledge's][1] post (linked). Below is my version of the code, explained.
```<code>$("#closeText").hide(); $("#close").hover(function(){ $("#closeText").show("slide", { direction: "left" }, 400);}, function(){ $("#closeText").hide("slide", { direction: "left" }, 400);});
</code>```

Replace #close with your icon element's ID, and change all three #closeText with the element that contains your text's ID. You can customise the animation time by changing the value currently at 400 (measured in milliseconds), however, this is a good speed for my site. You also need to set #close CSS to have a z-index of 2 more than the z-index of the #closeText.
Remember to get jQuery!

Here's how I used it for one of my pages on my website (link to CodePen).

Hope this helped anyone looking here for answers!
Luka S

Title: Slide in text when icon is hovered

Body:
I've been trying to get an effect where:

Icon Font is shown, text beside it is hidden.

when hover on an icon, slide in the text that is hidden. Slide in from the right.

Here is what I've tried so far:

(Since it will take to much time, replaced icons with some random keyboard symbols)
http://jsfiddle.net/h9EX9/

ul li { display: inline-block; list-style-type: none; margin-right: 10px; background: #eee; }
ul li span { display: inline-block; }
ul li a { display: inline-block; width: 0; height: 0; overflow: hidden;  }
ul li:hover a  { transition: all 1s ease-out; width: 100%; height: auto; }

This is the effect I'm trying to accomplish. Text and and width of comment slides from the right. But there are other icons besides this one. I hope its also possible to slide those when the width of the background expands.

So is this possible, if so how?

Body:
I know this is an old post, but this might help new people coming here...

This is a fix and improvement on [@SeekingKnowledge's][1] post (linked). Below is my version of the code, explained.

$("#closeText").hide(); $("#close").hover(function(){ $("#closeText").show("slide", { direction: "left" }, 400);}, function(){ $("#closeText").hide("slide", { direction: "left" }, 400);});

Replace #close with your icon element's ID, and change all three #closeText with the element that contains your text's ID. You can customise the animation time by changing the value currently at 400 (measured in milliseconds), however, this is a good speed for my site. You also need to set #close CSS to have a z-index of 2 more than the z-index of the #closeText.
Remember to get jQuery!

Here's how I used it for one of my pages on my website (link to CodePen).

Hope this helped anyone looking here for answers!
Luka S


问:
How to produce a list of enum keys/names in groovy
I have the following enum in groovy

```<code>public enum ImageTypes {

    jpg ("image/jpeg"),
    jpeg ("image/jpeg"),
    jpe ("image/jpeg"),
    jfif ("image/jpeg"),
    bmp ("image/bmp"),
    png ("image/png"),
    gif ("image/gif"),
    ief ("image/ief"),
    tiff ("image/tiff"),
    tif ("image/tiff"),
    pcx ("image/pcx"),
    pdf ("application/pdf"),

    final String value

    ImageTypes(String value) {
        this.value = value
    }

    String getValue() {
        return this.value
    }

    String toString(){
        value
    }

    String getKey() {
        name()
    }
}
</code>```

and I want to produce an ArrayList<String> of the keys or the values

What I am currently doing is looping through all the items and building the array list, but I'm thinking there has got to be a simple way to do this...

```<code>def imageTypes = ImageTypes.values()
def fileExts = new ArrayList<String>()
def mimeTypes = new ArrayList<String>()
for (type in imageTypes) {
    fileExts.add(type.key)
    mimeTypes.add(type.value)
}
</code>```

答:
Expanding @mnd's answer -

The Spread Operator is the best choice, but if you're using Jenkins this won't work as is. To run the Spread Operator you will need to add @NonCPS in the Jenkins Pipeline DSL.

Another way to the list of enum keys is to directly use its Enumeration features.

```<code>ImageTypes.values().collect() { it.name() }
</code>```

Body:
I have the following enum in groovy

public enum ImageTypes {

    jpg ("image/jpeg"),
    jpeg ("image/jpeg"),
    jpe ("image/jpeg"),
    jfif ("image/jpeg"),
    bmp ("image/bmp"),
    png ("image/png"),
    gif ("image/gif"),
    ief ("image/ief"),
    tiff ("image/tiff"),
    tif ("image/tiff"),
    pcx ("image/pcx"),
    pdf ("application/pdf"),

    final String value

    ImageTypes(String value) {
        this.value = value
    }

    String getValue() {
        return this.value
    }

    String toString(){
        value
    }

    String getKey() {
        name()
    }
}

and I want to produce an ArrayList<String> of the keys or the values

What I am currently doing is looping through all the items and building the array list, but I'm thinking there has got to be a simple way to do this...

def imageTypes = ImageTypes.values()
def fileExts = new ArrayList<String>()
def mimeTypes = new ArrayList<String>()
for (type in imageTypes) {
    fileExts.add(type.key)
    mimeTypes.add(type.value)
}

Body:
Expanding @mnd's answer -

The Spread Operator is the best choice, but if you're using Jenkins this won't work as is. To run the Spread Operator you will need to add @NonCPS in the Jenkins Pipeline DSL.

Another way to the list of enum keys is to directly use its Enumeration features.

ImageTypes.values().collect() { it.name() }


问:
Openssl telling certificate has expired when it has not
I'm having an issue with curl and openssl reporting a client certificate as expired, even though it's notAfter date is in the future:

```<code># echo | openssl s_client -showcerts -connect example.com:443 2>&1 | grep Verify
    Verify return code: 10 (certificate has expired)
</code>```

But

```<code># echo | openssl s_client -showcerts -connect example.com:443 2>&1 | openssl x509 -noout -dates
notBefore=Oct 17 00:00:00 2011 GMT
notAfter=Oct 21 12:00:00 2014 GMT
</code>```

System date is correct. Firefox is not showing any error for that site's cert either. Openssl versions I tried are OpenSSL 1.0.1e-fips 11 Feb 2013 and OpenSSL 1.0.1f 6 Jan 2014. I've found a similar-looking issue here where the author claims that the issue is missing in openssl 0.9.8, but present in 1.0.1.

Why is this happening?

答:
If you just execute openssl s_client -connect <server>:<port>, it should show you at the end after the Verify...  line something like:

```<code>---
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify error:num=10:certificate has expired
notAfter=May 30 10:48:38 2020 GMT
read:errno=10093
</code>```

Basically this failure message mentions the certificate in the certificate chain that was not verified and why it happened.

Body:
I'm having an issue with curl and openssl reporting a client certificate as expired, even though it's notAfter date is in the future:

# echo | openssl s_client -showcerts -connect example.com:443 2>&1 | grep Verify
    Verify return code: 10 (certificate has expired)

But

# echo | openssl s_client -showcerts -connect example.com:443 2>&1 | openssl x509 -noout -dates
notBefore=Oct 17 00:00:00 2011 GMT
notAfter=Oct 21 12:00:00 2014 GMT

System date is correct. Firefox is not showing any error for that site's cert either. Openssl versions I tried are OpenSSL 1.0.1e-fips 11 Feb 2013 and OpenSSL 1.0.1f 6 Jan 2014. I've found a similar-looking issue here where the author claims that the issue is missing in openssl 0.9.8, but present in 1.0.1.

Why is this happening?

Body:
If you just execute openssl s_client -connect <server>:<port>, it should show you at the end after the Verify...  line something like:

---
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify error:num=10:certificate has expired
notAfter=May 30 10:48:38 2020 GMT
read:errno=10093

Basically this failure message mentions the certificate in the certificate chain that was not verified and why it happened.


问:
PC gets restart on running android studio emulator
I have installed andriod studio 3.6 latest version and then configured by setting environment variables.

When i actually run virtual device Pixel 3 emulator, my PC ran in to problem with blue screen.

```
Blue screen error message:
Your PC ran into a problem and needs to restart. Were just collecting some error info, and then you can restart.
```

How to resolve this ? what is the problem ?

答:
I had the same problem and spend a lot of time trying to solve it. Finally find what was the problem - Windows update!
This Windows patches are causing the problem - KB4554354 and KB4549949

Updating the Windows to version 1909 (OS build 18363.836) fix the issue for me.

If you can't update windows to this version for some reason you can try to remove this patches.
You can rollback and uninstall your recent update follow these Steps:

Press Start button then click on the Gear icon which is the Settings

Press "Update and Security"

Press "View Update History"

Select "Uninstall Updates"

A pop up should appear then scroll down to the bottom then on the Microsoft Windows section, right click the recent or all of the "Update for Microsoft Windows KB4554354" then Click "uninstall".

wait for the process to be finished then restart the PC/Laptop there you should have the fix on your update problems.

Body:
I have installed andriod studio 3.6 latest version and then configured by setting environment variables.

When i actually run virtual device Pixel 3 emulator, my PC ran in to problem with blue screen.

Blue screen error message:
Your PC ran into a problem and needs to restart. Were just collecting some error info, and then you can restart.

How to resolve this ? what is the problem ?


问:
How compiler (Visual C++) optimize accessing vector elements by index?
I am trying to build tree where each node can have infinite children, and propagate some values from root down the tree. I tried multiple ways to achieve that.
First was by allocation of each individual node on heap. Then i tried to create vector of Nodes (not pointers to Nodes ) and build tree with Node pointers pointing to elements of that vector.
This was faster solution, because I stored nodes in one block of memory I guess. This solution works great but if vector resizes I have to rebuild whole tree again. Third option was to use build tree using indices instead of pointers. Only time index is invalidated is when I remove element from vector, but it is only one node so it is no big deal ( swap last element with removed one ). This solution is the slowest one on my machine, in debug mode ( using visual studio 2019) other two solutions perform a lot better in debug mode. But when i switch to release mode with optimization, this solution perform similiar to the solution where i used pointers to elements of vector. I read that compiler might use pointers directly instead of indices when optimization is on. But I can not really answer that. So my question is what is really going on? And can I assume that speed of code using indices will be almost same all the time?

Node using pointers:

```<code>struct Node
{
    void SetParent(Node* parent)
    {
        Parent = parent;
        NextSibling = parent->FirstChild;
        parent->FirstChild = this;
    }

    void Propagate(float x,float y)
    {
        Node* tmp = this;
        while (tmp)
        {
            tmp->X += x;
            tmp->Y += y;
            if (tmp->FirstChild)
                tmp->FirstChild->Propagate(tmp->X,tmp->Y);

            tmp = tmp->NextSibling;
        }
    }
    float X, Y;
    std::string Name;

    Node* Parent = nullptr;
    Node* FirstChild = nullptr;
    Node* NextSibling = nullptr;
}
</code>```

Node using indices:

```<code>struct Node
{
    void SetParent(std::vector<Node>& list,int parent)
    {
        Parent = parent;
        NextSibling = list[parent].FirstChild;
        list[parent].FirstChild = Index;
    }

    void Propagate(std::vector<Node>& list, int index, float x, float y)
    {
        while (index != -1)
        {
            list[index].X += x;
            list[index].Y += y;
            if (list[index].FirstChild != -1)
            {
                list[list[index].FirstChild].Propagate(list, list[index].FirstChild, list[index].X,
                 list[index].Y);
            }
            index = list[index].NextSibling;
        }
    }

    float X, Y;
    std::string Name;
    int Index = -1;
    int Parent = -1;
    int FirstChild = -1;
    int NextSibling = -1;
};

</code>```

答:
You'we been told in the comments that comparing the performance of the debug builds is not really useful. That statement is correct, and the issue here is not that release builds do something magical to access your vectors, but that debug builds are slowed down by a lot of verification and instrumentation code that does not get into the release builds.

Consider:
Depending on the stdc++ implementation, T operator[](size_t index) const can contain range checking code in debug build that you simply step around when you directly use pointers (IIRC, that how things work in Visual Studio stdc++ implementation).

Naturally, your debug build using pointer accesses will be faster, but you have already found many of the pitfalls.

Summa summarum: using indices in your case is perfectly fine. They won't hurt performance. In scenarios like these it's typically not the indexing that hurts, but how coherent those memory accesses are, are you trashing your CPU cache, etc.

Body:
I am trying to build tree where each node can have infinite children, and propagate some values from root down the tree. I tried multiple ways to achieve that.
First was by allocation of each individual node on heap. Then i tried to create vector of Nodes (not pointers to Nodes ) and build tree with Node pointers pointing to elements of that vector.
This was faster solution, because I stored nodes in one block of memory I guess. This solution works great but if vector resizes I have to rebuild whole tree again. Third option was to use build tree using indices instead of pointers. Only time index is invalidated is when I remove element from vector, but it is only one node so it is no big deal ( swap last element with removed one ). This solution is the slowest one on my machine, in debug mode ( using visual studio 2019) other two solutions perform a lot better in debug mode. But when i switch to release mode with optimization, this solution perform similiar to the solution where i used pointers to elements of vector. I read that compiler might use pointers directly instead of indices when optimization is on. But I can not really answer that. So my question is what is really going on? And can I assume that speed of code using indices will be almost same all the time?

Node using pointers:

struct Node
{
    void SetParent(Node* parent)
    {
        Parent = parent;
        NextSibling = parent->FirstChild;
        parent->FirstChild = this;
    }

    void Propagate(float x,float y)
    {
        Node* tmp = this;
        while (tmp)
        {
            tmp->X += x;
            tmp->Y += y;
            if (tmp->FirstChild)
                tmp->FirstChild->Propagate(tmp->X,tmp->Y);

            tmp = tmp->NextSibling;
        }
    }
    float X, Y;
    std::string Name;

    Node* Parent = nullptr;
    Node* FirstChild = nullptr;
    Node* NextSibling = nullptr;
}

Node using indices:

struct Node
{
    void SetParent(std::vector<Node>& list,int parent)
    {
        Parent = parent;
        NextSibling = list[parent].FirstChild;
        list[parent].FirstChild = Index;
    }

    void Propagate(std::vector<Node>& list, int index, float x, float y)
    {
        while (index != -1)
        {
            list[index].X += x;
            list[index].Y += y;
            if (list[index].FirstChild != -1)
            {
                list[list[index].FirstChild].Propagate(list, list[index].FirstChild, list[index].X,
                 list[index].Y);
            }
            index = list[index].NextSibling;
        }
    }

    float X, Y;
    std::string Name;
    int Index = -1;
    int Parent = -1;
    int FirstChild = -1;
    int NextSibling = -1;
};


问:
How to convert the inner value in an Option?
I have an Option that contains some JSON. If it is Some, the inner JSON must be converted, but if it is None, it must remain None.

This is how I have this implemented currently:

```<code>struct One;
struct Other;

impl One {
    pub fn convert(&self) -> Other {
        Other {}
    }
}

fn example(attr: Option<One>) -> Option<Other> {
    match attr {
        Some(attr) => Some(attr.convert()),
        None => None,
    }
}
</code>```

I'm new to Rust and don't fully get the intricacies of when to use match, if let or when to use the ? operator.

Is my implementation idiomatic Rust? It seems rather verbose to me, and looks like a pattern that will occur all over the place, so I can imagine this can be handled far more concise; is that so?

答:
Use Option::map:

fn example_a(attr: Option<One>) -> Option<Other> {
    attr.map(|v| v.convert())
}
```

<p>Since your function accepts a reference, you can also use <code>Option::as_ref</code> and then directly use the function inside of <code>map</code> instead of a closure:</p>

<pre class="lang-rust prettyprint-override"><code>fn example_b(attr: Option<One>) -> Option<Other> {
    attr.as_ref().map(One::convert)
}
</code>```

See also:

Converting from Option<String> to Option<&str>

Lifetime of Option::map's argument

How to implement some convenient methods (e.g., flat_map, flatten) on Option?

Use Option::map to Box::new a trait object does not work

How to convert Option<&T> to Option<T> in the most idiomatic way in Rust?

Is it possible to convert Option<Result<T, E>> to a Result<Option<T>, E> without using match?

Body:
I have an Option that contains some JSON. If it is Some, the inner JSON must be converted, but if it is None, it must remain None.

This is how I have this implemented currently:

struct One;
struct Other;

impl One {
    pub fn convert(&self) -> Other {
        Other {}
    }
}

fn example(attr: Option<One>) -> Option<Other> {
    match attr {
        Some(attr) => Some(attr.convert()),
        None => None,
    }
}

I'm new to Rust and don't fully get the intricacies of when to use match, if let or when to use the ? operator.

Is my implementation idiomatic Rust? It seems rather verbose to me, and looks like a pattern that will occur all over the place, so I can imagine this can be handled far more concise; is that so?

Body:
Use Option::map:

fn example_a(attr: Option<One>) -> Option<Other> {
    attr.map(|v| v.convert())
}

Since your function accepts a reference, you can also use Option::as_ref and then directly use the function inside of map instead of a closure:

fn example_b(attr: Option<One>) -> Option<Other> {
    attr.as_ref().map(One::convert)
}

See also:

Converting from Option<String> to Option<&str>

Lifetime of Option::map's argument

How to implement some convenient methods (e.g., flat_map, flatten) on Option?

Use Option::map to Box::new a trait object does not work

How to convert Option<&T> to Option<T> in the most idiomatic way in Rust?

Is it possible to convert Option<Result<T, E>> to a Result<Option<T>, E> without using match?


问:
Enabling blocked text selection using JavaScript
I recently came across a website that disabled text selection, preventing anyone from easily copying and pasting text. I have a bookmarklet that disables similar attempts to block context menus using JavaScript, and I'm wondering if it would be possible to do something similar for text selection.

```<code>function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}
</code>```

Elsewhere the function is called with disableSelection(document.body).

The solution from my context menu bookmarklet is also probably necessary:

```<code>javascript:void(document.onmousedown=null);
void(document.onclick=null);
void(document.oncontextmenu=null)
</code>```

Finally, I had seen elsewhere on StackOverflow that CSS could also be used:

```<code>-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
</code>```

Is there a method to fight all of these at once and end this tyranny over my browser? How would I both enable MozUserSelect/SelectStart for all elements and set the CSS properties?

答:
if you are on google chrome you can use this extension

https://chrome.google.com/webstore/detail/enable-selection/jehoagbopeaefibnihnfgenfcilmcikj/

It enables text selection and the right click if it's blocked

Body:
I recently came across a website that disabled text selection, preventing anyone from easily copying and pasting text. I have a bookmarklet that disables similar attempts to block context menus using JavaScript, and I'm wondering if it would be possible to do something similar for text selection.

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}

Elsewhere the function is called with disableSelection(document.body).

The solution from my context menu bookmarklet is also probably necessary:

javascript:void(document.onmousedown=null);
void(document.onclick=null);
void(document.oncontextmenu=null)

Finally, I had seen elsewhere on StackOverflow that CSS could also be used:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

Is there a method to fight all of these at once and end this tyranny over my browser? How would I both enable MozUserSelect/SelectStart for all elements and set the CSS properties?


问:
How to create a custom PreprocessingLayer in TF 2.2
I would like to create a custom preprocessing layer using the tf.keras.layers.experimental.preprocessing.PreprocessingLayer layer.

In this custom layer, placed after the input layer, I would like to normalize my image using tf.cast(img, tf.float32) / 255.

I tried to find some code or example showing how to create this preprocessing layer, but I couldn't find.

Please, can someone provide a full example creating and using the PreprocessingLayer layer ?

答:
I think that the best and cleaner solution to do this is using a simple Lambda layer where you can wrap your pre-processing function

this is a dummy working example

```<code>import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras.models import *

X = np.random.randint(0,256, (200,32,32,3))
y = np.random.randint(0,3, 200)

inp = Input((32,32,3))
x = Lambda(lambda x: x/255)(inp)
x = Conv2D(8, 3, activation='relu')(x)
x = Flatten()(x)
out = Dense(3, activation='softmax')(x)

m = Model(inp, out)
m.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = m.fit(X, y, epochs=10)
</code>```

Body:
I think that the best and cleaner solution to do this is using a simple Lambda layer where you can wrap your pre-processing function

this is a dummy working example

import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras.models import *

X = np.random.randint(0,256, (200,32,32,3))
y = np.random.randint(0,3, 200)

inp = Input((32,32,3))
x = Lambda(lambda x: x/255)(inp)
x = Conv2D(8, 3, activation='relu')(x)
x = Flatten()(x)
out = Dense(3, activation='softmax')(x)

m = Model(inp, out)
m.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = m.fit(X, y, epochs=10)


问:
Is it possible to access AWS Cognito API with access token?
I have a simple application consisting of two modules - OAuth2 client (Spring Cloud Gateway) and OAuth2 resource. I use AWS Cognito as an identity provider. Some users with specific roles should be able to create/update/delete other Cognito users.

I'm going to use aws-java-sdk-cognitoidp library for integration with AWS Cognito API, but I need to make this calls as a current logged-in user, to be able to check user's groups and IAM roles. Because users from different groups should have different privileges.

I found AWSSessionCredentialsProvider that seems suitable for this task, but there is no implementation.

I implemented this provider to get access token from the SecurityContext. When I call the API I get an error:

The security token included in the request is invalid

Is it possible to use user's access token as a credentials for AWSCognitoIdentityProvider?

答:
I used to have app to login with given user with his credentials -

```<code>AWSCognitoIdentityProvider cognitoIdentityProvider = AWSCognitoIdentityProviderClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(getSDKCredentials()))
                .withRegion(Regions.fromName(getAwsRegion()))
                .build();

    Map<String,String> params =new HashMap<>();
        params.put("USERNAME", userName);
        params.put("PASSWORD", passCode);

    AdminInitiateAuthRequest initialRequest=new AdminInitiateAuthRequest()
            .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
            .withAuthParameters(params)
            .withClientId(getClientId())
            .withUserPoolId(getUserPoolId());

    AdminInitiateAuthResult response = cognitoIdentityProvider.adminInitiateAuth(initialRequest);
</code>```

this will return your response where you have session. check if it helps-

Body:
I used to have app to login with given user with his credentials -

AWSCognitoIdentityProvider cognitoIdentityProvider = AWSCognitoIdentityProviderClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(getSDKCredentials()))
                .withRegion(Regions.fromName(getAwsRegion()))
                .build();

    Map<String,String> params =new HashMap<>();
        params.put("USERNAME", userName);
        params.put("PASSWORD", passCode);

    AdminInitiateAuthRequest initialRequest=new AdminInitiateAuthRequest()
            .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
            .withAuthParameters(params)
            .withClientId(getClientId())
            .withUserPoolId(getUserPoolId());

    AdminInitiateAuthResult response = cognitoIdentityProvider.adminInitiateAuth(initialRequest);

this will return your response where you have session. check if it helps-


问:
tar -xvf file.tar.gz failed with: gzip:stdin:not in gzip format
I tar a set of files with command:tar -czvf file.tar.gz file/ then copy to usb (ext4 format), I checked that I can untar it. After I reinstall system , when mount usb , some error happened , I do fsck /dev/sdc1 and success in mount and copy it to pc. When I untar it tar -xvf file.tar.gz, error happen again:

```<code>gzip: stdin: not in gzip format
tar : child returned status 1
tar: Error is not recoverable: exiting now
</code>```

I have no idea how to rescue the data.
Any help needed. Thanks.

答:
check for file by the command

```<code>file <file name>

<filename>: HTML document, ASCII text, with very long lines
</code>```

comes then it may be corrupted

Body:
I tar a set of files with command:tar -czvf file.tar.gz file/ then copy to usb (ext4 format), I checked that I can untar it. After I reinstall system , when mount usb , some error happened , I do fsck /dev/sdc1 and success in mount and copy it to pc. When I untar it tar -xvf file.tar.gz, error happen again:

gzip: stdin: not in gzip format
tar : child returned status 1
tar: Error is not recoverable: exiting now

I have no idea how to rescue the data.
Any help needed. Thanks.

Body:
check for file by the command

file <file name>

<filename>: HTML document, ASCII text, with very long lines

comes then it may be corrupted


问:
Google Sheet Query Cannot be Parsed to date/time
I have a problem with my google sheet query.

=query(teachers,"select A,B,C,D,E,F where B = '"&A2&"' AND G = date '"&TEXT(DATEVALUE("'"&B2&"'"),"yyyy-mm-dd")&"' label A 'DATE', B 'NAME OF TEACHER', C 'LOG IN FOR', D 'LOG IN TIME', E 'LOG OUT FOR', F 'LOG OUT TIME'",1)

WHERE cell B2 is a dropdown filter (using data range) where user will select the date he/she wants to display dynamically. But it resulted to an error says "cannot be parsed to date/time". But if i change the value like this:

=query(teachers,"select A,B,C,D,E,F where B = '"&A2&"' AND G = date '"&TEXT(DATEVALUE("6/2/2020"),"yyyy-mm-dd")&"' label A 'DATE', B 'NAME OF TEACHER', C 'LOG IN FOR', D 'LOG IN TIME', E 'LOG OUT FOR', F 'LOG OUT TIME'",1)

it will work but I want that cell B2 to be controlled dynamically by the user.

Please help me with my problem. Thanks!

答:
I'd say you just need to remove the quotes around B2:

TEXT(DATEVALUE(B2),"yyyy-mm-dd")

Reference:

DATEVALUE


问:
Corda: Synchronize multiple Nodes that represent same Party
I am working on a Cordapp that contain multiple nodes. In my app, every party will be represented by two nodes running at different locations. One of the nodes will always be Online where as the other node can be offline/online at times.

I am looking for an API with-in Corda that will enable the offline node to run a job/api to synchronize with the online node. I could not find any such API.

Can you please suggest if you have come across a similar scenario and it here is already any available API/usecase.

答:
You can write a pair of flows for the on/off node to request clone all the details from the always-online node.

On/Off node

```<code>FlowSession session = initiateFlow(alwaysOnNode);

//Send any hint for the other node to query the past transactions, maybe a timestamp?
session.send(hint);

/*
* Waiting for the On/Off node to reply
*/

//Receive the transaction and store it in its vault. The use of ALL_VISIBLE is critical here
subFlow(new ReceiveTransactionFlow(session, true, StatesToRecord.ALL_VISIBLE));
</code>```

Always on node

```<code>//Query the newest transaction happened from the vault. Here I used the transaction hash in my case
SignedTransaction stx = getServiceHub().getValidatedTransactions().getTransaction(state.getRef().getTxhash());

//Send it back to the on/off node for update
subFlow(new SendTransactionFlow(holderSession, stx));
</code>```

Here is an example I wrote which the shareholder asks the company for any happened transaction about a StockState.

Body:
You can write a pair of flows for the on/off node to request clone all the details from the always-online node.

On/Off node

FlowSession session = initiateFlow(alwaysOnNode);

//Send any hint for the other node to query the past transactions, maybe a timestamp?
session.send(hint);

/*
* Waiting for the On/Off node to reply
*/

//Receive the transaction and store it in its vault. The use of ALL_VISIBLE is critical here
subFlow(new ReceiveTransactionFlow(session, true, StatesToRecord.ALL_VISIBLE));

Always on node

//Query the newest transaction happened from the vault. Here I used the transaction hash in my case
SignedTransaction stx = getServiceHub().getValidatedTransactions().getTransaction(state.getRef().getTxhash());

//Send it back to the on/off node for update
subFlow(new SendTransactionFlow(holderSession, stx));

Here is an example I wrote which the shareholder asks the company for any happened transaction about a StockState.


问:
getting data from database table using cursor in android
I have one employee table which has column values

```<code>("store_loc_id","name","password","address_id","role_id",
"retailer_id").
</code>```

I want to get the name and password from this table using cursor. how can i do??

答:
Haven't check this code, but the idiom should be understandable.</p>

```<code>Cursor cursor = db.query(...);
if(cursor !=null && cursor.moveToFirst()) {
   do {
     String name = cursor.getString(cursor.getColumnIndex("name"));
   } while (cursor.moveToNext());
}
</code>```

Body:
I have one employee table which has column values

("store_loc_id","name","password","address_id","role_id",
"retailer_id").

I want to get the name and password from this table using cursor. how can i do??

Body:
Haven't check this code, but the idiom should be understandable.

Cursor cursor = db.query(...);
if(cursor !=null && cursor.moveToFirst()) {
   do {
     String name = cursor.getString(cursor.getColumnIndex("name"));
   } while (cursor.moveToNext());
}