问:
AttributeError: 'NoneType' object has no attribute 'transform' when sending inference request to SageMaker endpoint
I'm working on a SageMaker AutoGluon prediction model and after performing batch transform and creating the endpoint I've been trying to send inference requests to the endpoint but I keep getting the following error:

```<code>ModelError                                Traceback (most recent call last)
<ipython-input-54-47897c53ab79> in <module>
11     for row in f:
12         payload = row.rstrip('\n')
13         response = predictor.predict(data=payload[2:])
14         sleep(0.5)
15 print('done!')

/opt/conda/lib/python3.7/site-packages/sagemaker/predictor.py in predict(self, data, initial_args, target_model, target_variant, inference_id)
159             data, initial_args, target_model, target_variant, inference_id
160         )
161         response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)
162         return self._handle_response(response)
163

/opt/conda/lib/python3.7/site-packages/botocore/client.py in _api_call(self, *args, **kwargs)
528                 )
529             # The "self" in this scope is referring to the BaseClient.
530             return self._make_api_call(operation_name, kwargs)
531
532         _api_call.__name__ = str(py_operation_name)

/opt/conda/lib/python3.7/site-packages/botocore/client.py in _make_api_call(self, operation_name, api_params)
958             error_code = parsed_response.get("Error", {}).get("Code")
959             error_class = self.exceptions.from_code(error_code)
960             raise error_class(parsed_response, operation_name)
961         else:
962             return parsed_response

ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (503) from primary with message "{
  "code": 503,
  "type": "InternalServerException",
  "message": "Prediction failed"
}
See https://ap-south-1.console.aws.amazon.com/cloudwatch/home?region=ap-south-1#logEventViewer:group=/aws/sagemaker/Endpoints/autogluon-endpoint-12-06-2022-10-10-03-EP in account 767907449954 for more information.
</code>```

The CloudWatch log looks like this:

2022-12-06T10:18:53,823 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle - Invoking custom service failed.

2022-12-06T10:18:53,824 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle - Traceback (most recent call last):

2022-12-06T10:18:53,824 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle -   File "/usr/local/lib/python3.8/dist-packages/mms/service.py", line 108, in predict

2022-12-06T10:18:53,825 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle -     ret = self._entry_point(input_batch, self.context)

2022-12-06T10:18:53,825 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle -   File "/usr/local/lib/python3.8/dist-packages/sagemaker_inference/default_handler_service.py", line 50, in handle

2022-12-06T10:18:53,825 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle -     return self._service.transform(data, context)

2022-12-06T10:18:53,825 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle - AttributeError: 'NoneType' object has no attribute 'transform'

Here's the model and endpoint creation code for more information:

```<code>endpoint_name = sagemaker.utils.unique_name_from_base("sagemaker-autogluon-batch_transform-trained-model")

model_data = sess.upload_data(path=os.path.join(".", "model.tar.gz"), key_prefix=f"{endpoint_name}/models")

model_url = model_data

image_uri = image_uris.retrieve(
            "autogluon",
            region=region,
            version='0.4',
            py_version='py38',
            image_scope="inference",
            instance_type='ml.m4.xlarge',)

</code>```
```<code># create a model.

from sagemaker.model_monitor import DataCaptureConfig
from sagemaker.predictor import RealTimePredictor
from sagemaker.predictor import csv_serializer
from datetime import datetime

sm_client = boto3.client('sagemaker')
latest_model = sm_client.list_models(MaxResults=1,
                                                SortBy='CreationTime',
                                                SortOrder='Descending')

CreationTime = datetime.now().strftime(("%m-%d-%Y-%H-%M-%S"))

model_name = 'autogluon-endpoint-' + CreationTime

def create_model(role, model_name, container_uri, model_data):
    return sm_client.create_model(
        ModelName=model_name,
        PrimaryContainer={
        'Image': image_uri,
        'ModelDataUrl': model_url,
        'Environment': {}
        },
        ExecutionRoleArn=role)

try:
    model = create_model(role, model_name, image_uri, model_url)
except Exception as e:
        sm_client.delete_model(ModelName=model_name)
        model = create_model(role, model_name, image_uri, model_url)

#Specify data configuration setting

s3_capture_upload_path = 's3://{}/{}/monitoring/datacapture'.format(rawbucket, prefix)
data_capture_configuration = {
    "EnableCapture": True,
    "InitialSamplingPercentage": 100,
    "DestinationS3Uri": s3_capture_upload_path,
    "CaptureOptions": [
        { "CaptureMode": "Output" },
        { "CaptureMode": "Input" }
    ],
    "CaptureContentTypeHeader": {
       "CsvContentTypes": ["text/csv"],
       "JsonContentTypes": ["application/json"]}}

#Create endpoint configuration

def create_endpoint_config(model_config, data_capture_config):
    return sm_client.create_endpoint_config(
                                                EndpointConfigName=model_config,
                                                ProductionVariants=[
                                                        {
                                                            'VariantName': 'AllTraffic',
                                                            'ModelName': model_config,
                                                            'InitialInstanceCount': 1,
                                                            'InstanceType': 'ml.m4.xlarge',
                                                            'InitialVariantWeight': 1.0,
                                                },

                                                    ],
                                                DataCaptureConfig=data_capture_config
                                                )
try:
    endpoint_config = create_endpoint_config(model_name, data_capture_configuration)
except Exception as e:
    sm_client.delete_endpoint_config(EndpointConfigName=model)
    endpoint_config = create_endpoint_config(model_name, data_capture_configuration)
print('Endpoint configuration created: '+ endpoint_config['EndpointConfigArn'])

#Create endpoint

endpoint_name = model_name + '-EP'
def create_endpoint(endpoint_name, config_name):
    return sm_client.create_endpoint(
                                    EndpointName=endpoint_name,
                                    EndpointConfigName=model_name
                                )
try:
    endpoint = create_endpoint(endpoint_name, endpoint_config)
except Exception as e:
    sm_client.delete_endpoint(EndpointName=endpoint_name)
    endpoint = create_endpoint(endpoint_name, endpoint_config)

print('Endpoint created: '+ endpoint['EndpointArn'])

</code>```

Here is the code that's causing the error:

```<code>
#Sending inference requests to the endpoint

from sagemaker.predictor import RealTimePredictor
from sagemaker.predictor import csv_serializer

predictor = RealTimePredictor(endpoint_name = endpoint_name, content_type = 'text/csv')

with open('test_sample.csv', 'r') as f:
    for row in f:
        payload = row.rstrip('\n')
        response = predictor.predict(data=payload[2:])
        sleep(0.5)
print('done!')
</code>```

I'm clueless as I have no idea what's causing the error, so any help will be much appreciated. Thank you in advance!

Body:
I'm working on a SageMaker AutoGluon prediction model and after performing batch transform and creating the endpoint I've been trying to send inference requests to the endpoint but I keep getting the following error:

ModelError                                Traceback (most recent call last)
<ipython-input-54-47897c53ab79> in <module>
11     for row in f:
12         payload = row.rstrip('\n')
13         response = predictor.predict(data=payload[2:])
14         sleep(0.5)
15 print('done!')

/opt/conda/lib/python3.7/site-packages/sagemaker/predictor.py in predict(self, data, initial_args, target_model, target_variant, inference_id)
159             data, initial_args, target_model, target_variant, inference_id
160         )
161         response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)
162         return self._handle_response(response)
163

/opt/conda/lib/python3.7/site-packages/botocore/client.py in _api_call(self, *args, **kwargs)
528                 )
529             # The "self" in this scope is referring to the BaseClient.
530             return self._make_api_call(operation_name, kwargs)
531
532         _api_call.__name__ = str(py_operation_name)

/opt/conda/lib/python3.7/site-packages/botocore/client.py in _make_api_call(self, operation_name, api_params)
958             error_code = parsed_response.get("Error", {}).get("Code")
959             error_class = self.exceptions.from_code(error_code)
960             raise error_class(parsed_response, operation_name)
961         else:
962             return parsed_response

ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (503) from primary with message "{
  "code": 503,
  "type": "InternalServerException",
  "message": "Prediction failed"
}
See https://ap-south-1.console.aws.amazon.com/cloudwatch/home?region=ap-south-1#logEventViewer:group=/aws/sagemaker/Endpoints/autogluon-endpoint-12-06-2022-10-10-03-EP in account 767907449954 for more information.

The CloudWatch log looks like this:

2022-12-06T10:18:53,823 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle - Invoking custom service failed.

2022-12-06T10:18:53,824 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle - Traceback (most recent call last):

2022-12-06T10:18:53,824 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle -   File "/usr/local/lib/python3.8/dist-packages/mms/service.py", line 108, in predict

2022-12-06T10:18:53,825 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle -     ret = self._entry_point(input_batch, self.context)

2022-12-06T10:18:53,825 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle -   File "/usr/local/lib/python3.8/dist-packages/sagemaker_inference/default_handler_service.py", line 50, in handle

2022-12-06T10:18:53,825 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle -     return self._service.transform(data, context)

2022-12-06T10:18:53,825 [INFO ] W-model-3-stdout com.amazonaws.ml.mms.wlm.WorkerLifeCycle - AttributeError: 'NoneType' object has no attribute 'transform'

Here's the model and endpoint creation code for more information:

endpoint_name = sagemaker.utils.unique_name_from_base("sagemaker-autogluon-batch_transform-trained-model")

model_data = sess.upload_data(path=os.path.join(".", "model.tar.gz"), key_prefix=f"{endpoint_name}/models")

model_url = model_data

image_uri = image_uris.retrieve(
            "autogluon",
            region=region,
            version='0.4',
            py_version='py38',
            image_scope="inference",
            instance_type='ml.m4.xlarge',)

# create a model.

from sagemaker.model_monitor import DataCaptureConfig
from sagemaker.predictor import RealTimePredictor
from sagemaker.predictor import csv_serializer
from datetime import datetime

sm_client = boto3.client('sagemaker')
latest_model = sm_client.list_models(MaxResults=1,
                                                SortBy='CreationTime',
                                                SortOrder='Descending')

CreationTime = datetime.now().strftime(("%m-%d-%Y-%H-%M-%S"))

model_name = 'autogluon-endpoint-' + CreationTime

def create_model(role, model_name, container_uri, model_data):
    return sm_client.create_model(
        ModelName=model_name,
        PrimaryContainer={
        'Image': image_uri,
        'ModelDataUrl': model_url,
        'Environment': {}
        },
        ExecutionRoleArn=role)

try:
    model = create_model(role, model_name, image_uri, model_url)
except Exception as e:
        sm_client.delete_model(ModelName=model_name)
        model = create_model(role, model_name, image_uri, model_url)

#Specify data configuration setting

s3_capture_upload_path = 's3://{}/{}/monitoring/datacapture'.format(rawbucket, prefix)
data_capture_configuration = {
    "EnableCapture": True,
    "InitialSamplingPercentage": 100,
    "DestinationS3Uri": s3_capture_upload_path,
    "CaptureOptions": [
        { "CaptureMode": "Output" },
        { "CaptureMode": "Input" }
    ],
    "CaptureContentTypeHeader": {
       "CsvContentTypes": ["text/csv"],
       "JsonContentTypes": ["application/json"]}}

#Create endpoint configuration

def create_endpoint_config(model_config, data_capture_config):
    return sm_client.create_endpoint_config(
                                                EndpointConfigName=model_config,
                                                ProductionVariants=[
                                                        {
                                                            'VariantName': 'AllTraffic',
                                                            'ModelName': model_config,
                                                            'InitialInstanceCount': 1,
                                                            'InstanceType': 'ml.m4.xlarge',
                                                            'InitialVariantWeight': 1.0,
                                                },

                                                    ],
                                                DataCaptureConfig=data_capture_config
                                                )
try:
    endpoint_config = create_endpoint_config(model_name, data_capture_configuration)
except Exception as e:
    sm_client.delete_endpoint_config(EndpointConfigName=model)
    endpoint_config = create_endpoint_config(model_name, data_capture_configuration)
print('Endpoint configuration created: '+ endpoint_config['EndpointConfigArn'])

#Create endpoint

endpoint_name = model_name + '-EP'
def create_endpoint(endpoint_name, config_name):
    return sm_client.create_endpoint(
                                    EndpointName=endpoint_name,
                                    EndpointConfigName=model_name
                                )
try:
    endpoint = create_endpoint(endpoint_name, endpoint_config)
except Exception as e:
    sm_client.delete_endpoint(EndpointName=endpoint_name)
    endpoint = create_endpoint(endpoint_name, endpoint_config)

print('Endpoint created: '+ endpoint['EndpointArn'])

Here is the code that's causing the error:

#Sending inference requests to the endpoint

from sagemaker.predictor import RealTimePredictor
from sagemaker.predictor import csv_serializer

predictor = RealTimePredictor(endpoint_name = endpoint_name, content_type = 'text/csv')

with open('test_sample.csv', 'r') as f:
    for row in f:
        payload = row.rstrip('\n')
        response = predictor.predict(data=payload[2:])
        sleep(0.5)
print('done!')

I'm clueless as I have no idea what's causing the error, so any help will be much appreciated. Thank you in advance!


来源: stackexchange

问:
How to connect MainWindow and Widget

I have a MainWindow and a Form/widget created through Qt designer(.ui).

-> .ui files are converted to respective .py files.

MainWindow has a Menubar with 'Evaluate' as Action.

On clicking 'Evaluate' i want it to open the Form/widget.

How can i connect them?

MainWindow.py

the Action is triggered as - self.actionEVALUATE_Team.triggered.connect(self.evaluateTeam)

```<code>class Ui_MainWindow(object):
    def evaluateTeam(self):
        from evaluteTeam2 import Ui_Form
        Form = QtWidgets.QWidget()
        ui = Ui_Form()
        ui.setupUi(Form)
        ret = Form.exec()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

evaluteTeam2.py

```<code>class Ui_Form(object):
    def __init__(self):
        self.team= []
        self.pointlist = []
        self.playersList = []
        self.total = 0
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to connect MainWindow and Widget

Body:
I have a MainWindow and a Form/widget created through Qt designer(.ui).

-> .ui files are converted to respective .py files.

MainWindow has a Menubar with 'Evaluate' as Action.

On clicking 'Evaluate' i want it to open the Form/widget.

How can i connect them?

MainWindow.py

the Action is triggered as - self.actionEVALUATE_Team.triggered.connect(self.evaluateTeam)

class Ui_MainWindow(object):
    def evaluateTeam(self):
        from evaluteTeam2 import Ui_Form
        Form = QtWidgets.QWidget()
        ui = Ui_Form()
        ui.setupUi(Form)
        ret = Form.exec()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

evaluteTeam2.py

class Ui_Form(object):
    def __init__(self):
        self.team= []
        self.pointlist = []
        self.playersList = []
        self.total = 0
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())


问:
when i use to import matplotlib.pyplot as plt in jupyter notebook, i am getting an module error
whenever i use to import matplotlib.pyplot in jupyter noteboopk. it shows me module error. whilst there is no problem in pycharm to import this same library.

```<code>---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In [1], line 1
----> 1 import matplotlib.pyplot as plt

File c:\users\welcome\appdata\local\programs\python\python38\lib\site-packages\matplotlib\pyplot.py:2469
   2467     dict.__setitem__(rcParams, "backend", rcsetup._auto_backend_sentinel)
   2468 # Set up the backend.
-> 2469 switch_backend(rcParams["backend"])
   2471 # Just to be safe.  Interactive mode can be turned on without
   2472 # calling `plt.ion()` so register it again here.
   2473 # This is safe because multiple calls to `install_repl_displayhook`
   2474 # are no-ops and the registered function respect `mpl.is_interactive()`
   2475 # to determine if they should trigger a draw.
   2476 install_repl_displayhook()

File c:\users\welcome\appdata\local\programs\python\python38\lib\site-packages\matplotlib\pyplot.py:277, in switch_backend(newbackend)
    270 # Backends are implemented as modules, but "inherit" default method
    271 # implementations from backend_bases._Backend.  This is achieved by
    272 # creating a "class" that inherits from backend_bases._Backend and whose
    273 # body is filled with the module's globals.
    275 backend_name = cbook._backend_module_name(newbackend)
--> 277 class backend_mod(matplotlib.backend_bases._Backend):
    278     locals().update(vars(importlib.import_module(backend_name)))
    280 required_framework = _get_required_interactive_framework(backend_mod)

File c:\users\welcome\appdata\local\programs\python\python38\lib\site-packages\matplotlib\pyplot.py:278, in switch_backend.<locals>.backend_mod()
    277 class backend_mod(matplotlib.backend_bases._Backend):
--> 278     locals().update(vars(importlib.import_module(backend_name)))

File c:\users\welcome\appdata\local\programs\python\python38\lib\importlib\__init__.py:127, in import_module(name, package)
    125             break
    126         level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)

ModuleNotFoundError: No module named 'matplotlib_inline'
</code>```

i am getting this type of output

Body:
whenever i use to import matplotlib.pyplot in jupyter noteboopk. it shows me module error. whilst there is no problem in pycharm to import this same library.

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In [1], line 1
----> 1 import matplotlib.pyplot as plt

File c:\users\welcome\appdata\local\programs\python\python38\lib\site-packages\matplotlib\pyplot.py:2469
   2467     dict.__setitem__(rcParams, "backend", rcsetup._auto_backend_sentinel)
   2468 # Set up the backend.
-> 2469 switch_backend(rcParams["backend"])
   2471 # Just to be safe.  Interactive mode can be turned on without
   2472 # calling `plt.ion()` so register it again here.
   2473 # This is safe because multiple calls to `install_repl_displayhook`
   2474 # are no-ops and the registered function respect `mpl.is_interactive()`
   2475 # to determine if they should trigger a draw.
   2476 install_repl_displayhook()

File c:\users\welcome\appdata\local\programs\python\python38\lib\site-packages\matplotlib\pyplot.py:277, in switch_backend(newbackend)
    270 # Backends are implemented as modules, but "inherit" default method
    271 # implementations from backend_bases._Backend.  This is achieved by
    272 # creating a "class" that inherits from backend_bases._Backend and whose
    273 # body is filled with the module's globals.
    275 backend_name = cbook._backend_module_name(newbackend)
--> 277 class backend_mod(matplotlib.backend_bases._Backend):
    278     locals().update(vars(importlib.import_module(backend_name)))
    280 required_framework = _get_required_interactive_framework(backend_mod)

File c:\users\welcome\appdata\local\programs\python\python38\lib\site-packages\matplotlib\pyplot.py:278, in switch_backend.<locals>.backend_mod()
    277 class backend_mod(matplotlib.backend_bases._Backend):
--> 278     locals().update(vars(importlib.import_module(backend_name)))

File c:\users\welcome\appdata\local\programs\python\python38\lib\importlib\__init__.py:127, in import_module(name, package)
    125             break
    126         level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)

ModuleNotFoundError: No module named 'matplotlib_inline'

i am getting this type of output


问:
update a value by running through every row in a data frame with conditions (another version of extension)
This is a further extension of my previous question update a value by running through every row in a data frame with conditions (extension)

Working with the same data frame that has an added column:

Df:

Index
A
B
A_yes
B_yes
Win/Lose

0
2.43
1.55
1
0
1

1
2.58
1.49
0
1
0

2
1.61
2.32
1
0
1

3
2.7
1.46
1
0
1

Where in the Win/Lose column 1 = win and 0 = lose.

Currently I have this code to generate the following output:

```<code>start = 500
weights = (df["A"].where(df["A_yes"].eq(1), df["B"]) * 0.5 + 0.5).cumprod()
df["Points"] = start * weights
</code>```

Output Df:

Index
A
B
A_yes
B_yes
Points

0
2.43
1.55
1
0
875.5

1
2.58
1.49
0
1
1067.5875

2
1.61
2.32
1
0
1393.2017

3
2.7
1.46
1
0
2557.42324

How can I modify it so that it follows this pattern that now depend on the win/lose column:

Desired new output:

Index
A
B
A_yes
B_yes
Win/Lose
Points

0
2.43
1.55
1
0
1
857.5

1
2.58
1.49
0
1
0
428.75

2
1.61
2.32
1
0
1
707.4375

3
2.7
1.46
1
0
1
1308.75912

Body:
This is a further extension of my previous question update a value by running through every row in a data frame with conditions (extension)

Working with the same data frame that has an added column:

Df:

Index
A
B
A_yes
B_yes
Win/Lose

0
2.43
1.55
1
0
1

1
2.58
1.49
0
1
0

2
1.61
2.32
1
0
1

3
2.7
1.46
1
0
1

Where in the Win/Lose column 1 = win and 0 = lose.

Currently I have this code to generate the following output:

start = 500
weights = (df["A"].where(df["A_yes"].eq(1), df["B"]) * 0.5 + 0.5).cumprod()
df["Points"] = start * weights

Output Df:

Index
A
B
A_yes
B_yes
Points

0
2.43
1.55
1
0
875.5

1
2.58
1.49
0
1
1067.5875

2
1.61
2.32
1
0
1393.2017

3
2.7
1.46
1
0
2557.42324

How can I modify it so that it follows this pattern that now depend on the win/lose column:

Desired new output:

Index
A
B
A_yes
B_yes
Win/Lose
Points

0
2.43
1.55
1
0
1
857.5

1
2.58
1.49
0
1
0
428.75

2
1.61
2.32
1
0
1
707.4375

3
2.7
1.46
1
0
1
1308.75912


问:
VS Code Formatting - only selected features
I use VS Code for my C# code.
Unfortunately, the formatter lets you define many details of your code, especially where spaces should go within a line, a function call, a conditional statement etc., and enforces the whole set of options.

This makes it impossible to intentionally add whitespace for visual orientation, such as :

```<code>        public int                Key    { get; set; } = 0;
        public string             Name   { get; set; } = string.Empty;
        public UnitId             Unit   { get; set; } = UnitId.None;
        public UnderlyingDataType Type   { get; set; } = UnderlyingDataType.UINT32;
        public string             Source { get; set; } = string.Empty;
</code>```

as the formatter will shrink it back at next occasion:

```<code>        public int Key { get; set; } = 0;
        public string Name { get; set; } = string.Empty;
        public UnitId Unit { get; set; } = UnitId.None;
        public UnderlyingDataType Type { get; set; } = UnderlyingDataType.UINT32;
        public string Source { get; set; } = string.Empty;
</code>```

I do wish to use some of the formatter settings, such as 4 spaces for a tab, auto-indentation etc, but would like to set my other whitespace deliberately.

In the settings (Omnisharp), it is only possible to say "true" or "false" to distinct space settings, but they cannot just disabled at all.

Can anyone help?

Alternatively, is it possible to switch off this formatter at all, and use something else to correct indentation (of a selection)? (Eclipse, for instance, has the shortcut Ctrl-i, which does only indentation, but no whitespace correction.)

Body:
I use VS Code for my C# code.
Unfortunately, the formatter lets you define many details of your code, especially where spaces should go within a line, a function call, a conditional statement etc., and enforces the whole set of options.

This makes it impossible to intentionally add whitespace for visual orientation, such as :

        public int                Key    { get; set; } = 0;
        public string             Name   { get; set; } = string.Empty;
        public UnitId             Unit   { get; set; } = UnitId.None;
        public UnderlyingDataType Type   { get; set; } = UnderlyingDataType.UINT32;
        public string             Source { get; set; } = string.Empty;

as the formatter will shrink it back at next occasion:

        public int Key { get; set; } = 0;
        public string Name { get; set; } = string.Empty;
        public UnitId Unit { get; set; } = UnitId.None;
        public UnderlyingDataType Type { get; set; } = UnderlyingDataType.UINT32;
        public string Source { get; set; } = string.Empty;

I do wish to use some of the formatter settings, such as 4 spaces for a tab, auto-indentation etc, but would like to set my other whitespace deliberately.

In the settings (Omnisharp), it is only possible to say "true" or "false" to distinct space settings, but they cannot just disabled at all.

Can anyone help?

Alternatively, is it possible to switch off this formatter at all, and use something else to correct indentation (of a selection)? (Eclipse, for instance, has the shortcut Ctrl-i, which does only indentation, but no whitespace correction.)


问:
Routing elasticsearch field in terraform
For example in logstash I have next config in output

```<code> if [@metadata][kafka][topic] == "cash-box-dynamic" {
    elasticsearch {
            hosts => ["elasticsearch:9200"]
            index => "cash-boxes"
            document_id => "dynamic_%{[joinField][parent]}"
            routing => "%{[joinField][parent]}"
            template => "/local/template/backend_logstash_cash_boxes_template.json"
            template_name => "cash-box"
            manage_template => true
            template_overwrite => true
        }
    }
</code>```

And data in my index need to looks like this

```<code>{
        "_index" : "cash-box-dynamic",
        "_type" : "_doc",
        "_id" : "dynamic_1601260015",
        "_score" : 0.6931471,
        "_routing" : "1601260015",
        "_source" : {
          "cashRegisterFactoryNumber": "100",
          "deviceFactoryNumber": "200",
          "timeDelta" : 330,
          "joinField" : {
            "name" : "dynamic",
            "parent" : "1601260015"
          },
          "status" : "REGISTRATION",
        }
}
</code>```

I depreceted logstash and use kafka stream + elasticsearch sink connector + terraform (for rest api in kafka-connector and elasticsearch).

I use to this kafka connect image https://hub.docker.com/layers/confluentinc/cp-kafka-connect/5.4.10/images/sha256-e09d5b21f8717198f9873fd42b44c19881c7d16237d099f8d6db5256b6b6db3c?context=explore

And this elasticsearch sink connector enter link description here ver. 14.0.2

Sink connector read from topics

```<code>"cash-box-dynamic", "cash-box-aggregate"
</code>```

And put data from topics into eponymous indexes by terraform

```<code>resource "kafka-connect_connector" "cash_box_dynamic" {
  name = "cash_box_dynamic"
  config = {
    "connector.class"                                 = "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector"
    "tasks.max"                                       = var.cash_box_dynamic_tasks_max
    "topics"                                          = "cash-box-dynamic"
    "key.ignore"                                      = "false"
    "schema.ignore"                                   = "true"
    "connection.url"                                  = var.elasticsearch_url
    "type.name"                                       = "_doc"
    "name"                                            = "cash_box_dynamic"
    "key.converter"                                   = "org.apache.kafka.connect.storage.StringConverter"
    "value.converter"                                 = "org.apache.kafka.connect.json.JsonConverter"
    "value.converter.schemas.enable"                  = "false"
    "flush.synchronously"                             = "true"
  }
}
</code>```

I configured terraform index template for aliases cash-boxes like this

```<code>resource "elasticstack_elasticsearch_index_template" "cash_boxes_backend" {
  name     = "cash-boxes-backend"
  priority = 10

  index_patterns = ["cash-box-dynamic", "cash-box-aggregate"]

  template {
    settings = jsonencode({
      number_of_shards       = "1"
    })
    alias {
      name = "cash-boxes"
    }
    mappings = file("/app/terraform-module-gs-connectors/files/backend_logstash_cash_boxes_template.json")
  }
  version = 1
}
</code>```

and have next index pattern for index alias cash-boxes
backend_logstash_cash_boxes_template.json

```<code>{
  "properties": {
    "cashRegisterFactoryNumber": {
      "type": "keyword"
    },
    "deviceFactoryNumber": {
      "type": "keyword"
    },
    "status": {
      "type": "keyword"
    },
    "timeDelta": {
      "type": "long"
    },
    "joinField": {
      "type": "join",
      "relations": {
        "static": "dynamic"
      }
    }
  }
}
</code>```

The problem is that according to documentation https://www.elastic.co/guide/en/elasticsearch/reference/current/parent-join.html
I have to use in join field routing field (important that it's need to be custom like in the logstash config). But how I can do this in the terraform or maybe in elasticsearch sink connector?

Body:
For example in logstash I have next config in output

 if [@metadata][kafka][topic] == "cash-box-dynamic" {
    elasticsearch {
            hosts => ["elasticsearch:9200"]
            index => "cash-boxes"
            document_id => "dynamic_%{[joinField][parent]}"
            routing => "%{[joinField][parent]}"
            template => "/local/template/backend_logstash_cash_boxes_template.json"
            template_name => "cash-box"
            manage_template => true
            template_overwrite => true
        }
    }

And data in my index need to looks like this

{
        "_index" : "cash-box-dynamic",
        "_type" : "_doc",
        "_id" : "dynamic_1601260015",
        "_score" : 0.6931471,
        "_routing" : "1601260015",
        "_source" : {
          "cashRegisterFactoryNumber": "100",
          "deviceFactoryNumber": "200",
          "timeDelta" : 330,
          "joinField" : {
            "name" : "dynamic",
            "parent" : "1601260015"
          },
          "status" : "REGISTRATION",
        }
}

I depreceted logstash and use kafka stream + elasticsearch sink connector + terraform (for rest api in kafka-connector and elasticsearch).

I use to this kafka connect image https://hub.docker.com/layers/confluentinc/cp-kafka-connect/5.4.10/images/sha256-e09d5b21f8717198f9873fd42b44c19881c7d16237d099f8d6db5256b6b6db3c?context=explore

And this elasticsearch sink connector enter link description here ver. 14.0.2

Sink connector read from topics

"cash-box-dynamic", "cash-box-aggregate"

And put data from topics into eponymous indexes by terraform

resource "kafka-connect_connector" "cash_box_dynamic" {
  name = "cash_box_dynamic"
  config = {
    "connector.class"                                 = "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector"
    "tasks.max"                                       = var.cash_box_dynamic_tasks_max
    "topics"                                          = "cash-box-dynamic"
    "key.ignore"                                      = "false"
    "schema.ignore"                                   = "true"
    "connection.url"                                  = var.elasticsearch_url
    "type.name"                                       = "_doc"
    "name"                                            = "cash_box_dynamic"
    "key.converter"                                   = "org.apache.kafka.connect.storage.StringConverter"
    "value.converter"                                 = "org.apache.kafka.connect.json.JsonConverter"
    "value.converter.schemas.enable"                  = "false"
    "flush.synchronously"                             = "true"
  }
}

I configured terraform index template for aliases cash-boxes like this

resource "elasticstack_elasticsearch_index_template" "cash_boxes_backend" {
  name     = "cash-boxes-backend"
  priority = 10

  index_patterns = ["cash-box-dynamic", "cash-box-aggregate"]

  template {
    settings = jsonencode({
      number_of_shards       = "1"
    })
    alias {
      name = "cash-boxes"
    }
    mappings = file("/app/terraform-module-gs-connectors/files/backend_logstash_cash_boxes_template.json")
  }
  version = 1
}

and have next index pattern for index alias cash-boxes
backend_logstash_cash_boxes_template.json

{
  "properties": {
    "cashRegisterFactoryNumber": {
      "type": "keyword"
    },
    "deviceFactoryNumber": {
      "type": "keyword"
    },
    "status": {
      "type": "keyword"
    },
    "timeDelta": {
      "type": "long"
    },
    "joinField": {
      "type": "join",
      "relations": {
        "static": "dynamic"
      }
    }
  }
}

The problem is that according to documentation https://www.elastic.co/guide/en/elasticsearch/reference/current/parent-join.html
I have to use in join field routing field (important that it's need to be custom like in the logstash config). But how I can do this in the terraform or maybe in elasticsearch sink connector?


问:
How can I find out roughly how many users my Flask API on Heroku can handle?
I am running a Python Flask API on a Heroku Hobby Dev tier, and set the workers to 10. I believe this means 10 instances of the API are running simultaneously so it can accept requests 10 times than a single worker can, correct me if I'm wrong.

How can I find out roughly how many users this API can handle? Say a standard request takes 500ms~ to complete per request, and a single user may send requests from 1 every 5 seconds, to 10 every 10 seconds (if they're scrolling through an image gallery).

If I am to release an application that will garner thousands of users, how can I assess if the API can handle it and be reasonably fast? And if it can't, what do I do with Heroku to be able to handle more concurrent users?


问:
sqlalchemy different behaviour on different table in same schema
I am connecting to clickHouse database by means of sqlalchemy. ne table is okay but another one acts weird.

When I print querystatement, the table name is loaded twice in it! Can anyone helps me to find out why two different tables might act differently .
My code :

```<code>session.query(className)
</code>```

query.statement:

```<code>select a,b from table_name, table_name
</code>```

Body:
I am connecting to clickHouse database by means of sqlalchemy. ne table is okay but another one acts weird.

When I print querystatement, the table name is loaded twice in it! Can anyone helps me to find out why two different tables might act differently .
My code :

session.query(className)

query.statement:

select a,b from table_name, table_name


问:
How to get a client token generator for postman api
How to get a client token generator for postman for API testing

How to get a client token generator for postman for API testing


问:
Trying to index an array based on a variable. But when it's zero, nothing happens
I'm trying to access my "state" array based on the 9th digit of the "CPF" Variable. When the 9th digit is ZERO, nothing is printed. Otherwise, it works fine.

```<code>#include <stdio.h>
#include <string.h>

int main(void){
    char state[10][100] = {"Rio Grande do Sul", "Distrito Federal, Goias, Mato Grosso, Mato Grosso do Sul ou Tocantins", "Amazonas, Para, Roraima, Amapa, Acre ou Rondonia", "Ceara, Maranhao e Piaui", "Paraiba, Pernambuco, Alagoas ou Rio Grande do Norte", "Bahia ou Sergipe", "Minas Gerais", "Rio de Janeiro ou Espirito Santo", "Sao Paulo", "Parana ou Santa Catarina"};

    char cpf[11];
    printf("Enter a CPF: ");
    scanf("%s", cpf);
    int digit = (int)(cpf[8])-48;

    printf("STATE: %s",state[digit]);
    return 0;

}
</code>```

The digit value will tell me the state that the person lives. After turning the 9th digit of cpf into int, I subtracted 48 because of the ascii table (0-9)

Example of states:

state[0]= Rio Grande do Sul <-- Nothing shows

state[1]= Distrito Federal, Goias, Mato Grosso, Mato Grosso do Sul ou Tocantins <-- Ok

...

state[9]= Parana ou Santa Catarina

Example of inputs and outputs:

CPF = 00000000100

Distrito Federal, Goias, Mato Grosso, Mato Grosso do Sul ou Tocantins

CPF = 00000000900

Parana ou Santa Catarina

CPF = 00000000000

Body:
I'm trying to access my "state" array based on the 9th digit of the "CPF" Variable. When the 9th digit is ZERO, nothing is printed. Otherwise, it works fine.

#include <stdio.h>
#include <string.h>

int main(void){
    char state[10][100] = {"Rio Grande do Sul", "Distrito Federal, Goias, Mato Grosso, Mato Grosso do Sul ou Tocantins", "Amazonas, Para, Roraima, Amapa, Acre ou Rondonia", "Ceara, Maranhao e Piaui", "Paraiba, Pernambuco, Alagoas ou Rio Grande do Norte", "Bahia ou Sergipe", "Minas Gerais", "Rio de Janeiro ou Espirito Santo", "Sao Paulo", "Parana ou Santa Catarina"};

    char cpf[11];
    printf("Enter a CPF: ");
    scanf("%s", cpf);
    int digit = (int)(cpf[8])-48;

    printf("STATE: %s",state[digit]);
    return 0;

}

The digit value will tell me the state that the person lives. After turning the 9th digit of cpf into int, I subtracted 48 because of the ascii table (0-9)

Example of states:

state[0]= Rio Grande do Sul <-- Nothing shows

state[1]= Distrito Federal, Goias, Mato Grosso, Mato Grosso do Sul ou Tocantins <-- Ok

...

state[9]= Parana ou Santa Catarina

Example of inputs and outputs:

CPF = 00000000100

Distrito Federal, Goias, Mato Grosso, Mato Grosso do Sul ou Tocantins

CPF = 00000000900

Parana ou Santa Catarina

CPF = 00000000000


问:
Add a ".csv" extension to a file's name or path
Is there a recommended way to add a ".csv" extension, to a file's name or path, which you want to export as a csv?

I achieved it directly and naively, and I wonder if there is another way to make it more elegant.

My code:

```<code>def get_file_path (csv_name, file_path, file_type = ".csv"):

    cwd = os.getcwd()
    file_path = os.path.join(cwd, csv_name + file_type)

    return file_path
</code>```

Body:
Is there a recommended way to add a ".csv" extension, to a file's name or path, which you want to export as a csv?

I achieved it directly and naively, and I wonder if there is another way to make it more elegant.

My code:

def get_file_path (csv_name, file_path, file_type = ".csv"):

    cwd = os.getcwd()
    file_path = os.path.join(cwd, csv_name + file_type)

    return file_path


问:
how to split a set with duplicate data into several groups?
I say I have a data array like [500,500,520,520,520,535,535...],I wanna split the array into several groups so that the sum of each group is between 3000 and 3100(it's ok if a set or two do not qualify), and more importantly, the result groups can be clustered into several clusters and the groups in the same cluster are very similar and the groups in different group are really different from each other.The less the number of clusters, the better the result is.

For example, group A:[500,520,535,700,800],group B:[500,520,535,720,800]. These the sums of two group are both between 3000 and 3100, and they are very similar to each other and can be cluster to the same group because of the similarity between them.
If possible,we should avoid putting the same number more than once in the same group to reduce the number of clusters.

would anyone give me an idea or direction or some keywords how to solve such problem? any help would be appreciated.


问:
need to create attendance sheet with present and absent for the below model
```<code>var attendanceManagementSchema = mongoose.Schema({
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
    loginDateTime: Date,
    loggedoutDatetime: Date,
    loginLocation: { type: String },
    logoutLocation: { type: String },
    createdAt: { type: Date, required: true, default: Date.now }
});

module.exports = mongoose.model('attendanceManagement', attendanceManagementSchema);
</code>```

expecting output to display
enter image description here

Body:
var attendanceManagementSchema = mongoose.Schema({
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
    loginDateTime: Date,
    loggedoutDatetime: Date,
    loginLocation: { type: String },
    logoutLocation: { type: String },
    createdAt: { type: Date, required: true, default: Date.now }
});

module.exports = mongoose.model('attendanceManagement', attendanceManagementSchema);

expecting output to display
enter image description here


问:
Python - Adding SEM to px.box (plotly express box plot)
this is my graph:

This is how I created it:

```<code>fig = px.box(data_comb,
             x='task_level',
             y='value',
             color='task_level',
             title = title+"<br><sup>"+stitle+"</sup>",)
fig.update_traces(boxpoints=False)
fig.show()
</code>```

I want to add SEM (standard error of means) lines instead of the automatic whisker lines that represent min and max values.

Any idea how can I do it? is it possible to do it with plotly express?

I tried looking online but couldn't find anything...

Body:
this is my graph:

This is how I created it:

fig = px.box(data_comb,
             x='task_level',
             y='value',
             color='task_level',
             title = title+"
"+stitle+"",)
fig.update_traces(boxpoints=False)
fig.show()

I want to add SEM (standard error of means) lines instead of the automatic whisker lines that represent min and max values.

Any idea how can I do it? is it possible to do it with plotly express?

I tried looking online but couldn't find anything...


问:
HKHealthStore enableBackgroundDelivery when screen is locked never works
I am trying to create an app, that is connected to HealthKit and once there is a workout finished, I'd love to upload some of it's aggregated properties to our serves.

```<code>    let sampleType =  HKObjectType.workoutType()

    //1. Enable background delivery for workouts
    self.healthStore.enableBackgroundDelivery(for: sampleType, frequency: .immediate) { (success, error) in
        if let unwrappedError = error {
            print("could not enable background delivery: \(unwrappedError)")
        }
        if success {
            print("background delivery enabled")
        }
    }

    //2.  open observer query
    let query = HKObserverQuery(sampleType: sampleType, predicate: HealthKitService.compoundPredicate) { (query, completionHandler, error) in

        self.updateWorkouts() {
            completionHandler()
        }

    }
    healthStore.execute(query)
</code>```

This piece of code from AppDelegate works perfectly and gets called right after I finish the workout on my AppleWatch, but only in these cases:

the state of app does not matter. It works on killed, running or backgrounded app

it works when iPhone is unlocked

it never gets called on locked iPhone

My question is. Is this an Apple security feature?

Apple HealthKit docs say nothing about it, but I found similar question from 2015 here on stackoverflow that says so, but without any reference.

Have you faced the same situation? It is pretty important for me to upload the data immediately after the workout ends.

I have enabled Background delivery under HealthKit capabilities, but I haven't enabled any other Background modes.

Body:
I am trying to create an app, that is connected to HealthKit and once there is a workout finished, I'd love to upload some of it's aggregated properties to our serves.

    let sampleType =  HKObjectType.workoutType()

    //1. Enable background delivery for workouts
    self.healthStore.enableBackgroundDelivery(for: sampleType, frequency: .immediate) { (success, error) in
        if let unwrappedError = error {
            print("could not enable background delivery: \(unwrappedError)")
        }
        if success {
            print("background delivery enabled")
        }
    }

    //2.  open observer query
    let query = HKObserverQuery(sampleType: sampleType, predicate: HealthKitService.compoundPredicate) { (query, completionHandler, error) in

        self.updateWorkouts() {
            completionHandler()
        }

    }
    healthStore.execute(query)

This piece of code from AppDelegate works perfectly and gets called right after I finish the workout on my AppleWatch, but only in these cases:

the state of app does not matter. It works on killed, running or backgrounded app

it works when iPhone is unlocked

it never gets called on locked iPhone

My question is. Is this an Apple security feature?

Apple HealthKit docs say nothing about it, but I found similar question from 2015 here on stackoverflow that says so, but without any reference.

Have you faced the same situation? It is pretty important for me to upload the data immediately after the workout ends.

I have enabled Background delivery under HealthKit capabilities, but I haven't enabled any other Background modes.


问:
Slack Bolt.js Slash Commands open a new url
Is it possible to open a url link with a slash command in bolt framework in javascript?

I tried with a button but i want that when i type the slash command a new tab open with a url


问:
How to use Keras model.predict function with split inputs
I am trying to run Keras model.predict function for my Keras model which takes two sepearate set of inputs. 21 for one layer and 7 inputs for the concatenated layer. My data is stored in a numpy array. So I am trying to use the predict function like this. Here is the code:

```<code>input1 = np.array([])
input2 = np.array([])
for i in trainX[0,:21]:
  np.append(input1,i)
for i in trainX[0,21:]:
  np.append(input2,i)
# inputs = np.array([input1,input2])
q = model.predict(input1,input2)
</code>```

But I keep getting this error:

```<code>ValueError                                Traceback (most recent call last)

<ipython-input-53-ea6beb48f560> in <module>
     11   np.append(input2,i)
     12 # inputs = np.array([input1,input2])
---> 13 q = model_without_average.predict(input1,input2)
     14 # q = model.predict( np.array( [trainX[0,:21],trainX[0,21:]] ))
     15 # print(q)

1 frames

/usr/local/lib/python3.8/dist-packages/keras/engine/training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
   2046             callbacks.on_predict_batch_end(end_step, {'outputs': batch_outputs})
   2047       if batch_outputs is None:
-> 2048         raise ValueError('Unexpected result of `predict_function` '
   2049                          '(Empty batch_outputs). Please use '
   2050                          '`Model.compile(..., run_eagerly=True)`, or '

ValueError: Unexpected result of `predict_function` (Empty batch_outputs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.
</code>```

Can anyone tell me how to resolve this error ?

Body:
I am trying to run Keras model.predict function for my Keras model which takes two sepearate set of inputs. 21 for one layer and 7 inputs for the concatenated layer. My data is stored in a numpy array. So I am trying to use the predict function like this. Here is the code:

input1 = np.array([])
input2 = np.array([])
for i in trainX[0,:21]:
  np.append(input1,i)
for i in trainX[0,21:]:
  np.append(input2,i)
# inputs = np.array([input1,input2])
q = model.predict(input1,input2)

But I keep getting this error:

ValueError                                Traceback (most recent call last)

<ipython-input-53-ea6beb48f560> in <module>
     11   np.append(input2,i)
     12 # inputs = np.array([input1,input2])
---> 13 q = model_without_average.predict(input1,input2)
     14 # q = model.predict( np.array( [trainX[0,:21],trainX[0,21:]] ))
     15 # print(q)

1 frames

/usr/local/lib/python3.8/dist-packages/keras/engine/training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
   2046             callbacks.on_predict_batch_end(end_step, {'outputs': batch_outputs})
   2047       if batch_outputs is None:
-> 2048         raise ValueError('Unexpected result of `predict_function` '
   2049                          '(Empty batch_outputs). Please use '
   2050                          '`Model.compile(..., run_eagerly=True)`, or '

ValueError: Unexpected result of `predict_function` (Empty batch_outputs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

Can anyone tell me how to resolve this error ?


问:
How to style content in Microsoft Teams Deeplink?
I just try to create an angular which generates a deep link to open the ms teams wizard prefilled with values.
The offical docu by outlook yields the following format should fit for such a case:

https://teams.microsoft.com/l/meeting/new?subject=<meeting subject>&startTime=<date>&endTime=<date>&content=<content>&attendees=<user1>,<user2>,<user3>,...

However, I am wondering if I can format the content to be like

Dear xy,
this meeting serves the purpose...

I just tried to insert the content as string using \n and url encodings but all attempts to show a line break in teams does fail.

https://teams.microsoft.com/l/meeting/new?subject=test%20subject&attendees=joe@contoso.com,bob@contoso.com&startTime=10%2F24%2F2018%2010%3A30%3A00&endTime=10%2F24%2F2018%2010%3A30%3A00&content=test%0Acontent


问:
How can I add an Iconbutton inside mapbox-gl popup?
I want to add iconbutton inside popup. and copy popup content clicking that button. here is my code snippet.</p>
```<code>if (onClick) {
  const popup = new AnimatedPopup({
    closeButton: false,
    maxWidth: 'auto',
    openingAnimation: {
      duration: 400,
      easing: 'easeInOutQuint',
      transform: 'scale',
    },
    closingAnimation: {
      duration: 15,
      easing: 'easeInBack',
      transform: 'scale',
    },
  });
</code>```

Body:
I want to add iconbutton inside popup. and copy popup content clicking that button. here is my code snippet.

if (onClick) {
  const popup = new AnimatedPopup({
    closeButton: false,
    maxWidth: 'auto',
    openingAnimation: {
      duration: 400,
      easing: 'easeInOutQuint',
      transform: 'scale',
    },
    closingAnimation: {
      duration: 15,
      easing: 'easeInBack',
      transform: 'scale',
    },
  });


问:
how to get data in fragment from room database in Android using java
get data in fragment from room database how to get please any one tell me

i create a room database in android and add some fragments but dont know how to get data from room in fragment and data is in recyclerview formate


问:
Google OAuth OOB Migration
I am running a NodeJS application that uses googleapis library for multiple purposes using a Desktop Client OAuth Credentials created before 28th Feb 2022 to generate the access token. Currently due to Google removing OOB authorization flow, I have changed the redirect_uri from urn:ietf:wg:oauth:2.0:oob to http://127.0.0.1, in order to retrieve the AUTH Code. Is it the correct way to fix the problem ? and does it affect refreshing the token handled automatically by the googleapis library?</p>

Title: Google OAuth OOB Migration


问:
Cosmos Db Emulator cert fails in Azure pipeline
I'm running integrations tests within my Azure pipeline through the use of docker compose.

As part of this I'm spinning up a Linux cosmos Db emulator, and then running
update-ca-certificates --fresh
in order to allow SSL connections to cosmos from other containers within my test environment (as per the instructions here: https://learn.microsoft.com/en-us/azure/cosmos-db/docker-emulator-linux?tabs=sql-api%2Cssl-netstd21).

This works every time when running these tests locally, but when running on an Azure hosted agent (I've tried ubuntu 18.04, 20.04 and 22.04) I'm finding the trusting of the certs failing randomly - sometimes works fine, other times I receive the warning rehash: warning: skipping emulatorcert.pem,it does not contain exactly one certificate or CRL, which ultimately results in SSL exceptions and the tests failing to run.

Does anyone know a way to resolve this?

I'd found the following alpine issue which seems similar, but haven't had any success trying any of the proposed solutions in the thread: https://github.com/gliderlabs/docker-alpine/issues/30


问:
IllegalAccessError in custom ElasticSearch FieldMapper plugin
I am currently updating my ElasticSearch FieldMapper plugin for accepting a TokenStream in JSON format to ES version 7.17.
I copied most of it from the TextFieldPlugin because the Preanalyzed format is meant to contain longer text, but completely preanalyzed as a TokenStream.

All tests work fine. However, when I deploy the plugin in an ElasticSearch server, I get an IllegalAccessException when trying to create an index that contains a preanalyzed field, thus, engages the PreanalyzedFieldMapper:

```<code>java.lang.IllegalAccessError: class org.elasticsearch.index.mapper.PreanalyzedFieldMapper tried to access protected method 'void org.elasticsearch.index.mapper.FieldMapper$Parameter.toXContent(org.elasticsearch.xcontent.XContentBuilder, boolean)' (org.elasticsearch.index.mapper.PreanalyzedFieldMapper is in unnamed module of loader java.net.FactoryURLClassLoader @652b3733; org.elasticsearch.index.mapper.FieldMapper$Parameter is in unnamed module of loader 'app')
    at org.elasticsearch.index.mapper.PreanalyzedFieldMapper.doXContentBody(PreanalyzedFieldMapper.java:1255)
    at org.elasticsearch.index.mapper.FieldMapper.toXContent(FieldMapper.java:434)
    at org.elasticsearch.index.mapper.ObjectMapper.serializeMappers(ObjectMapper.java:431)
    at org.elasticsearch.index.mapper.ObjectMapper.toXContent(ObjectMapper.java:416)
    at org.elasticsearch.index.mapper.ObjectMapper.toXContent(ObjectMapper.java:394)
    at org.elasticsearch.index.mapper.ObjectMapper.serializeMappers(ObjectMapper.java:431)
    at org.elasticsearch.index.mapper.ObjectMapper.toXContent(ObjectMapper.java:416)
    at org.elasticsearch.index.mapper.Mapping.toXContent(Mapping.java:176)
    at org.elasticsearch.common.compress.CompressedXContent.<init>(CompressedXContent.java:96)
    at org.elasticsearch.index.mapper.Mapping.toCompressedXContent(Mapping.java:77)
    at org.elasticsearch.index.mapper.DocumentMapper.<init>(DocumentMapper.java:35)
    at org.elasticsearch.index.mapper.MapperService.newDocumentMapper(MapperService.java:460)
    at org.elasticsearch.index.mapper.MapperService.applyMappings(MapperService.java:440)
    at org.elasticsearch.index.mapper.MapperService.mergeAndApplyMappings(MapperService.java:421)
    at org.elasticsearch.index.mapper.MapperService.merge(MapperService.java:402)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.updateIndexMappingsAndBuildSortOrder(MetadataCreateIndexService.java:1303)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.lambda$applyCreateIndexWithTemporaryService$3(MetadataCreateIndexService.java:453)
    at org.elasticsearch.indices.IndicesService.withTempIndexService(IndicesService.java:673)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.applyCreateIndexWithTemporaryService(MetadataCreateIndexService.java:451)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.applyCreateIndexRequestWithV1Templates(MetadataCreateIndexService.java:567)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.applyCreateIndexRequest(MetadataCreateIndexService.java:413)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.applyCreateIndexRequest(MetadataCreateIndexService.java:420)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService$1.execute(MetadataCreateIndexService.java:319)
    at org.elasticsearch.cluster.ClusterStateUpdateTask.execute(ClusterStateUpdateTask.java:51)
    at org.elasticsearch.cluster.service.MasterService.executeTasks(MasterService.java:840)
    at org.elasticsearch.cluster.service.MasterService.calculateTaskOutputs(MasterService.java:407)
    at org.elasticsearch.cluster.service.MasterService.runTasks(MasterService.java:243)
    at org.elasticsearch.cluster.service.MasterService.access$100(MasterService.java:63)
    at org.elasticsearch.cluster.service.MasterService$Batcher.run(MasterService.java:170)
    at org.elasticsearch.cluster.service.TaskBatcher.runIfNotProcessed(TaskBatcher.java:146)
    at org.elasticsearch.cluster.service.TaskBatcher$BatchedTask.run(TaskBatcher.java:202)
    at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:718)
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.runAndClean(PrioritizedEsThreadPoolExecutor.java:262)
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.run(PrioritizedEsThreadPoolExecutor.java:225)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
    at java.base/java.lang.Thread.run(Thread.java:1589)
    Suppressed: java.lang.IllegalStateException: Failed to close the XContentBuilder
        at org.elasticsearch.xcontent.XContentBuilder.close(XContentBuilder.java:1131)
        at org.elasticsearch.common.compress.CompressedXContent.<init>(CompressedXContent.java:92)
        ... 28 more
    Caused by: java.io.IOException: Unclosed object or array found
        at org.elasticsearch.xcontent.json.JsonXContentGenerator.close(JsonXContentGenerator.java:456)
        at org.elasticsearch.xcontent.XContentBuilder.close(XContentBuilder.java:1129)
        ... 29 more
</code>```

The issue seems to be that my method doXContentBody() - which is really copied from the TextFieldMapper - tries to serialize its Parameter objects that are instances of an inner class in the mapper super class FieldMapper and have the protected method toXContent that is called in "my" method to serialize the whole mapper with its parameters.

Now I know why this doesn't work: My plugin lies in its own JAR file apart from the ElasticSearch core JARs and is loaded with another class loader. Thus, it does not have access to the protected fields and methods of the inner classes of its super class (Parameter is an inner class of FieldMapper).

My basic question here is: How is this meant to work? I tried to check out other ES Mapping Plugins but they just don't implement the doXContentBody() method. I am unclear about the consequences about implementing or not implementing it and so I am at a loss here. Must I implement it? How could I do it without access to the toXContent() method of the FieldMapper.Parameter class? What happens if I don't implement it?

My plugin code and the specific method can be found here: https://github.com/JULIELab/elasticsearch-mapper-preanalyzed/blob/86bd2b5cf9f3020231603ed5cc7bfcdb3feb6669/src/main/java/org/elasticsearch/index/mapper/PreanalyzedFieldMapper.java#L1241

As I said, it's in large parts a copy of ElasticSearch's TextFieldMapper class since it should behave like it. Perhaps that is an error to begin with. But in previous ES versions that worked fine. This issue with the protected parameter method is new to me.

Body:
I am currently updating my ElasticSearch FieldMapper plugin for accepting a TokenStream in JSON format to ES version 7.17.
I copied most of it from the TextFieldPlugin because the Preanalyzed format is meant to contain longer text, but completely preanalyzed as a TokenStream.

All tests work fine. However, when I deploy the plugin in an ElasticSearch server, I get an IllegalAccessException when trying to create an index that contains a preanalyzed field, thus, engages the PreanalyzedFieldMapper:

java.lang.IllegalAccessError: class org.elasticsearch.index.mapper.PreanalyzedFieldMapper tried to access protected method 'void org.elasticsearch.index.mapper.FieldMapper$Parameter.toXContent(org.elasticsearch.xcontent.XContentBuilder, boolean)' (org.elasticsearch.index.mapper.PreanalyzedFieldMapper is in unnamed module of loader java.net.FactoryURLClassLoader @652b3733; org.elasticsearch.index.mapper.FieldMapper$Parameter is in unnamed module of loader 'app')
    at org.elasticsearch.index.mapper.PreanalyzedFieldMapper.doXContentBody(PreanalyzedFieldMapper.java:1255)
    at org.elasticsearch.index.mapper.FieldMapper.toXContent(FieldMapper.java:434)
    at org.elasticsearch.index.mapper.ObjectMapper.serializeMappers(ObjectMapper.java:431)
    at org.elasticsearch.index.mapper.ObjectMapper.toXContent(ObjectMapper.java:416)
    at org.elasticsearch.index.mapper.ObjectMapper.toXContent(ObjectMapper.java:394)
    at org.elasticsearch.index.mapper.ObjectMapper.serializeMappers(ObjectMapper.java:431)
    at org.elasticsearch.index.mapper.ObjectMapper.toXContent(ObjectMapper.java:416)
    at org.elasticsearch.index.mapper.Mapping.toXContent(Mapping.java:176)
    at org.elasticsearch.common.compress.CompressedXContent.<init>(CompressedXContent.java:96)
    at org.elasticsearch.index.mapper.Mapping.toCompressedXContent(Mapping.java:77)
    at org.elasticsearch.index.mapper.DocumentMapper.<init>(DocumentMapper.java:35)
    at org.elasticsearch.index.mapper.MapperService.newDocumentMapper(MapperService.java:460)
    at org.elasticsearch.index.mapper.MapperService.applyMappings(MapperService.java:440)
    at org.elasticsearch.index.mapper.MapperService.mergeAndApplyMappings(MapperService.java:421)
    at org.elasticsearch.index.mapper.MapperService.merge(MapperService.java:402)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.updateIndexMappingsAndBuildSortOrder(MetadataCreateIndexService.java:1303)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.lambda$applyCreateIndexWithTemporaryService$3(MetadataCreateIndexService.java:453)
    at org.elasticsearch.indices.IndicesService.withTempIndexService(IndicesService.java:673)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.applyCreateIndexWithTemporaryService(MetadataCreateIndexService.java:451)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.applyCreateIndexRequestWithV1Templates(MetadataCreateIndexService.java:567)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.applyCreateIndexRequest(MetadataCreateIndexService.java:413)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService.applyCreateIndexRequest(MetadataCreateIndexService.java:420)
    at org.elasticsearch.cluster.metadata.MetadataCreateIndexService$1.execute(MetadataCreateIndexService.java:319)
    at org.elasticsearch.cluster.ClusterStateUpdateTask.execute(ClusterStateUpdateTask.java:51)
    at org.elasticsearch.cluster.service.MasterService.executeTasks(MasterService.java:840)
    at org.elasticsearch.cluster.service.MasterService.calculateTaskOutputs(MasterService.java:407)
    at org.elasticsearch.cluster.service.MasterService.runTasks(MasterService.java:243)
    at org.elasticsearch.cluster.service.MasterService.access$100(MasterService.java:63)
    at org.elasticsearch.cluster.service.MasterService$Batcher.run(MasterService.java:170)
    at org.elasticsearch.cluster.service.TaskBatcher.runIfNotProcessed(TaskBatcher.java:146)
    at org.elasticsearch.cluster.service.TaskBatcher$BatchedTask.run(TaskBatcher.java:202)
    at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:718)
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.runAndClean(PrioritizedEsThreadPoolExecutor.java:262)
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.run(PrioritizedEsThreadPoolExecutor.java:225)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
    at java.base/java.lang.Thread.run(Thread.java:1589)
    Suppressed: java.lang.IllegalStateException: Failed to close the XContentBuilder
        at org.elasticsearch.xcontent.XContentBuilder.close(XContentBuilder.java:1131)
        at org.elasticsearch.common.compress.CompressedXContent.<init>(CompressedXContent.java:92)
        ... 28 more
    Caused by: java.io.IOException: Unclosed object or array found
        at org.elasticsearch.xcontent.json.JsonXContentGenerator.close(JsonXContentGenerator.java:456)
        at org.elasticsearch.xcontent.XContentBuilder.close(XContentBuilder.java:1129)
        ... 29 more

The issue seems to be that my method doXContentBody() - which is really copied from the TextFieldMapper - tries to serialize its Parameter objects that are instances of an inner class in the mapper super class FieldMapper and have the protected method toXContent that is called in "my" method to serialize the whole mapper with its parameters.

Now I know why this doesn't work: My plugin lies in its own JAR file apart from the ElasticSearch core JARs and is loaded with another class loader. Thus, it does not have access to the protected fields and methods of the inner classes of its super class (Parameter is an inner class of FieldMapper).

My basic question here is: How is this meant to work? I tried to check out other ES Mapping Plugins but they just don't implement the doXContentBody() method. I am unclear about the consequences about implementing or not implementing it and so I am at a loss here. Must I implement it? How could I do it without access to the toXContent() method of the FieldMapper.Parameter class? What happens if I don't implement it?

My plugin code and the specific method can be found here: https://github.com/JULIELab/elasticsearch-mapper-preanalyzed/blob/86bd2b5cf9f3020231603ed5cc7bfcdb3feb6669/src/main/java/org/elasticsearch/index/mapper/PreanalyzedFieldMapper.java#L1241

As I said, it's in large parts a copy of ElasticSearch's TextFieldMapper class since it should behave like it. Perhaps that is an error to begin with. But in previous ES versions that worked fine. This issue with the protected parameter method is new to me.


问:
Is there any documentation on the TypeScript 'type spread' behavior?
I've just came across a TypeScript exercise, requiring the user to define custom LastElementOfArray type. The solution looks like this:

```<code>    type Last<A extends Array<any>> = A extends [...infer _, infer L] ? L : never
</code>```

But something is weird. If the used syntax is 'spread', why is there an inconsistency with how JavaScript handles 'spread'? Specifically, the spread variable must be the last one - this JavaScript code returns a SyntaxError:

```<code>    const a = [1,2,3,4,5];
    (([...rest, e4, e5])=>{console.error(e4,e5)})(a)
</code>```

Why does this 'inconsistency' exist? Is there any documentation on this? I've looked but found nothing.

Any help is appreacited.

Body:
I've just came across a TypeScript exercise, requiring the user to define custom LastElementOfArray type. The solution looks like this:

    type Last<A extends Array<any>> = A extends [...infer _, infer L] ? L : never

But something is weird. If the used syntax is 'spread', why is there an inconsistency with how JavaScript handles 'spread'? Specifically, the spread variable must be the last one - this JavaScript code returns a SyntaxError:

    const a = [1,2,3,4,5];
    (([...rest, e4, e5])=>{console.error(e4,e5)})(a)

Why does this 'inconsistency' exist? Is there any documentation on this? I've looked but found nothing.

Any help is appreacited.


问:
I'm going to work on the crontab every five minutes from 6 to 24
I'm going to work on the crontab every five minutes from 6 to 24.
but It's a 5-minute cycle, but I'm trying to get it done 40 seconds earlier.
Then every time, 4 minutes and 20 seconds, 9 minutes and 20 seconds, 14 minutes and 20 seconds... Everything will be done.
So the crontab schedule I thought of is 20 4/5 6-24 * *, did I set it up correctly?

Running every 5 minutes and sleeping for 4 minutes and 20 seconds seems inefficient.
And how do I do this in Window?


问:
Getting /script.sh: not found in Jenkins during running the docker image
My goal is to run a copyright job on Jenkins Declarative Pipeline.

When I run an image locally using these commands it works fine:

```<code>docker pull avidregistry.azurecr.io/my_repo/gocopyright:latest
docker run -v $(pwd):/workspace avidregistry.azurecr.io/my_repo/gocopyright:latest gocopyright -g
</code>```

But when I added a copyright stage to Jenkinsfile and running the same image:

```<code>        stage('Copyright') {
            agent {
                docker {
                    image 'avidregistry.azurecr.io/my_repo/gocopyright:latest'
                    args '-v $PWD:/workspace'
                    reuseNode true
                }
            }
            steps {
                sh 'gocopyright -g'
                sh 'ls -la'
                sh 'pwd'
            }
        }
</code>```

I get an exception like this one:

```<code>[my-pipeline@2] Running shell script
sh: /var/lib/jenkins/workspace/my-pipeline@2@tmp/durable-d3f6e37a/script.sh: not found
</code>```

What`s the problem in? How can I fix it?

Body:
My goal is to run a copyright job on Jenkins Declarative Pipeline.

When I run an image locally using these commands it works fine:

docker pull avidregistry.azurecr.io/my_repo/gocopyright:latest
docker run -v $(pwd):/workspace avidregistry.azurecr.io/my_repo/gocopyright:latest gocopyright -g

But when I added a copyright stage to Jenkinsfile and running the same image:

        stage('Copyright') {
            agent {
                docker {
                    image 'avidregistry.azurecr.io/my_repo/gocopyright:latest'
                    args '-v $PWD:/workspace'
                    reuseNode true
                }
            }
            steps {
                sh 'gocopyright -g'
                sh 'ls -la'
                sh 'pwd'
            }
        }

I get an exception like this one:

[my-pipeline@2] Running shell script
sh: /var/lib/jenkins/workspace/my-pipeline@2@tmp/durable-d3f6e37a/script.sh: not found

What`s the problem in? How can I fix it?


问:
Forbidden HTTPS request from Node.js server - what is going wrong here?
I'm attempting to make a GET request to the Discogs collection folders api via a node js server, however the request is 'Forbidden'.

At present, a html button triggers a GET request to the node server using fetch API. The Node server then routes the GET request to a handler which makes a https request to the GET collection folders endpoint.

I am expecting the following response (see 'Toggle' for the /users/{username}/collection/folders endpoint here):

expected response
https://www.discogs.com/developers/#page:user-collection,header:user-collection-collection

This requires authentication, for which a number of options are documented here: https://www.discogs.com/developers/#page:authentication,header:authentication-discogs-auth-flow

I have made successful GET and POST requests by passing my api key as and Authorization header when making requests from the frontend using fetch api only, so I am attempting to use that method to authorize the request from the node server.

Actual Output - Browser

Actual Output - Browser

Actual Output - Node terminal

Actual Output - Node terminal

HTML and Script

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test GET request to Discogs API</title>
</head>
<body>
    <form>
        <input type="button" value="Get Folders" onclick="getFolders()">
    </form>
    <script>
        async function getFolders() {
            try {
                const res = await fetch('http://localhost:1000/getfolders')
                if(!res.ok) {
                    console.log('node server response not ok')
                } else {
                    const jsonResponse = await res.json()
                    console.log('hello' + jsonResponse)
                }
            } catch (error) {
                console.log('there was an error' + error)
            }
        }
    </script>
</body>
</html>
</code>```

Node js Server

```<code>const http = require('http')
const https = require('https')
const url = require('url')
const port = 1000
const username = 'someUsername'
const apiKey = 'apikey123456789'

const server = http.createServer((req, res) => {
    const {method} = req

    switch(method) {
        case 'GET':
            return handleGetRequest(req, res)
        default:
            throw new Error(`Unsupported request method: ${method}`)
    }

    })

server.listen(port, () => {
    console.log('Server listening on port:' + port);
})

const handleGetRequest = (req, res) => {
    const options = {
        hostname: 'api.discogs.com',
        path: `/users/${username}/collection/folders`,
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Discogs token=${apiKey}`
        }
    }

    const request = https.request(options, response => {
        let data = ''

        response.on('data', (chunk) => {
            data += chunk
        })

        response.on('end', () => {
            console.log('Retrieved Data:', data)
            res.setHeader("Access-Control-Allow-Origin", "*")
            const jsonData = JSON.stringify(data)
            res.end(jsonData)
        })
    })

    request.end()
}
</code>```

Body:
I'm attempting to make a GET request to the Discogs collection folders api via a node js server, however the request is 'Forbidden'.

At present, a html button triggers a GET request to the node server using fetch API. The Node server then routes the GET request to a handler which makes a https request to the GET collection folders endpoint.

I am expecting the following response (see 'Toggle' for the /users/{username}/collection/folders endpoint here):

expected response
https://www.discogs.com/developers/#page:user-collection,header:user-collection-collection

This requires authentication, for which a number of options are documented here: https://www.discogs.com/developers/#page:authentication,header:authentication-discogs-auth-flow

I have made successful GET and POST requests by passing my api key as and Authorization header when making requests from the frontend using fetch api only, so I am attempting to use that method to authorize the request from the node server.

Actual Output - Browser

Actual Output - Browser

Actual Output - Node terminal

Actual Output - Node terminal

HTML and Script

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test GET request to Discogs API</title>

    <form>
        <input type="button" value="Get Folders" onclick="getFolders()">
    </form>

Node js Server

const http = require('http')
const https = require('https')
const url = require('url')
const port = 1000
const username = 'someUsername'
const apiKey = 'apikey123456789'

const server = http.createServer((req, res) => {
    const {method} = req

    switch(method) {
        case 'GET':
            return handleGetRequest(req, res)
        default:
            throw new Error(`Unsupported request method: ${method}`)
    }

    })

server.listen(port, () => {
    console.log('Server listening on port:' + port);
})

const handleGetRequest = (req, res) => {
    const options = {
        hostname: 'api.discogs.com',
        path: `/users/${username}/collection/folders`,
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Discogs token=${apiKey}`
        }
    }

    const request = https.request(options, response => {
        let data = ''

        response.on('data', (chunk) => {
            data += chunk
        })

        response.on('end', () => {
            console.log('Retrieved Data:', data)
            res.setHeader("Access-Control-Allow-Origin", "*")
            const jsonData = JSON.stringify(data)
            res.end(jsonData)
        })
    })

    request.end()
}


问:
How to generate hmac in binary in Python and convert it into base64
I have the following code in bash and I want to convert it in Python.

```<code>
#!/bin/bash
username="USERNAME"
apiKey='KEY'
date=`env LANG="en_US.UTF-8" date -u "+%a, %d %b %Y %H:%M:%S GMT"`
password=`echo -n "$date" | openssl dgst -sha1 -hmac $apiKey -binary | openssl enc -base64`
curl -i --url "YOUR API HERE" \
-X "POST" \
-H "Date:$date" \
-H "Content-Type: application/json" \
-u "$username:$password" \
-d'{
    "urls": [
        "YOUR URL HERE"
            ]
}'
</code>```

I have rewritten most of the code in Python but I am having trouble in implementing the following line
password=echo -n "$date" | openssl dgst -sha1 -hmac $apiKey -binary | openssl enc -base64

My current python code is as follows

```<code>import time
import requests
import base64

username = "Username"
apiKey = 'KEY'
date = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())

hmac1 = hmac.new(key=apiKey.encode(), msg=date.encode(), digestmod="sha1")
message_digest1 = hmac1.hexdigest()

headers = {
    "Date": date,
    "Content-Type": "application/json"
}
data = {
    "urls": [
        "YOUR URL HERE"
            ]
}
url = 'YOUR API HERE'
response = requests.post(url, headers=headers, data=data, auth = (username, message_digest1))

print(response.headers)
print(response.text)`
</code>```

I know the answer involves using hmac and hashlib library but none of what I have tried has worked. Also does the -u flag in curl translate to auth in python. Can anyone help

Body:
I have the following code in bash and I want to convert it in Python.

#!/bin/bash
username="USERNAME"
apiKey='KEY'
date=`env LANG="en_US.UTF-8" date -u "+%a, %d %b %Y %H:%M:%S GMT"`
password=`echo -n "$date" | openssl dgst -sha1 -hmac $apiKey -binary | openssl enc -base64`
curl -i --url "YOUR API HERE" \
-X "POST" \
-H "Date:$date" \
-H "Content-Type: application/json" \
-u "$username:$password" \
-d'{
    "urls": [
        "YOUR URL HERE"
            ]
}'

I have rewritten most of the code in Python but I am having trouble in implementing the following line
password=echo -n "$date" | openssl dgst -sha1 -hmac $apiKey -binary | openssl enc -base64

My current python code is as follows

import time
import requests
import base64

username = "Username"
apiKey = 'KEY'
date = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())

hmac1 = hmac.new(key=apiKey.encode(), msg=date.encode(), digestmod="sha1")
message_digest1 = hmac1.hexdigest()

headers = {
    "Date": date,
    "Content-Type": "application/json"
}
data = {
    "urls": [
        "YOUR URL HERE"
            ]
}
url = 'YOUR API HERE'
response = requests.post(url, headers=headers, data=data, auth = (username, message_digest1))

print(response.headers)
print(response.text)`

I know the answer involves using hmac and hashlib library but none of what I have tried has worked. Also does the -u flag in curl translate to auth in python. Can anyone help


问:
Is there a way to assert type without duplicating code? - Typescript
I wrote up this code where you can see the issue I'm having with the solution that I currently have.

```<code>type Keys = "foo" | "bar";

type Item = {
  id: string;
}

type Dated = {
  date: string;
  item: Item
}

function isItem(param: any): param is Item {
  if (!param) return false;
  return (param as Item).id !== undefined;
}

type AddDated = {
  item: string | Dated;
  key: Extract<Keys, "foo">
}

type AddNonDated = {
  item: Item;
  key: Extract<Keys, "bar">
}

function addItem(payload: AddDated | AddNonDated) {
  // Do something
}

function manageItem(item: AddDated["item"] | AddNonDated["item"], key: Keys) {
  if (isItem(item) && key === "bar") {
    addItem({
      item: item,
      key
    })
  } else if (!isItem(item) && key === "foo") {
    addItem({
      item: item,
      key
    })
  }

}
</code>```

ts playground

Basically what I want to know is if it's possible to have the manageItem function with type assertion but without having to duplicate the code that is going to use the asserted variable.

Body:
I wrote up this code where you can see the issue I'm having with the solution that I currently have.

type Keys = "foo" | "bar";

type Item = {
  id: string;
}

type Dated = {
  date: string;
  item: Item
}

function isItem(param: any): param is Item {
  if (!param) return false;
  return (param as Item).id !== undefined;
}

type AddDated = {
  item: string | Dated;
  key: Extract<Keys, "foo">
}

type AddNonDated = {
  item: Item;
  key: Extract<Keys, "bar">
}

function addItem(payload: AddDated | AddNonDated) {
  // Do something
}

function manageItem(item: AddDated["item"] | AddNonDated["item"], key: Keys) {
  if (isItem(item) && key === "bar") {
    addItem({
      item: item,
      key
    })
  } else if (!isItem(item) && key === "foo") {
    addItem({
      item: item,
      key
    })
  }

}

<a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBA0hIGcoF4oCIBmB7LaoB90AjAQwCc0BuAKGtEigElgIBbFKAb2qigEsAJgC4oCYGT4A7AOY0AvrXrQAIiRYCO3XgLUQRYiTJq8+LViOZtqC6hgCukgMbA+WSfwSXWACjDkS5lAkkiAAlCJ+ZAEeTGZcPPwYUN4AhJEBoVBkEMB2ZO4YJAA2CBDGWTl57r7+7CRIXqEAdIJQKcioDgIQGFIQAvKK4NAAggICquqaCaZs+uJS0gRQk-3lANbwIgCiAB7iJM4APHCIADTo2LgAfNZDDGMCAHJuqxqoWvxmFmYbW1B7A7HU4IC5oUgUW42exOFxuILjLw1EBFLAkYRQR5vZaPF6SN6ZT4AeiJKywoiwrByAAtFndbA5nK53KxgiRpBAkbNAljdAIANpobloAC6OPGeLeguFIoumxAIhBhJmSW8fE8ZjVZkyADIdVB5SgOsRyGhlbxeOiBEjPhavnN7awzgk7fKXVA5KEEnIoBAStA+KqUuqudqoHqDfAjahMDgzfE7Vabe6TN9Hc67bw3XbPd7aHIgA" rel="nofollow noreferrer">ts playground

Basically what I want to know is if it's possible to have the manageItem function with type assertion but without having to duplicate the code that is going to use the asserted variable.


问:
MUI5 Alert severity backgroundColor change from theme file isn't working
I'm trying to change the default severity backgroundColor for the Alert component from MUI5 to give every severity my custom background color.
I want to do it with a theme update so the changes will apply to all the components using it but only in this case couldn't find the way to do so.

the component: Alert MUI

here is how it looks in dev tools

I tried to override it with:

```<code> MuiAlert: {
  styleOverrides: {
    root: {
      filled: {
        filledSuccess: {
          backgroundColor: "grey",
        }
      },
    }
  },
},
</code>```

and with:

```<code>  MuiAlert: {
  styleOverrides: {
    filledSuccess: {
      backgroundColor: "grey",
    },
  },
},
</code>```

Body:
I'm trying to change the default severity backgroundColor for the Alert component from MUI5 to give every severity my custom background color.
I want to do it with a theme update so the changes will apply to all the components using it but only in this case couldn't find the way to do so.

the component: Alert MUI

here is how it looks in dev tools

I tried to override it with:

 MuiAlert: {
  styleOverrides: {
    root: {
      filled: {
        filledSuccess: {
          backgroundColor: "grey",
        }
      },
    }
  },
},

and with:

  MuiAlert: {
  styleOverrides: {
    filledSuccess: {
      backgroundColor: "grey",
    },
  },
},


问:
I was recieving the new daily table with dates format dailytable_20221121_20221204_20221205_041703, looking for a query to find latest table
I was recieving the daily table with below example dates format. Data inside the table loading from last 14 days starts from yesterday's (20221121_20221204) and table creation date was today. Example : dailytable_20221121_20221204_20221205_041703 How can I write query with these date formats for daily newly added table? I want to conctanate these data into my main_table.

Contacting daily a new table to the main table. Schema and the dataset are same.


问:
How to efficiently formalize an optimization problem for python
I have an optimization problem that I could set up as either a rather complex univariate problem with a non-linear optimization function, or as a multivariate problem with linear optimization function.

Is it possible to somewhat generalize whether from a programming perspective, one is more efficient than the other? I.e. even without going into the details of the functions and constraints, are solvers more efficient with functionally complex univariate problems over simple multivariate problems or vice versa?

I tried to google the problem but the results I read were all looking at examples that didn't even require numerical solving. (e.g. this)

Once I figured out the best approach I'll implement it in python.


问:
Modulating encrypted text file
I am trying to modulate encrypted txt file using GNU Radio. Encryption part is already done and working. I am trying to figure out how to trasmitt it using psk. Im still a beginner at gnu radio. Is the following flowgraph logical?

Im trying to use unpack/pack to convert the encrypted text to binary so it can be transmitted, but this seems not to work.

Title: Modulating encrypted text file


问:
Disable local notifications on button press in Expo / react-native
I have an Expo app (which has been ejected but there is very little native code being used). I am using expo-notifications to schedule local notifications for the user. I am only doing this for background/killed state notifications. There are no foreground notifications.

I'd like to know if it's possible to turn them on or off when a button is pressed without losing all the notification data in React-native/Expo?

I want to add a toggle in the settings screen to turn notifications on or off and I can't figure out how to do this. I can of course cancel all scheduled notifications with cancelAllScheduledNotificationsAsync, but then if they toggle notifications back on all the existing ones would be lost.

I'm hoping to avoid having to store a bunch of data in AsyncStorage for this.

I'm working on handling this all in push notifications (which will solve a lot of headaches) but that's still a way out from being ready.


问:
Wordpress - Add validation to First and Last name
I've been stuck on, in my opinion, a very simple and stupid problem. In the Wordpress User Backend, you have a First and Last name field. The only thing I want to accomplish is to add some form of validation to these fields. I also want to prevent Users from adding numbers to their first and last names in their WooCommerce account.

The problem

I cannot allow any numbers in the First and Last name fields, since WooCommerce uses this field for billing and shipping, and I use these fields for other purposes as well. I do not want to use plugins for this, and would like to accomplish this programmatically.

( BTW, it's also absolutely ridiculous even trying to Google this very problem. The only results are about custom fields and plugins, plugins, plugins... And the worst thing, is that none of those actually serve this purpose )

What I have tried

I have tried looking trough WP's admin user code, but I can't make heads or tails of it. I've seen ( a lot of ) suggestions about using plugins and using Custom Fields, but I don't want a plugin to do this for me, because of WooCommerce. I 'simply' want to add a validation to these 2 fields to prevent numbers in these fields.

Example of Checkout validation

Below is a code snippet that adds registration validation for a custom field. I was wondering if I could use this for the first and last name fields as well. I would like to use this for both the User registration form on the front-end, and the Wordpress back-end.

```<code>add_action( 'user_profile_update_errors','wooc_validate_custom_field', 10, 1 );

add_action( 'woocommerce_save_account_details_errors','wooc_validate_custom_field', 10, 1 );

function wooc_validate_custom_field( $args )
{
    if ( isset( $_POST['first_name'] ) )
    {
        if(preg_match('~[0-9]+~',$_POST['first_name'])) // if value contains a number
        $args->add( 'error', __( 'Numbers not allowed', 'woocommerce' ),'');
    }
}
</code>```

Does anyone know how I could accomplish this? without using plugins please.. :)

Body:
I've been stuck on, in my opinion, a very simple and stupid problem. In the Wordpress User Backend, you have a First and Last name field. The only thing I want to accomplish is to add some form of validation to these fields. I also want to prevent Users from adding numbers to their first and last names in their WooCommerce account.

The problem

I cannot allow any numbers in the First and Last name fields, since WooCommerce uses this field for billing and shipping, and I use these fields for other purposes as well. I do not want to use plugins for this, and would like to accomplish this programmatically.

( BTW, it's also absolutely ridiculous even trying to Google this very problem. The only results are about custom fields and plugins, plugins, plugins... And the worst thing, is that none of those actually serve this purpose )

What I have tried

I have tried looking trough WP's admin user code, but I can't make heads or tails of it. I've seen ( a lot of ) suggestions about using plugins and using Custom Fields, but I don't want a plugin to do this for me, because of WooCommerce. I 'simply' want to add a validation to these 2 fields to prevent numbers in these fields.

Example of Checkout validation

Below is a code snippet that adds registration validation for a custom field. I was wondering if I could use this for the first and last name fields as well. I would like to use this for both the User registration form on the front-end, and the Wordpress back-end.

add_action( 'user_profile_update_errors','wooc_validate_custom_field', 10, 1 );

add_action( 'woocommerce_save_account_details_errors','wooc_validate_custom_field', 10, 1 );

function wooc_validate_custom_field( $args )
{
    if ( isset( $_POST['first_name'] ) )
    {
        if(preg_match('~[0-9]+~',$_POST['first_name'])) // if value contains a number
        $args->add( 'error', __( 'Numbers not allowed', 'woocommerce' ),'');
    }
}

Does anyone know how I could accomplish this? without using plugins please.. :)


问:
How to refer to main database instead test one Django TestCase
I am using Django TestCase class to run some test in my project. Few of these test using selenium driver to test forms via browser. Creation of new instance of database table (Recipe for ex.)
Point is. Since im using a browser and fill forms fields with Selenium driver, new recipe instance is creating for main database, not test one.

I am trying to delete last added row from Recipe table with

```<code>Recipe.objects.using('default').latest('id').delete()
</code>```

after successful test run.

'default' is single database connection. But this query is targeting test database, which us creating while tests run.
How make query refer to main database instead?

Body:
I am using Django TestCase class to run some test in my project. Few of these test using selenium driver to test forms via browser. Creation of new instance of database table (Recipe for ex.)
Point is. Since im using a browser and fill forms fields with Selenium driver, new recipe instance is creating for main database, not test one.

I am trying to delete last added row from Recipe table with

Recipe.objects.using('default').latest('id').delete()

after successful test run.

'default' is single database connection. But this query is targeting test database, which us creating while tests run.
How make query refer to main database instead?


问:
How to request response from .net core to aws amplify GraphQL
Recently, I'm working on AWS Amplify, Which has  java and javaScripts related example, but no .net related example. after next i solved this below the way. Here is my question this is the only process to request or response, another way that i missed.

```<code>const string query = "query ";

var serializer = new NewtonsoftJsonSerializer();

using var graphQlClient = new GraphQLHttpClient("https://xx.xx.xx.amazonaws.com/graphql", serializer);

graphQlClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", "<api key>");

var subscriptionStream = await graphQlClient.SendQueryAsync<dynamic>(query);

</code>```

I expect a better way, except my current code.

Body:
Recently, I'm working on AWS Amplify, Which has  java and javaScripts related example, but no .net related example. after next i solved this below the way. Here is my question this is the only process to request or response, another way that i missed.

const string query = "query ";

var serializer = new NewtonsoftJsonSerializer();

using var graphQlClient = new GraphQLHttpClient("https://xx.xx.xx.amazonaws.com/graphql", serializer);

graphQlClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", "<api key>");

var subscriptionStream = await graphQlClient.SendQueryAsync<dynamic>(query);

I expect a better way, except my current code.