问:
Chrome addons (plugins) javascript files seem isolated
I have created an unpacked plugin for Chrome (that also works in Firefox), that has a single script.js file.  And it works.

However, trying to call a function included in the addon's script.js file from the console results in:

```<code>Uncaught ReferenceError: _islet_convert is not defined
at <anonymous>:1:1
</code>```

(anonymous) @ VM259:1

Which by the way I tested just to verify with not_a_function() in the console, and the error was the same.

Can someone tell me how Chrome and probably Firefox handles or isolates the JavaScript in the content_scripts files?  And if there is any way to reference a function/method in the file.

答:
From the documentation in Chrome:

https://developer.chrome.com/docs/extensions/mv2/content_scripts/

Content scripts live in an isolated world, allowing a content script to makes changes to its JavaScript environment without conflicting with the page or additional content scripts.

...

Isolated worlds do not allow for content scripts, the extension, and the web page to access any variables or functions created by the others. This also gives content scripts the ability to enable functionality that should not be accessible to the web page.

Essentially, it appears any communication needs to happen through the DOM including adding event listeners.

OwnerDisplayName: Oliver Williams

Body:
I have created an unpacked plugin for Chrome (that also works in Firefox), that has a single script.js file.  And it works.

However, trying to call a function included in the addon's script.js file from the console results in:

Uncaught ReferenceError: _islet_convert is not defined
at <anonymous>:1:1

(anonymous) @ VM259:1

Which by the way I tested just to verify with not_a_function() in the console, and the error was the same.

Can someone tell me how Chrome and probably Firefox handles or isolates the JavaScript in the content_scripts files?  And if there is any way to reference a function/method in the file.


来源: stackexchange

问:
Customizing the predefined callbacks of Matplotlib Navigation Toolbar buttons
I have GUI based interface where the user can select and unselect different properties to plot on a canvas, which is why it is important for me to use axis.autoscale_view every time a new plot is plotted. This seems to work fine until the use decides to zoom in a graph and then hits the home button and plots something new. After which for some reason the autoscale_view stops working.

For this reason, I want to embed this directly in the callback function of the home button provided in the navigation toolbar. Is it possible to modify the already created callback function of the home button in the navigation toolbar?

答:
I just stumbled upon your question ... not sure if it's still relevant, but here's a hacky way how you could do it by decorating the toolbar._update_view function ...

(_update_view is called whenever the home or the change view buttons are pressed from the gui toolbar)

import matplotlib.pyplot as plt

f, ax = plt.subplots()
l, = ax.plot([1,2,3,4,5])

def update_decorator(f):
    def newf(*args, **kwargs):
        ret = f(*args, **kwargs)
        print("something happened")
        return ret
    return newf

# decorate toolbar._update_view
# (called whenever the home-button or the change-view button is pressed in a gui)
toolbar = f.canvas.toolbar
if toolbar is not None:
    toolbar._update_view = update_decorator(toolbar._update_view)
```

ContentLicense: CC BY-SA 4.0


问:
Failed to upload apk via Connect API
I am working on a python script to update the app on Huawei AppGallery via Connect API.
I successfully fetched the token and upload URL but not able to upload the APK/AAB.
Getting this error -

{'result': {'CException': {'errorCode': 70001405, 'errorDesc': 'get no file from request!'}, 'resultCode': '70001405'}}

Here's my python script

```<code>def uploadAAB(uploadUrl, authCode, accessToken, appId):
    try:
        fileName = 'latest_hms.apk'
        headers = {
            "Authorization": "Bearer " + accessToken,
            "accept": "application/json",
            "client_id": clientId,
            "Content-Type": "multipart/form-data"
        }

        uploadBody = {
            "authCode": authCode,
            "fileCount": 1
        }

        with open(aabPath, 'rb') as f:
            f.seek(0, os.SEEK_END)
            print(f.tell()) # printing the correct size
            first_phase = requests.post(
                uploadUrl,
                files={fileName: f},
                data=uploadBody,
                headers=headers)

            if first_phase.status_code == 200:
                print(first_phase.json())
                body = {
                    'fileType': 5,
                    'files': [{
                        'fileName': fileName,
                        'fileDestUrl': first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['fileDestUlr'],
                        'size': str(first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['size'])
                    }]
                }

                fileHeader = {
                    'client_id': clientId,
                    'Authorization': 'Bearer ' + accessToken,
                }
                params = {
                    'appId': appId,
                }
                second_phase = requests.put(
                    BASE_URL + "/publish/v2/app-file-info",
                    headers=fileHeader,
                    json=body,
                    params=params)
                print(second_phase.json())

    except (requests.exceptions.RequestException, requests.exceptions.HTTPError, KeyError) as err:
        stopOnError(repr(err))
</code>```

Please help me out here.

答:
{'result': {'CException': {'errorCode': 70001405, 'errorDesc': 'get no file from request!'}, 'resultCode': '70001405'}}

This error means there is no file in the request. the file is not include successfully in the request. Please make sure the file is achievable.

Title: Failed to upload apk via Connect API

Body:
I am working on a python script to update the app on Huawei AppGallery via Connect API.
I successfully fetched the token and upload URL but not able to upload the APK/AAB.
Getting this error -

{'result': {'CException': {'errorCode': 70001405, 'errorDesc': 'get no file from request!'}, 'resultCode': '70001405'}}

Here's my python script

def uploadAAB(uploadUrl, authCode, accessToken, appId):
    try:
        fileName = 'latest_hms.apk'
        headers = {
            "Authorization": "Bearer " + accessToken,
            "accept": "application/json",
            "client_id": clientId,
            "Content-Type": "multipart/form-data"
        }

        uploadBody = {
            "authCode": authCode,
            "fileCount": 1
        }

        with open(aabPath, 'rb') as f:
            f.seek(0, os.SEEK_END)
            print(f.tell()) # printing the correct size
            first_phase = requests.post(
                uploadUrl,
                files={fileName: f},
                data=uploadBody,
                headers=headers)

            if first_phase.status_code == 200:
                print(first_phase.json())
                body = {
                    'fileType': 5,
                    'files': [{
                        'fileName': fileName,
                        'fileDestUrl': first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['fileDestUlr'],
                        'size': str(first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['size'])
                    }]
                }

                fileHeader = {
                    'client_id': clientId,
                    'Authorization': 'Bearer ' + accessToken,
                }
                params = {
                    'appId': appId,
                }
                second_phase = requests.put(
                    BASE_URL + "/publish/v2/app-file-info",
                    headers=fileHeader,
                    json=body,
                    params=params)
                print(second_phase.json())

    except (requests.exceptions.RequestException, requests.exceptions.HTTPError, KeyError) as err:
        stopOnError(repr(err))

Please help me out here.


问:
Odoo Custom Tree Control
If you create new quotation in the Sales module, there are some control buttons:

Add a product

Add a section

Add a note

I want to create those custom control for my tree view. But when I search from the source code, I can't find where is the python method is called.

```<code>...
<tree string="Sales Order Lines" editable="bottom">
    <control>
        <create name="add_product_control" string="Add a product"/>
        <create name="add_section_control" string="Add a section" context="{'default_display_type': 'line_section'}"/>
        <create name="add_note_control" string="Add a note" context="{'default_display_type': 'line_note'}"/>
    </control>
...
</code>```

I search the add_product_control keyword, but there is nothing I found.

答:
Because odoo is not calling any python method it will trigger from javascript side and it will add new record and hide other fields using display_type
display-types

line_section

line_note

and you can find code in
/addons/account/static/src/js/section_and_note_fields_backend.js

Title: Odoo Custom Tree Control

Body:
If you create new quotation in the Sales module, there are some control buttons:

Add a product

Add a section

Add a note

I want to create those custom control for my tree view. But when I search from the source code, I can't find where is the python method is called.

...
<tree string="Sales Order Lines" editable="bottom">
    <control>
        <create name="add_product_control" string="Add a product"/>
        <create name="add_section_control" string="Add a section" context="{'default_display_type': 'line_section'}"/>
        <create name="add_note_control" string="Add a note" context="{'default_display_type': 'line_note'}"/>
    </control>
...

I search the add_product_control keyword, but there is nothing I found.


问:
If I pull the data from BiqQuery, will Google charge me or not for sending the data to Data Studio?
If I pull the data from BiqQuery, will Google charge me or not for sending the data to Data Studio?</p>

答:
BigQuery runs queries that you pay.

DataStudio runs queries on BigQuery that you pay.

There is no cost of transfer between the two systems.


问:
Using pyinstaller with anaconda environment
I have a very simple application made on python(v 3.6), and I wanted to freeze it using pyinstaller.I have made the app using an environment created with anaconda, and I installed there the packages I needed(youtube_dl). I need help on how to use pyinstaller for my app(Main.py) using the environment I created with all its packages inside it.
If I run "pyinstaller Main.py" I get this error:

```<code>Traceback (most recent call last):
  File "Main.py", line 7, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyInstaller/loader/pyimod03_importers.py", line 631, in exec_module
    exec(bytecode, module.__dict__)
  File "youtube_downloader.py", line 3, in <module>
ModuleNotFoundError: No module named 'youtube_dl'
[2708] Failed to execute script Main
logout
</code>```

How can I make pyinstaller use the environment I created at anaconda´s directory?

答:
If you failed to run piping piping's answer.

Eg:

Using a very old version of Anaconda and you still have to use it.

Using very old pip.

You cannot access to pypi from host machine.

You may install pyinstaller manually.

Prerequisite

Assuming you have setuptools installed.

Example: PyInstaller 3.5 (for python 2.7) on linux

Download PyInstaller 3.5

Check the requirements.txt

```<code>pefile; sys_platform == 'win32'
macholib; sys_platform == 'darwin'
altgraph  # <== you need this

dis3; python_version < '3.0' #<== and this
pywin32-ctypes; sys_platform == 'win32'
</code>```

Download and install dis3

tar xzf dis3-0.1.3.tar.gz

cd dis3-0.1.3

python setup.py install or /somewhere/your/python2.7 setup.py install

Download and install altgraph

Same as dis3

Install PyIstaller

Same as above.

Body:
I have a very simple application made on python(v 3.6), and I wanted to freeze it using pyinstaller.I have made the app using an environment created with anaconda, and I installed there the packages I needed(youtube_dl). I need help on how to use pyinstaller for my app(Main.py) using the environment I created with all its packages inside it.
If I run "pyinstaller Main.py" I get this error:

Traceback (most recent call last):
  File "Main.py", line 7, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyInstaller/loader/pyimod03_importers.py", line 631, in exec_module
    exec(bytecode, module.__dict__)
  File "youtube_downloader.py", line 3, in <module>
ModuleNotFoundError: No module named 'youtube_dl'
[2708] Failed to execute script Main
logout

How can I make pyinstaller use the environment I created at anaconda´s directory?

Body:
If you failed to run piping piping's answer.

Eg:

Using a very old version of Anaconda and you still have to use it.

Using very old pip.

You cannot access to pypi from host machine.

You may install pyinstaller manually.

Prerequisite

Assuming you have setuptools installed.

Example: PyInstaller 3.5 (for python 2.7) on linux

Download PyInstaller 3.5

Check the requirements.txt

pefile; sys_platform == 'win32'
macholib; sys_platform == 'darwin'
altgraph  # <== you need this

dis3; python_version < '3.0' #<== and this
pywin32-ctypes; sys_platform == 'win32'

Download and install dis3

tar xzf dis3-0.1.3.tar.gz

cd dis3-0.1.3

python setup.py install or /somewhere/your/python2.7 setup.py install

Download and install altgraph

Same as dis3

Install PyIstaller

Same as above.


问:
Can't install Tensorflow lower than 2.0
I got this error

AttributeError: module 'TensorFlow' has no attribute 'variable_scope'

when I ran my code and I'm searching in Google for this. They said it required TensorFlow lower than 2.0. Then I started to install it with this code in cmd pip install tensorflow==1.15 then I got another error

ERROR: Could not find a version that satisfies the requirement tensorflow==1.15 (from versions: 2.5.0rc0, 2.5.0rc1, 2.5.0rc2, 2.5.0rc3, 2.5.0, 2.5.1, 2.5.2, 2.5.3, 2.6.0rc0, 2.6.0rc1, 2.6.0rc2, 2.6.0, 2.6.1, 2.6.2, 2.6.3, 2.7.0rc0, 2.7.0rc1, 2.7.0, 2.7.1, 2.8.0rc0, 2.8.0rc1, 2.8.0)
ERROR: No matching distribution found for tensorflow==1.15

I tried a lot of ways on the internet to find a way to solve it!
My information Tensorflow and computer

Name: tensorflow
Version: 2.8.0
Summary: TensorFlow is an open source machine learning framework for everyone.
Home-page: https://www.tensorflow.org/
Author: Google Inc.
Author-email: packages@tensorflow.org
License: Apache 2.0
Location: c:\users\admin\appdata\roaming\python\python39\site-packages
Requires: absl-py, astunparse, flatbuffers, gast, google-pasta, grpcio, h5py, keras, keras-preprocessing, libclang, numpy, opt-einsum, protobuf, setuptools, six, tensorboard, tensorflow-io-gcs-filesystem, termcolor, tf-estimator-nightly, typing-extensions, wrapt

Python 3.9.7

Computer information:

Intel(R) Core(TM) i7-8750H CPU Processor @ 2.20 GHz 2.21 GHz
Installed RAM 16.0 GB (15.9 GB usable)
Device ID 26A28871-033A-43F4-9933-B82BE00E75C3
Product ID 00330-80000-00000-AA214
System type 64 bit Operating system, processor based on x64
Pen and apps No pen or touchpad for this monitor

Thank you for your help

答:
You probably have CUDA11 install on your system. Tensorflow 1.X can't run on CUDA 11 unless you use Docker and Nvidia Container Toolkit.

I recommend you to use a Docker container provided by Tensorflow with the required version.

```<code>tensorflow/tensorflow:1.14.0-gpu-py3
</code>```

Check this post to view information about Python, CUDA, CudNN and Tensorflow version requirements:

Which TensorFlow and CUDA version combinations are compatible?

Title: Can't install Tensorflow lower than 2.0

Body:
You probably have CUDA11 install on your system. Tensorflow 1.X can't run on CUDA 11 unless you use Docker and Nvidia Container Toolkit.

I recommend you to use a Docker container provided by Tensorflow with the required version.

tensorflow/tensorflow:1.14.0-gpu-py3

Check this post to view information about Python, CUDA, CudNN and Tensorflow version requirements:

Which TensorFlow and CUDA version combinations are compatible?


问:
base64 HmacSHA1 decode in iPhone
I am working on an iPhone application that requires Base64 decoding using HmacSHA1 algorithm. Can anyone help me doing the objective-C equivalent of the given Java code:

```<code>SecretKeykey = new SecretKeySpec(com.sinotar.algorithm.Base64.decode(
    "vNQKX3C1wD/KprnnOcdRwM80YIn5bo47w9VdTlDpCB8="), "HmacSHA1");
</code>```

Thanks matthijz, But it has nothing to do with HmacSHA1. The solution I am looking for is something that does the equivalent of the Java code:

```<code>SecretKey key = null;
try { key = new SecretKeySpec(com.sinotar.algorithm.Base64.decode("vNQKX3C1wD/KprnnOcdRwM80YIn5bo47w9VdTlDpCB8="),
                              "HmacSHA1");
}
</code>```

Any help is appreciated.

答: Check out Matt Gallagher's article on Base64 encoding - it has downloadable code at the end. http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html</p>

ContentLicense: CC BY-SA 3.0

Title: base64 HmacSHA1 decode in iPhone

Body:
I am working on an iPhone application that requires Base64 decoding using HmacSHA1 algorithm. Can anyone help me doing the objective-C equivalent of the given Java code:

SecretKeykey = new SecretKeySpec(com.sinotar.algorithm.Base64.decode(
    "vNQKX3C1wD/KprnnOcdRwM80YIn5bo47w9VdTlDpCB8="), "HmacSHA1");

Thanks matthijz, But it has nothing to do with HmacSHA1. The solution I am looking for is something that does the equivalent of the Java code:

SecretKey key = null;
try { key = new SecretKeySpec(com.sinotar.algorithm.Base64.decode("vNQKX3C1wD/KprnnOcdRwM80YIn5bo47w9VdTlDpCB8="),
                              "HmacSHA1");
}

Any help is appreciated.


问:
How to implant a bot framework bot into an existing mvc application
Thank you for visiting my problem.
As you know from the title, I want to know how to add bot to the already existing mvc.
And I'm going to host it locally with iis.
In general, chatbots are located in the lower right corner of the screen.
Then I want a bot that is actually operated on web, not a bot that is viewed as an emulator.
I wonder if the bot framework implements a button at the bottom right with a separate css or image when the bot is actually implanted.
Can you help me solve this problem?

bot app and web app

答:
You should look at this tutorial as it looks like what you are searching to do :

https://www.codeproject.com/Articles/871501/Adding-a-Self-Hosted-Chatbot-to-an-ASP-NET-Website

Regards


问:
why does using-declaration in class definition sometimes hides names from its base class and sometimes not?
```<code>struct A { int i; };
struct B { int i; };
struct C: A, B {
    using A::i;
    void f() {
        i = 0;
    }
};
</code>```

This compiles happily. As far as I know, it is because using A::i; hides B::i.

```<code>struct A { int i; };
struct B: A {};
struct C: A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};
</code>```

But this does not compile, saying error: 'A' is an ambiguous base of 'D'. I don't understand what's the difference between those two. Why using B::i; does not hide C::i here?

Edit: I'm not trying to make something with that design. I know I should use virtual inheritance most of the case. I'm just wondering about the syntax of c++.

Edit: I'm still confusing with answers (which is now deleted) such as "B::i is same as A::i in second example". What I'm wondering is why is that. Where can I find basic syntax rules that makes B::i and A::i same? I have "The C++ Programming Language" of Bjarne Stroustroup, but that book is simply unreadable to me as a non native English user. If you also have the book, I'd appreciate it if you tell me the section of the book describing this problem.

答:
You formed the "Diamond of Death", well-known problem in C++, which is a design error novice programmer produces. Consider change the design. or, If you really wish it to be compiled, try this:

```<code>struct A { int i; };
struct B: virtual A {};
struct C: virtual A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};
</code>```

Some more detail:
In your code, B has its own A inside its instance, and C has its own A inside its instance. By inheriting from both B, C, D has B::A, and C::A inside it. when you trying to assign a value in i, it may be a B::A::i or C::A::i. Therefore ambiguity arises, and compiler complains. My suggestion code is utilizing virtual inheritance, so, in this diamond, A is appearing in D only once, and the ambiguity is resolved.

Addition: If you wish not to use the virtual inheritance, specify what i you are assigning to. ex)B::A::i = 0;

Body:
struct A { int i; };
struct B { int i; };
struct C: A, B {
    using A::i;
    void f() {
        i = 0;
    }
};

This compiles happily. As far as I know, it is because using A::i; hides B::i.

struct A { int i; };
struct B: A {};
struct C: A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};

But this does not compile, saying error: 'A' is an ambiguous base of 'D'. I don't understand what's the difference between those two. Why using B::i; does not hide C::i here?

Edit: I'm not trying to make something with that design. I know I should use virtual inheritance most of the case. I'm just wondering about the syntax of c++.

Edit: I'm still confusing with answers (which is now deleted) such as "B::i is same as A::i in second example". What I'm wondering is why is that. Where can I find basic syntax rules that makes B::i and A::i same? I have "The C++ Programming Language" of Bjarne Stroustroup, but that book is simply unreadable to me as a non native English user. If you also have the book, I'd appreciate it if you tell me the section of the book describing this problem.

Body:
You formed the "Diamond of Death", well-known problem in C++, which is a design error novice programmer produces. Consider change the design. or, If you really wish it to be compiled, try this:

struct A { int i; };
struct B: virtual A {};
struct C: virtual A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};

Some more detail:
In your code, B has its own A inside its instance, and C has its own A inside its instance. By inheriting from both B, C, D has B::A, and C::A inside it. when you trying to assign a value in i, it may be a B::A::i or C::A::i. Therefore ambiguity arises, and compiler complains. My suggestion code is utilizing virtual inheritance, so, in this diamond, A is appearing in D only once, and the ambiguity is resolved.

Addition: If you wish not to use the virtual inheritance, specify what i you are assigning to. ex)B::A::i = 0;


问:
Unable to validate the following destination configurations (S3 to SQS)
I am trying to set up a workflow with serverless that creates a new S3 bucket, a new SQS queue and when an object is created in the S3 bucket, puts a messages on the queue and spins up a lambda once there are enough messages on the queue. I have the following in my resources block:

```<code>resources:
  Resources:
    AnalyticsQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "my-queue"
    S3EventQueuePolicy:
      Type: AWS::SQS::QueuePolicy
      DependsOn: AnalyticsQueue
      Properties:
        PolicyDocument:
          Id: SQSPolicy
          Statement:
            - Effect: Allow
              Action: sqs:SendMessage:*
              Resource: !Ref AnalyticsQueue
        Queues:
          - !GetAtt AnalyticsQueue.Arn
    AnalyticsBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: "my-bucket"
        NotificationConfiguration:
          QueueConfigurations:
            - Event: s3:ObjectCreated:*
              Queue: !GetAtt AnalyticsQueue.Arn
</code>```

When I try to deploy this I receive the following error:

An error occurred: AnalyticsBucket - Unable to validate the following destination configurations (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: E2A1F8BD6BEE6EF4;).

Some googling and I found that the issue is in the NotificationConfiguration block on the AnalyticsBucket. If I remove that whole sub-block, it deploys just fine but then obviously won't generate messages on the queue when objects get created.

Looking for a way to resolve this.

答:
I tried to create the event manually in the AWS console and got the same problem.
It seems this problem occurs if we register an event to encrypted SQS. I tried to disable the SQS encryption to solve this problem. Maybe for encrypted SQS, further configuration is needed.

Body:
I am trying to set up a workflow with serverless that creates a new S3 bucket, a new SQS queue and when an object is created in the S3 bucket, puts a messages on the queue and spins up a lambda once there are enough messages on the queue. I have the following in my resources block:

resources:
  Resources:
    AnalyticsQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "my-queue"
    S3EventQueuePolicy:
      Type: AWS::SQS::QueuePolicy
      DependsOn: AnalyticsQueue
      Properties:
        PolicyDocument:
          Id: SQSPolicy
          Statement:
            - Effect: Allow
              Action: sqs:SendMessage:*
              Resource: !Ref AnalyticsQueue
        Queues:
          - !GetAtt AnalyticsQueue.Arn
    AnalyticsBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: "my-bucket"
        NotificationConfiguration:
          QueueConfigurations:
            - Event: s3:ObjectCreated:*
              Queue: !GetAtt AnalyticsQueue.Arn

When I try to deploy this I receive the following error:

An error occurred: AnalyticsBucket - Unable to validate the following destination configurations (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: E2A1F8BD6BEE6EF4;).

Some googling and I found that the issue is in the NotificationConfiguration block on the AnalyticsBucket. If I remove that whole sub-block, it deploys just fine but then obviously won't generate messages on the queue when objects get created.

Looking for a way to resolve this.


问:
How to delete all files in folder except CSV?
I wrote a dataframe to a csv in Pyspark. And I got the output files in the directory as:

._SUCCESS.crc

.part-00000-6cbfdcfd-afff-4ded-802c-6ccd67f3804a-c000.csv.crc

part-00000-6cbfdcfd-afff-4ded-802c-6ccd67f3804a-c000.csv

How do I keep only the CSV file in the directory and delete rest of the files, using Python?

答:
I would recommended to use pathlib (Python >= 3.4) and the in-build type set() to substract all csv filenames from the list of all files. I would argument this is easy to read, fast to process and a good pythonic solution.

```<code>>>> from pathlib import Path
>>> p = Path('/path/to/directory/with/files')
>>> # Get all file names
>>> # https://stackoverflow.com/a/65025567/4865723
>>> set_all_files = set(filter(Path.is_file, p.glob('**/*')))
>>> # Get all csv filenames (BUT ONLY with lower case suffix!)
>>> set_csv_files = set(filter(Path.is_file, p.glob('**/*.csv')))
>>> # Create a file list without csv files
>>> set_files_to_delete = set_all_files - set_csv_files
>>> # Iteratore on that list and delete the file
>>> for file_name in set_files_to_delete:
...     Path(file_name).unlink()
</code>```

Body:
I would recommended to use pathlib (Python >= 3.4) and the in-build type set() to substract all csv filenames from the list of all files. I would argument this is easy to read, fast to process and a good pythonic solution.

>>> from pathlib import Path
>>> p = Path('/path/to/directory/with/files')
>>> # Get all file names
>>> # https://stackoverflow.com/a/65025567/4865723
>>> set_all_files = set(filter(Path.is_file, p.glob('**/*')))
>>> # Get all csv filenames (BUT ONLY with lower case suffix!)
>>> set_csv_files = set(filter(Path.is_file, p.glob('**/*.csv')))
>>> # Create a file list without csv files
>>> set_files_to_delete = set_all_files - set_csv_files
>>> # Iteratore on that list and delete the file
>>> for file_name in set_files_to_delete:
...     Path(file_name).unlink()


问:
Vertical rulers in Visual Studio Code

Rendering More than One Ruler in VS Code

VS Code's default configuration for a ruler is demonstrated below.

```<code>  "editor.ruler": 80
</code>```

The issue I am having with the default VS Code configuration (as shown above) is that it only renders a single ruler. In the Sublime Text Editor I can render as many rulers as I like using the following Sublime configuration.

```<code>  "rulers": [72, 80, 100, 120]
</code>```

Is it possible to render multiple rulers in V.S. Code. If it is possible, What does a multi-ruler configuration look like in VS Code?

答:
File -> Preferences -> Settings Or cntrl+,

type "rulers" and click Edit Setings.json

3. Add the size value by ',' As you wish

Like this(Gif)

Title: Vertical rulers in Visual Studio Code

Body:
Rendering More than One Ruler in VS Code

VS Code's default configuration for a ruler is demonstrated below.

  "editor.ruler": 80

The issue I am having with the default VS Code configuration (as shown above) is that it only renders a single ruler. In the Sublime Text Editor I can render as many rulers as I like using the following Sublime configuration.

  "rulers": [72, 80, 100, 120]

Is it possible to render multiple rulers in V.S. Code. If it is possible, What does a multi-ruler configuration look like in VS Code?


问:
Do a Nim regex modifier just like Perl one
How is Nim regex PCRE modifier done as in Perl itself is e.g.

```<code>/foobar/i
/ foo bar /x
/foobar.*/s
</code>```

etc ?

Please explain correctly doing such on Nim

Thanks much in advance

答:
You should be using inline modifiers,

(?i)foobar
(?x)foobar
(?s)foobar
```
<p>Or, <em>modifier groups</em>, which is especially handy when only a part of the pattern needs to be modified:</p>
<pre class="lang-none prettyprint-override"><code>(?i:foobar)
(?x:foobar)
(?s:foobar)
</code>```

See "Regex Modifiers—Turning them On".

Body:
How is Nim regex PCRE modifier done as in Perl itself is e.g.

/foobar/i
/ foo bar /x
/foobar.*/s

etc ?

Please explain correctly doing such on Nim

Thanks much in advance

Body:
You should be using inline modifiers,

(?i)foobar
(?x)foobar
(?s)foobar

Or, modifier groups, which is especially handy when only a part of the pattern needs to be modified:

(?i:foobar)
(?x:foobar)
(?s:foobar)

See "Regex Modifiers—Turning them On".


问:
Convert tensor of (row, column) coordinates to boolean mask in TensorFlow
I have an array of 2D coordinates, from which I need to obtain a boolean mask with a known shape, where elements whose index is in the coordinates array is True.

For example, if I had an indices tensor which contains [[0, 0], [1, 1], [2, 2], [0, 1], [1, 2]] and a given shape of (5, 5) I need to get a matrix that is like so:

```<code>[[ True,  True, False, False, False],
 [False,  True,  True, False, False],
 [False, False,  True, False, False],
 [False, False, False, False, False],
 [False, False, False, False, False]]
</code>```

In Numpy I'd do it like so:

```<code>idx = np.array([[0, 0], [1, 1], [2, 2], [0, 1], [1, 2]])
bool_mat = np.zeros(shape=(5, 5), dtype=np.bool)
bool_mat[idx[:, 0], idx[:, 1]] = True
</code>```

However, in TensorFlow you can't assign tensor items like this.

How can I express an equivalent computation in TensorFlow?

答:
You can use tf.tensor_scatter_nd_update(tensor, indices, updates):

```<code>import tensorflow as tf

indices = tf.constant([[0, 0], [1, 1], [2, 2], [0, 1], [1, 2]])
bool_mat = tf.zeros(shape=(5, 5), dtype=tf.bool)

bool_mat = tf.tensor_scatter_nd_update(bool_mat, indices, tf.repeat([True], repeats=tf.shape(indices)[0]))
print(bool_mat)
</code>```
```<code>tf.Tensor(
[[ True  True False False False]
 [False  True  True False False]
 [False False  True False False]
 [False False False False False]
 [False False False False False]], shape=(5, 5), dtype=bool)
</code>```

Body:
I have an array of 2D coordinates, from which I need to obtain a boolean mask with a known shape, where elements whose index is in the coordinates array is True.

For example, if I had an indices tensor which contains [[0, 0], [1, 1], [2, 2], [0, 1], [1, 2]] and a given shape of (5, 5) I need to get a matrix that is like so:

[[ True,  True, False, False, False],
 [False,  True,  True, False, False],
 [False, False,  True, False, False],
 [False, False, False, False, False],
 [False, False, False, False, False]]

In Numpy I'd do it like so:

idx = np.array([[0, 0], [1, 1], [2, 2], [0, 1], [1, 2]])
bool_mat = np.zeros(shape=(5, 5), dtype=np.bool)
bool_mat[idx[:, 0], idx[:, 1]] = True

However, in TensorFlow you can't assign tensor items like this.

How can I express an equivalent computation in TensorFlow?

Body:
You can use tf.tensor_scatter_nd_update(tensor, indices, updates):

import tensorflow as tf

indices = tf.constant([[0, 0], [1, 1], [2, 2], [0, 1], [1, 2]])
bool_mat = tf.zeros(shape=(5, 5), dtype=tf.bool)

bool_mat = tf.tensor_scatter_nd_update(bool_mat, indices, tf.repeat([True], repeats=tf.shape(indices)[0]))
print(bool_mat)

tf.Tensor(
[[ True  True False False False]
 [False  True  True False False]
 [False False  True False False]
 [False False False False False]
 [False False False False False]], shape=(5, 5), dtype=bool)


问:
WazirX API wrapper library
I am new to using APIs and was trying to build a trading bot in python using WazirX exchange's REST API. I am unable to understand how to make API calls using their documentation (Also, is this an example of a good API documentation or of a bad one?). Can anyone point to any python wrapper libraries through which I can execute trades using an API key and secret? I tried searching a lot but couldn't find any Github repository using their API to execute trades (I have seen some using the public endpoints only).

Any help would be appreciated.

答:
Wazirx itself has provided Ruby and Python connectors
There are also 3rd party libraries available which can be used.
https://docs.wazirx.com/#api-third-party-integrations</p>

Title: WazirX API wrapper library


问:
installing puppeteer 2 elastickbeanstalk
I can't deploy puppeteer on aws AWS Elastic Beanstalk.

I'm getting the following error:

Failed to launch the browser process!\n/var/app/current/node_modules/puppeteer/.local-chromium/linux-722234/chrome-linux/chrome: /lib64/libdbus-1.so.3: no version information available (required by /usr/lib64/libatk-bridge-2.0.so.0)\n/var/app/current/node_modules/puppeteer/.local-chromium/linux-722234/chrome-linux/chrome: /lib64/libdbus-1.so.3: no version information available (required by /usr/lib64/libatspi.so.0)\n/var/app/current/node_modules/puppeteer/.local-chromium/linux-722234/chrome-linux/chrome: symbol lookup error: /var/app/current/node_modules/puppeteer/.local-chromium/linux-722234/chrome-linux/chrome: undefined symbol: g_type_class_adjust_private_offset\n\n\nTROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/master/docs/troubleshooting.md\n"

Did anyone had the same issue and managed to solve it?

答:
This worked for me !

Connected remotly via SSH in elastic beanstalk

eb ssh {environment_name}

Install Google Chrome

curl https://intoli.com/install-google-chrome.sh | bash

Source :
https://dev.to/achimoraites/a-developers-guide-to-run-puppeteer-on-elastic-beanstalk-no-ubuntu-linux-4pl5


问:
Flutter: How to convert Object? to Map
I'm using sharedPrefs to store some data. I stored Map like this Map<String, String> map = {'test1':'test2'};. After I save it locally _sharedPrefsStore.write(PrefsKeys.testMapSave, map); When I try to read it var savedMap = _sharedPrefsStore.read(PrefsKeys.testMapSave,valueParser: (value) => value); savedMap is Object?. When printed I get the my saved values {test1 : test2}. It displays my saved variable and key as map, but its Object?. How can I convert this Object? to Map?

答:
Rather than storing your Map as it is, save it as a String using json.encode(yourMap).

To store:

```<code>_sharedPrefsStore.setString(PrefsKeys.testMapSave, json.encode(myMap));
</code>```

To read:
create a method to parse a json decoded map and then

```<code>String myJson = _sharedPrefsStore.getString(PrefsKeys.testMapSave);
Map<String, String> myMap = jsonParsingMethod(myJson);
</code>```

Title: Flutter: How to convert Object? to Map

Body:
Rather than storing your Map as it is, save it as a String using json.encode(yourMap).

To store:

_sharedPrefsStore.setString(PrefsKeys.testMapSave, json.encode(myMap));

To read:
create a method to parse a json decoded map and then

String myJson = _sharedPrefsStore.getString(PrefsKeys.testMapSave);
Map<String, String> myMap = jsonParsingMethod(myJson);


问:
How to create a MSIX package for a Win32 application without an installer
I have a Qt application that I have deployed using windeployqt. Now I have a folder on my disk, which contains a "MyApp.exe" and all the necessary Qt dll files to run this file (without installing anything else). I would now like to create a MSIX package for my application. I have downloaded the MSIX Packaging Tool from the Microsoft Store, running this tool I get the following screen stating that an installer isn't necessary:

After, clicking Next without filling the installer path and then filling the "Package Information" section. You get to this screen

Now, it is unclear to me how does one create a MSIX package without an installer and how can I instead create a package that deploys the content of my folder containing the executable generate by windeployqt. What instructions do I need to follow to correctly use the MSIX Packaging Tool to achieve this?

答:
The MSIX Packaging Tool is intended to be used by IT pros to create MSIX packages for apps where they don't have the source code. It is not designed for developers.

If you have access to your source code, which it sounds you do, then you can use Visual Studio or third-party tools like Advanced Installer to create the MSIX package.

This older SO question has more details: How to build an MSIX from comandline


问:
How to make css counter works with css selector?
I'was trying to use css counter...
This is my css code:

```<code>div.primaries div.entries>div.meaning:first-child:before {
    counter-increment: section;
    content: counter(section);
}
</code>```

and the part of html

```<code><div class="primaries">
<div class="headword entries">
<div class="meaning terms">
<span class="meaning terms text">A collection of items of the ...</span>
</div>
<div class="meaning entries">
<div class="example terms">
<span class="example terms text">an arms <em>cache</em></span>
</div>
</div>
<div class="meaning entries">
<div class="example terms">
<span class="example terms text">a <em>cache</em> of gold coins</span>
</div>
</div>
</div>
<div class="headword entries">
<div class="meaning terms">
<span class="meaning terms text">A hidden or inaccessible ...</span>
</div>
</div>
<div class="headword entries">
<div class="meaning terms">
<span class="meaning terms text">An auxiliary memory from ...</span>
</div>
</div>
</div>
</code>```

I did not use any "counter-reset".
However, every number outputed was 1.
So, why it is always 1?

答:
Add this and I think it will do as you will:

```<code>div.primaries
{
  counter-reset: section;
}
</code>```

See it work at jsfiddle/Larry/ev758/.

Body:
I'was trying to use css counter...
This is my css code:

div.primaries div.entries>div.meaning:first-child:before {
    counter-increment: section;
    content: counter(section);
}

and the part of html

A collection of items of the ...

an arms cache

a cache of gold coins

A hidden or inaccessible ...

An auxiliary memory from ...

I did not use any "counter-reset".
However, every number outputed was 1.
So, why it is always 1?

Body:
Add this and I think it will do as you will:

div.primaries
{
  counter-reset: section;
}

See it work at jsfiddle/Larry/ev758/.


问:
Getting Thread Abort Exception while using Response.Redirect()
I wrote the following piece of code in a page which is under Update Panel.

```<code>protected void myGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
    try
    {
        if (e.CommandName =="EditNames")
        {
            long lSelectedName = Convert.ToInt64(e.CommandArgument);
            Session["SelectedItem"] = lSelectedName;
            Response.Redirect("EditItem.aspx");
        }
        else if (e.CommandName =="DeleteNames")
        {
            long lSelectedName = Convert.ToInt64(e.CommandArgument);
            ValidName.DeleteItem(lSelectedName);

            ScriptManager.RegisterStartupScript(this, GetType(), "Key", "alert('Name deleted sucessfully')", true);
        }
    }
    catch (System.Threading.ThreadAbortException)
    {

    }
    catch (Exception ex)
    {
        Error handling code...
    }
}
</code>```

Here, I am getting a Thread Abort Exception while redirecting. However, I resolved it by using an error handler System.Threading.ThreadAbortException.

But I am unsure why that error came while redirecting. Even though I solved this problem, I would like to know is there any mistake in the way I am coding or is there any way to stop the error firing at all.

Give your inputs...

Note that the page is under AJAX UPDATE PANEL.

答:
```<code>Response.Redirect("Location", false);
</code>```

It works fine without "ThreadAbortException".

Body:
I wrote the following piece of code in a page which is under Update Panel.

protected void myGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
    try
    {
        if (e.CommandName =="EditNames")
        {
            long lSelectedName = Convert.ToInt64(e.CommandArgument);
            Session["SelectedItem"] = lSelectedName;
            Response.Redirect("EditItem.aspx");
        }
        else if (e.CommandName =="DeleteNames")
        {
            long lSelectedName = Convert.ToInt64(e.CommandArgument);
            ValidName.DeleteItem(lSelectedName);

            ScriptManager.RegisterStartupScript(this, GetType(), "Key", "alert('Name deleted sucessfully')", true);
        }
    }
    catch (System.Threading.ThreadAbortException)
    {

    }
    catch (Exception ex)
    {
        Error handling code...
    }
}

Here, I am getting a Thread Abort Exception while redirecting. However, I resolved it by using an error handler System.Threading.ThreadAbortException.

But I am unsure why that error came while redirecting. Even though I solved this problem, I would like to know is there any mistake in the way I am coding or is there any way to stop the error firing at all.

Give your inputs...

Note that the page is under AJAX UPDATE PANEL.

Body:
Response.Redirect("Location", false);

It works fine without "ThreadAbortException".


问:
How to add one line per video with lua when using MPV?
I am logging video files I have played through MPV and while using io I want it to create one line per video. Using the inital options it merley deletes it, and upon going to next video, it won't add new line by default.

I think the script should be close to working. However, this issue stands in my way: "bad argument #1 to '(for generator)' (invalid option). Apparently, something is wrong with the for loop, but I am unable to pinpoint it and would appreciate a pair of hands in solving this problem as I am still learning lua.

Here's the code so far:

```<code>    if not paused then totaltime = totaltime + os.clock() - lasttime end
    message = (totaltime .. "s, " .. timeloaded .. ", " .. filename)
    local file = io.open(logpath, "r+")
    local lines = {}
    if file_exists(logpath) then
        for l in file:lines('L') do
            if not l:find(message, 1, true) then
                lines[#lines+1] = 1
                file.write(message)
                file:close()
         end
     end
   end
end
</code>```

答:
The problem is this line

```<code>for l in file:lines('L') do
</code>```

You're probably running Lua 5.1 which does not support that option 'L' for file:lines

Just use

```<code>for l in file:lines() do
</code>```

Also if you close the file in the generic for loop you'll cause an error for attempting to read from an already closed file.
You should break the loop after closing the file.

It says bad argument to write (FILE* expected, got string).

Replace file.write(message) with file:write(message) which is short for file.write(file, message). This function actually needs two arguments. One is the file itself which is implicitly provided when using the colon syntax.

If you just want to add a line to an existing file you don't need to read and check all  the lines. Just open the file with option 'a' to open it in append mode.

```<code>local file = io.open(logpath, "a")
if file then
   file:write("\nThis is a new line")
   file:close()
end
</code>```

Body:
I am logging video files I have played through MPV and while using io I want it to create one line per video. Using the inital options it merley deletes it, and upon going to next video, it won't add new line by default.

I think the script should be close to working. However, this issue stands in my way: "bad argument #1 to '(for generator)' (invalid option). Apparently, something is wrong with the for loop, but I am unable to pinpoint it and would appreciate a pair of hands in solving this problem as I am still learning lua.

Here's the code so far:

    if not paused then totaltime = totaltime + os.clock() - lasttime end
    message = (totaltime .. "s, " .. timeloaded .. ", " .. filename)
    local file = io.open(logpath, "r+")
    local lines = {}
    if file_exists(logpath) then
        for l in file:lines('L') do
            if not l:find(message, 1, true) then
                lines[#lines+1] = 1
                file.write(message)
                file:close()
         end
     end
   end
end

Body:
The problem is this line

for l in file:lines('L') do

You're probably running Lua 5.1 which does not support that option 'L' for file:lines

Just use

for l in file:lines() do

Also if you close the file in the generic for loop you'll cause an error for attempting to read from an already closed file.
You should break the loop after closing the file.

It says bad argument to write (FILE* expected, got string).

Replace file.write(message) with file:write(message) which is short for file.write(file, message). This function actually needs two arguments. One is the file itself which is implicitly provided when using the colon syntax.

If you just want to add a line to an existing file you don't need to read and check all  the lines. Just open the file with option 'a' to open it in append mode.

local file = io.open(logpath, "a")
if file then
   file:write("\nThis is a new line")
   file:close()
end


问:
How to install Go in alpine linux
I am trying to install Go inside an Alpine Docker image. For that I downloaded tar file from here inside my alpine docker image, untar it using following command:

tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz

exported PATH to have go binary as:

export PATH=$PATH:/usr/local/go/bin

However, when I say go version  then it says that sh: go: not found. I am quite new to alpine. Does anyone know, what I am missing here?

Steps to reproduce-

```<code>$ docker run -it alpine sh
$ wget https://dl.google.com/go/go1.10.3.linux-amd64.tar.gz
$ tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
$ go version
</code>```

答:
Just in case someone encounters the same issue with me.

I was able to install the golang1.17.6 ion Alpine3.15 by following @Yogesh Jilhawar 's answer.

When I ran the command apk add --no-cache --virtual .build-deps bash gcc musl-dev openssl go, I got

```<code>ERROR: unable to select packages:
  go (no such packages):
    required by: world[go]
</code>```

Then I tried to install the "gcc-go", it installs. After that, I can build the golang from the source successfully.

Title: How to install Go in alpine linux

Body:
I am trying to install Go inside an Alpine Docker image. For that I downloaded tar file from here inside my alpine docker image, untar it using following command:

tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz

exported PATH to have go binary as:

export PATH=$PATH:/usr/local/go/bin

However, when I say go version  then it says that sh: go: not found. I am quite new to alpine. Does anyone know, what I am missing here?

Steps to reproduce-

$ docker run -it alpine sh
$ wget https://dl.google.com/go/go1.10.3.linux-amd64.tar.gz
$ tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
$ go version

Body:
Just in case someone encounters the same issue with me.

I was able to install the golang1.17.6 ion Alpine3.15 by following @Yogesh Jilhawar 's answer.

When I ran the command apk add --no-cache --virtual .build-deps bash gcc musl-dev openssl go, I got

ERROR: unable to select packages:
  go (no such packages):
    required by: world[go]

Then I tried to install the "gcc-go", it installs. After that, I can build the golang from the source successfully.


问:
Mongodb sort and group by
I'm not sure that my question is correct, but it seems so:

I have a set of rows in my Mongodb, like:

```<code>[{'_id': '5b4c9aa7ddc752c1f5844315',
  'ccode': 'RU',
  'date': '2018-07-16T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 4,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}},
 {'_id': '5b4cad0dddc752c1f5844322',
  'ccode': 'US',
  'date': '2018-07-16T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 4,
            'registered': 2,
            'regs_age1': 2,
            'regs_male': 2}},
 {'_id': '5bd88204af4c814883a414b2',
  'ccode': 'US',
  'date': '2018-10-30T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 2,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}},
 {'_id': '5bd88204af4c814883a414b3',
  'ccode': 'RU',
  'date': '2018-10-30T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 2,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}}]

</code>```

And I want to sort them by date and combine because for the same date there are multiple rows from different countries.
So the result should look something like ...

```<code>[{'2018-07-16T00:00:00.000Z': [{'_id': '5b4c9aa7ddc752c1f5844315',
                                'ccode': 'RU',
                                'date': '2018-07-16T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 4,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}},
                               {'_id': '5b4cad0dddc752c1f5844322',
                                'ccode': 'US',
                                'date': '2018-07-16T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 4,
                                          'registered': 2,
                                          'regs_age1': 2,
                                          'regs_male': 2}}]},
 {'2018-10-30T00:00:00.000Z': [{'_id': '5bd88204af4c814883a414b2',
                                'ccode': 'US',
                                'date': '2018-10-30T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 2,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}},
                               {'_id': '5bd88204af4c814883a414b3',
                                'ccode': 'RU',
                                'date': '2018-10-30T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 2,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}}]}]
</code>```

I tried:

```<code>    db.getCollection('daily_stats').aggregate([
        {'$match': some_condition},
        {'$group': {'ccode': 1}},  # ccode or date?
        {'$sort': {"date": 1}},
    ])
</code>```

But got an error
The field * must be an accumulator object

I googled the error, it's pretty clear, but not seems that related to my case. I don't need any sum, avg, etc functions

答:
When using $group, you need an _id

From the docs

```<code>{
  $group:
    {
      _id: <expression>, // Group By Expression
      <field1>: { <accumulator1> : <expression1> },
      ...
    }
 }
</code>```

In your case...

```<code>   db.getCollection('daily_stats').aggregate([
        {'$match': some_condition},
        {'$group': {
               '_id': "$ccode",
               'rates': { $addToSet: '$rates' },
               'date': { $first: '$date' }
        }},
        {'$sort': {"date": 1}},
        {'$project: { "_id": 0, "country": "$_id", "rates": 1, "date": 1 }}
    ])
</code>```

Playground: https://mongoplayground.net/p/B31XLS9p-6W

Title: Mongodb sort and group by

Body:
I'm not sure that my question is correct, but it seems so:

I have a set of rows in my Mongodb, like:

[{'_id': '5b4c9aa7ddc752c1f5844315',
  'ccode': 'RU',
  'date': '2018-07-16T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 4,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}},
 {'_id': '5b4cad0dddc752c1f5844322',
  'ccode': 'US',
  'date': '2018-07-16T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 4,
            'registered': 2,
            'regs_age1': 2,
            'regs_male': 2}},
 {'_id': '5bd88204af4c814883a414b2',
  'ccode': 'US',
  'date': '2018-10-30T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 2,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}},
 {'_id': '5bd88204af4c814883a414b3',
  'ccode': 'RU',
  'date': '2018-10-30T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 2,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}}]

And I want to sort them by date and combine because for the same date there are multiple rows from different countries.
So the result should look something like ...

[{'2018-07-16T00:00:00.000Z': [{'_id': '5b4c9aa7ddc752c1f5844315',
                                'ccode': 'RU',
                                'date': '2018-07-16T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 4,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}},
                               {'_id': '5b4cad0dddc752c1f5844322',
                                'ccode': 'US',
                                'date': '2018-07-16T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 4,
                                          'registered': 2,
                                          'regs_age1': 2,
                                          'regs_male': 2}}]},
 {'2018-10-30T00:00:00.000Z': [{'_id': '5bd88204af4c814883a414b2',
                                'ccode': 'US',
                                'date': '2018-10-30T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 2,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}},
                               {'_id': '5bd88204af4c814883a414b3',
                                'ccode': 'RU',
                                'date': '2018-10-30T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 2,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}}]}]

I tried:

    db.getCollection('daily_stats').aggregate([
        {'$match': some_condition},
        {'$group': {'ccode': 1}},  # ccode or date?
        {'$sort': {"date": 1}},
    ])

But got an error
The field * must be an accumulator object

I googled the error, it's pretty clear, but not seems that related to my case. I don't need any sum, avg, etc functions

Body:
When using $group, you need an _id

From the docs

{
  $group:
    {
      _id: <expression>, // Group By Expression
      <field1>: { <accumulator1> : <expression1> },
      ...
    }
 }

In your case...

   db.getCollection('daily_stats').aggregate([
        {'$match': some_condition},
        {'$group': {
               '_id': "$ccode",
               'rates': { $addToSet: '$rates' },
               'date': { $first: '$date' }
        }},
        {'$sort': {"date": 1}},
        {'$project: { "_id": 0, "country": "$_id", "rates": 1, "date": 1 }}
    ])

Playground: https://mongoplayground.net/p/B31XLS9p-6W


问:
log4j and weblogic: duplicate log messages
I use log4j for logging in my project. Here is it's sample setup:

```<code>public class MyClass {
  private final Logger logger = Logger.getLogger(MyClass.class);

  public MyClass() {
    BasicConfigurator.configure();
    Logger.getLogger(MyClass.class).setLevel(Level.INFO);
  }

  ...

}
</code>```

The problem is that on each next logger call it duplicates log messages (I mean on first call there is only 1 message, on second call there are 2 same messages, then there are 3 of them and so on). It seems that each time new logger's instance is created and used with all old instances.

How to avoid this problem?
Thanks.

UPP. Tried to make it static,but it doesn't work anyway. I still get multiple log messages. Any ideas? Probably some Weblogic specific stuff?

答:
try setting additivity false programmatically or in config.

```<code>    Logger.getLogger(MyClass.class).setAdditivity(false);
</code>```

To me, that did the trick when I set it in log4j.xml

```<code><logger name="com.stackoverflow.answers.gnat" additivity="false">
    <!-- note additivity value set above -->
    <level value="INFO"/>
    <appender-ref ref="knowledge"/>
    <appender-ref ref="reputation"/>
</logger>
</code>```

Body:
I use log4j for logging in my project. Here is it's sample setup:

public class MyClass {
  private final Logger logger = Logger.getLogger(MyClass.class);

  public MyClass() {
    BasicConfigurator.configure();
    Logger.getLogger(MyClass.class).setLevel(Level.INFO);
  }

  ...

}

The problem is that on each next logger call it duplicates log messages (I mean on first call there is only 1 message, on second call there are 2 same messages, then there are 3 of them and so on). It seems that each time new logger's instance is created and used with all old instances.

How to avoid this problem?
Thanks.

UPP. Tried to make it static,but it doesn't work anyway. I still get multiple log messages. Any ideas? Probably some Weblogic specific stuff?

Body:
try setting additivity false programmatically or in config.

    Logger.getLogger(MyClass.class).setAdditivity(false);

To me, that did the trick when I set it in log4j.xml

<logger name="com.stackoverflow.answers.gnat" additivity="false">
    <!-- note additivity value set above -->
    <level value="INFO"/>
    <appender-ref ref="knowledge"/>
    <appender-ref ref="reputation"/>
</logger>


问:
Alchemy Error: what is the meaning of this -> maxFeePerGas cannot be less than maxPriorityFeePerGas
I am following this tutorial -> https://docs.alchemy.com/alchemy/tutorials/sending-txs
The only difference is that i am trying to eth to ropsten test faucet

```<code>async function main() {
  require('dotenv').config();
  const { API_URL, PRIVATE_KEY } = process.env;
  const { createAlchemyWeb3 } = require('@alch/alchemy-web3');
  const web3 = createAlchemyWeb3(API_URL);
  const myAddress = 'xxxx'; //TODO: replace this address with your own public address

  const nonce = await web3.eth.getTransactionCount(myAddress, 'latest'); // nonce starts counting from 0
  console.log(nonce);
  const transaction = {
    to: '0x9f1099b301716892d17d576387027cE5B73E2c20', // faucet address to return eth
    value: 100,
    gas: 30000,
    maxFeePerGas: 1000000108,
    nonce: nonce,
    // optional data field to send message or execute smart contract
  };

  const signedTx = await web3.eth.accounts.signTransaction(
    transaction,
    PRIVATE_KEY
  );

  web3.eth.sendSignedTransaction(
    signedTx.rawTransaction,
    function (error, hash) {
      if (!error) {
        console.log(
          ' The hash of your transaction is: ',
          hash,
          "\n Check Alchemy's Mempool to view the status of your transaction!"
        );
      } else {
        console.log(
          '❗Something went wrong while submitting your transaction:',
          error
        );
      }
    }
  );
}

main();
</code>```

When i am running code i am getting this error -> Error: maxFeePerGas cannot be less than maxPriorityFeePerGas (The total must be the larger of the two) (tx type=2 hash=not available (unsigned) nonce=23 value=100 signed=false hf=london maxFeePerGas=1000000108 maxPriorityFeePerGas=2500000000)

Update : if i replace maxFeePerGas with maxPriorityFeePerGas this works

What am i missing conceptually?

答:
It seems that the default value of maxPriorityFeePerGas was changed from 1.0 gwei to 2.5 gwei due to some incentive mechanism for miners.

Follow this issue for more detailed information.

Hence, if we don't set the maxPriorityFeePerGas parameter, the default value 2.5 gwei would larger than maxFeePerGas, which is 1.0 gwei we set and violate the rule.

We can solve this issue by either setting maxPriorityFeePerGas smaller than 1.0 gwei or changing maxFeePerGas larger than 2.5 gwei.

Body:
I am following this tutorial -> https://docs.alchemy.com/alchemy/tutorials/sending-txs
The only difference is that i am trying to eth to ropsten test faucet

async function main() {
  require('dotenv').config();
  const { API_URL, PRIVATE_KEY } = process.env;
  const { createAlchemyWeb3 } = require('@alch/alchemy-web3');
  const web3 = createAlchemyWeb3(API_URL);
  const myAddress = 'xxxx'; //TODO: replace this address with your own public address

  const nonce = await web3.eth.getTransactionCount(myAddress, 'latest'); // nonce starts counting from 0
  console.log(nonce);
  const transaction = {
    to: '0x9f1099b301716892d17d576387027cE5B73E2c20', // faucet address to return eth
    value: 100,
    gas: 30000,
    maxFeePerGas: 1000000108,
    nonce: nonce,
    // optional data field to send message or execute smart contract
  };

  const signedTx = await web3.eth.accounts.signTransaction(
    transaction,
    PRIVATE_KEY
  );

  web3.eth.sendSignedTransaction(
    signedTx.rawTransaction,
    function (error, hash) {
      if (!error) {
        console.log(
          ' The hash of your transaction is: ',
          hash,
          "\n Check Alchemy's Mempool to view the status of your transaction!"
        );
      } else {
        console.log(
          '❗Something went wrong while submitting your transaction:',
          error
        );
      }
    }
  );
}

main();

When i am running code i am getting this error -> Error: maxFeePerGas cannot be less than maxPriorityFeePerGas (The total must be the larger of the two) (tx type=2 hash=not available (unsigned) nonce=23 value=100 signed=false hf=london maxFeePerGas=1000000108 maxPriorityFeePerGas=2500000000)

Update : if i replace maxFeePerGas with maxPriorityFeePerGas this works

What am i missing conceptually?


问:
How to enable dark mode for markdown-it-vue plugin with vuetify
I'm trying to show some documentation in my Vue application. Since they are based on markdown format, I have already included the markdown-it-vue plugin.

However, the plugin does not support the vuetify dark mode. Is there any way to support that? Below is a minimal example. I want to highlight the text in white and the table background in gray. Maybe the markdown-it-vue.css needs to be changed, but I'm not sure how to do that. Thank you in advance!

const vm = new Vue({
  el: "#app",
  data() {
    return {
      content: "This needs to be white\n| Item | Price | # In stock |\n|--------------|-----------|------------|\n| Juicy Apples | 1.99 | *7* |\n| Bananas      | **1.89** | 5234 |"
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/vuetify@1.2.2/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.2.2/dist/vuetify.min.js"></script>
<script src="https://unpkg.com/markdown-it-vue@1.1.6/dist/markdown-it-vue.umd.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/markdown-it-vue@1.1.6/dist/markdown-it-vue.css">

<div id="app">
  <v-app :dark="true">
    <markdown-it-vue :content="content"></markdown-it-vue>
  </v-app>
</div></code>```

答:
markdown-it-vue's contents can be styled with CSS, so you can apply your own dark theme to the Markdown contents. Vuetify sets the .theme--dark class on the app root element, and the markdown-it-vue's element has the .markdown-body class.

On .theme--dark .markdown-body, apply a color with !important to override Vuetify's theme:

.theme--dark .markdown-body {
  color: white !important;
}
```
<p>Also on all its table children (i.e., on <code>table *</code>), apply a <code>background</code> color::</p>
<pre class="lang-css prettyprint-override"><code>.theme--dark .markdown-body table * {
  background: gray;
}
</code>```

const vm = new Vue({
  el: "#app",
  data() {
    return {
      dark: true,
      content: "This needs to be white\n| Item | Price | # In stock |\n|--------------|-----------|------------|\n| Juicy Apples | 1.99 | *7* |\n| Bananas      | **1.89** | 5234 |"
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.theme--dark .markdown-body {
  color: white !important;
}

.theme--dark .markdown-body table * {
  background: gray;
}</code>```

<link href="https://cdn.jsdelivr.net/npm/vuetify@1.2.2/dist/vuetify.min.css" rel="stylesheet" />

<link rel="stylesheet" href="https://unpkg.com/markdown-it-vue@1.1.6/dist/markdown-it-vue.css">

  <v-app :dark="dark">
    <v-btn @click="dark = !dark">Toggle dark mode</v-btn>
    <markdown-it-vue :content="content"></markdown-it-vue>
  </v-app>

```

Body:
I'm trying to show some documentation in my Vue application. Since they are based on markdown format, I have already included the markdown-it-vue plugin.

However, the plugin does not support the vuetify dark mode. Is there any way to support that? Below is a minimal example. I want to highlight the text in white and the table background in gray. Maybe the markdown-it-vue.css needs to be changed, but I'm not sure how to do that. Thank you in advance!

const vm = new Vue({
  el: "#app",
  data() {
    return {
      content: "This needs to be white\n| Item | Price | # In stock |\n|--------------|-----------|------------|\n| Juicy Apples | 1.99 | *7* |\n| Bananas      | **1.89** | 5234 |"
    }
  }
})

<link href="https://cdn.jsdelivr.net/npm/vuetify@1.2.2/dist/vuetify.min.css" rel="stylesheet" />

<link rel="stylesheet" href="https://unpkg.com/markdown-it-vue@1.1.6/dist/markdown-it-vue.css">

  <v-app :dark="true">
    <markdown-it-vue :content="content"></markdown-it-vue>
  </v-app>

Body:
markdown-it-vue's contents can be styled with CSS, so you can apply your own dark theme to the Markdown contents. Vuetify sets the .theme--dark class on the app root element, and the markdown-it-vue's element has the .markdown-body class.

On .theme--dark .markdown-body, apply a color with !important to override Vuetify's theme:

.theme--dark .markdown-body {
  color: white !important;
}

Also on all its table children (i.e., on table *), apply a background color::

.theme--dark .markdown-body table * {
  background: gray;
}

const vm = new Vue({
  el: "#app",
  data() {
    return {
      dark: true,
      content: "This needs to be white\n| Item | Price | # In stock |\n|--------------|-----------|------------|\n| Juicy Apples | 1.99 | *7* |\n| Bananas      | **1.89** | 5234 |"
    }
  }
})

.theme--dark .markdown-body {
  color: white !important;
}

.theme--dark .markdown-body table * {
  background: gray;
}

<link href="https://cdn.jsdelivr.net/npm/vuetify@1.2.2/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.2.2/dist/vuetify.min.js"></script>
<script src="https://unpkg.com/markdown-it-vue@1.1.6/dist/markdown-it-vue.umd.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/markdown-it-vue@1.1.6/dist/markdown-it-vue.css">

<div id="app">
  <v-app :dark="dark">
    <v-btn @click="dark = !dark">Toggle dark mode</v-btn>
    <markdown-it-vue :content="content"></markdown-it-vue>
  </v-app>
</div>


问:
Yet another ClickOnce GAC reference question
I am trying to deploy an update and all of a sudden I am getting the message about log4net.dll version 1.2.10.0 needing to be installed in the GAC.  This is version number 38 and I have property set to Copy Local = true, and set the value to Include on the Application Files setting.  I even gave up and registered the log4net.dll into the GAC on the target machine.  Funny thing is this update rolls out just fine on two other computers.

I am not sure what might have changed since the last update?

cheers

bob

edit: I found this entry in the manifest file for log4net.  It is not in any of the other manifest files for other applications where I use log4net?  Yet if I try to modify the file, clickonce knows and says the install is corrupted.

```<code><dependency>
<dependentAssembly dependencyType="preRequisite" allowDelayedBinding="true">
  <assemblyIdentity name="log4net" version="1.2.10.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="x86" />
</dependentAssembly>
</code>```

答:
My best guess would be that you have two dependencies to log4net.dll.
On comes directly from your project, which has it referenced, and one is an implicit reference from another library (typically a library compiled for .net 1.1, in my case it happened with Crystal Reports). My guess is that this two references point to different versions.

You could try leaving log4net installed on your target machine, and Exclude it from Application Files in the ClickOnce project. This way it will NOT be needed by the ClickOnce installation (but it's not clear to me what will happen once installed, when trying to run the application).

If it doesn't work or if it fails at run-time, then maybe setting Copy Local and Specific Version to false in the project that references it would do the trick.
But then log4net in the GAC will be a prerequisite for the application to run, which means you need to install .NET 1.1 (or 2.0/3.5 full). 350MB of prerequisite is quite heavy...

Your idea of changing your manifest file after publishing could
work. To avoid ClickOnce saying the installation is corrupted, you
need to resign the publication using MAGE (Manifest Editing and
Generation Tool, normally available from the Start Menu group from
Visual Studio). I don't know what will happen if your application
really needs log4net at run-time and cannot find it.

Body:
I am trying to deploy an update and all of a sudden I am getting the message about log4net.dll version 1.2.10.0 needing to be installed in the GAC.  This is version number 38 and I have property set to Copy Local = true, and set the value to Include on the Application Files setting.  I even gave up and registered the log4net.dll into the GAC on the target machine.  Funny thing is this update rolls out just fine on two other computers.

I am not sure what might have changed since the last update?

cheers

bob

edit: I found this entry in the manifest file for log4net.  It is not in any of the other manifest files for other applications where I use log4net?  Yet if I try to modify the file, clickonce knows and says the install is corrupted.

<dependency>
<dependentAssembly dependencyType="preRequisite" allowDelayedBinding="true">
  <assemblyIdentity name="log4net" version="1.2.10.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="x86" />
</dependentAssembly>


问:
unsupported operand type(s) for -: 'decimal.Decimal' and 'float' in Python 3
I am getting this issue unsupported operand type(s) for -: 'decimal.Decimal' and 'float'

Here is my models.py

```<code>def _convert(self,from_currency, to_currency, price):
        custom_rate_obj = self.quote.client.custom_rates.filter(currency=to_currency).first()
        if custom_rate_obj is None or custom_rate_obj.exchange_rate in (0, None):
            custom_rate_obj = ExchangeRates.objects.latest('created')
        return custom_rate_obj.convert(from_currency, to_currency, price)

    def get_margin(self):
        if self.cost_price:
            cost_price = self.cost_price
            unit_price = self._convert(self.currency, self.cost_currency, self.unit_price)
            if unit_price:
                return ((unit_price - float(cost_price))/unit_price) * 100
</code>```

How can i solve my issue

答:
Change the unit_price to float as well.

```<code> return ((float(unit_price) - float(cost_price))/unit_price) * 100
</code>```

And always use typing in python 3 t avoid such errors.

```<code>def _convert(self,from_currency: str, to_currency : str, price: float) => float:
</code>```

Body:
I am getting this issue unsupported operand type(s) for -: 'decimal.Decimal' and 'float'

Here is my models.py

def _convert(self,from_currency, to_currency, price):
        custom_rate_obj = self.quote.client.custom_rates.filter(currency=to_currency).first()
        if custom_rate_obj is None or custom_rate_obj.exchange_rate in (0, None):
            custom_rate_obj = ExchangeRates.objects.latest('created')
        return custom_rate_obj.convert(from_currency, to_currency, price)

    def get_margin(self):
        if self.cost_price:
            cost_price = self.cost_price
            unit_price = self._convert(self.currency, self.cost_currency, self.unit_price)
            if unit_price:
                return ((unit_price - float(cost_price))/unit_price) * 100

How can i solve my issue

Body:
Change the unit_price to float as well.

 return ((float(unit_price) - float(cost_price))/unit_price) * 100

And always use typing in python 3 t avoid such errors.

def _convert(self,from_currency: str, to_currency : str, price: float) => float:


问:
how can i use laravel code in java script
i want to translate button name in javascript by write laravel code

```<code>$(document).on('click', '.leave-edit-btn', function() {
        $(this).removeClass('leave-edit-btn').addClass('btn btn-white leave-cancel-btn').text("{{ __('trans.Edit') }}");
</code>```

how can i do this?

(copied from comment):
this my code when i click on button no translation run

```<code>@section('scripts')
<script>
$(document).on('click', '.leave-edit-btn', function() {
  $(this).removeClass('leave-edit-btn').addClass('btn btn-white leave-cancel-btn').text({{ __('trans.Save') }});
});
</script>
@endsection
</code>```

答:
based on the comments, are you sure your file is *.blade.php not just *.php? and it need to be under resources/view and use it as a view

are you sure your js is actually works? like the .leave-edit-btn is exists

You may try this btw

@section('scripts')

@endsection
```

Body:
i want to translate button name in javascript by write laravel code

$(document).on('click', '.leave-edit-btn', function() {
        $(this).removeClass('leave-edit-btn').addClass('btn btn-white leave-cancel-btn').text("{{ __('trans.Edit') }}");

how can i do this?

(copied from comment):
this my code when i click on button no translation run

@section('scripts')

@endsection

Body:
based on the comments, are you sure your file is *.blade.php not just *.php? and it need to be under resources/view and use it as a view

are you sure your js is actually works? like the .leave-edit-btn is exists

You may try this btw

@section('scripts')
<script>
$(document).ready(()=>{
  $(document).on('click', '.leave-edit-btn', function() {
    $(this).removeClass('leave-edit-btn').addClass('btn btn-white leave-cancel-btn').text(@json(__('trans.Save')));
  });
});
</script>
@endsection


问:
Eslint not showing warnings - React
On my new project, ESLint is not outputting warnings like before, I'm using VSCode. If I have an unsed var somewhere in my code, it doesn't show the warning in the  terminal output anymore. Only in the problem tab.

Here's my eslint config file:

.eslintrc.json

```<code>{
  "env": {
      "browser": true,
      "es6": true
  },
  "extends": [
      "plugin:react/recommended",
      "airbnb-typescript",
      "plugin:@typescript-eslint/recommended",
      "plugin:@typescript-eslint/eslint-recommended",
      "prettier/@typescript-eslint",
      "plugin:prettier/recommended"
  ],
  "globals": {
      "Atomics": "readonly",
      "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
      "ecmaFeatures": {
          "jsx": true
      },
      "ecmaVersion": 2018,
      "sourceType": "module",
      "project": "./tsconfig.json"
  },
  "plugins": [
      "react",
      "react-hooks",
      "@typescript-eslint",
      "prettier"
  ],
  "rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks":"error",
    "react-hooks/exhaustive-deps": "warn",
    "camelcase": "off",
    "@typescript-eslint/camelcase": "off",
    "react/jsx-filename-extension": [1, {"extensions": [".tsx"]}],
    "import/prefer-default-export": "off",
    "react/jsx-one-expression-per-line": "off",
    "react/jsx-props-no-spreading": "off",
    "react/prop-types": "off",
    "no-unused-expressions": "off",
    "@typescript-eslint/no-unused-vars": "error",
    "@typescript-eslint/explicit-function-return-type": [
      "error",
      {
        "allowExpressions": true
      }
    ],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "ts": "never",
        "tsx": "never"
      }
    ],
    "semi":"off"
  },
  "settings": {
    "import/resolver": {
      "typescript": {}
    }
  }
}

</code>```

and Here is my package.json devDependencies:

package.json

```<code>  "dependencies": {
    ...,
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "^4.0.2"
  }
  "devDependencies": {
    "@types/react-router-dom": "^5.1.7",
    "@types/styled-components": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.14.2",
    "@typescript-eslint/parser": "^4.14.2",
    "eslint": "^7.19.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-config-prettier": "^7.2.0",
    "eslint-import-resolver-typescript": "^2.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-react": "^7.22.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "husky": "^5.0.8",
    "prettier": "^2.2.1",
    "prettier-eslint-cli": "^5.0.0",
    "typescript": "^4.1.3"
  }
</code>```

答:
I have installed in my project all this eslint plugins:

```<code>"eslint": "^4.19.1"
"eslint-config-airbnb-base": "^12.1.0"
"eslint-import-resolver-babel-plugin-root-import": "^1.1.1"
"eslint-import-resolver-webpack": "^0.9.0"
"eslint-loader": "^2.2.1"
"eslint-plugin-import": "^2.19.1"
"eslint-plugin-jest": "^21.15.1"
"eslint-plugin-react": "^7.17.0"
</code>```

And I have this config in my .eslintrc.js

```<code>const PATHS = require('./../paths');
const rootImportRegex = '~/(components|chains|output-types|utilities)/';

module.exports = {
  parser: 'babel-eslint',
  env: {
    browser: true,
    commonjs: true,
    es6: true,
    node: true
  },
  settings: {
    'import/resolver': {
      webpack: {
        config: `${PATHS.config}/webpack.base.js`
      }
    },
  },
  extends: [
    'airbnb-base',
    'plugin:react/recommended',
    'plugin:jest/recommended'
  ],
  parserOptions: {
    sourceType: 'module',
    ecmaVersion: 6,
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    'max-len': [2, 120, 2],
    'import/no-extraneous-dependencies': ['error', { 'devDependencies': true }],
    'import/no-unresolved': ['error', { ignore: [rootImportRegex] }],
    'import/extensions': ['warning', 'ignorePackages']
  }
};
</code>```

Title: Eslint not showing warnings - React

Body:
On my new project, ESLint is not outputting warnings like before, I'm using VSCode. If I have an unsed var somewhere in my code, it doesn't show the warning in the  terminal output anymore. Only in the problem tab.

Here's my eslint config file:

.eslintrc.json

{
  "env": {
      "browser": true,
      "es6": true
  },
  "extends": [
      "plugin:react/recommended",
      "airbnb-typescript",
      "plugin:@typescript-eslint/recommended",
      "plugin:@typescript-eslint/eslint-recommended",
      "prettier/@typescript-eslint",
      "plugin:prettier/recommended"
  ],
  "globals": {
      "Atomics": "readonly",
      "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
      "ecmaFeatures": {
          "jsx": true
      },
      "ecmaVersion": 2018,
      "sourceType": "module",
      "project": "./tsconfig.json"
  },
  "plugins": [
      "react",
      "react-hooks",
      "@typescript-eslint",
      "prettier"
  ],
  "rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks":"error",
    "react-hooks/exhaustive-deps": "warn",
    "camelcase": "off",
    "@typescript-eslint/camelcase": "off",
    "react/jsx-filename-extension": [1, {"extensions": [".tsx"]}],
    "import/prefer-default-export": "off",
    "react/jsx-one-expression-per-line": "off",
    "react/jsx-props-no-spreading": "off",
    "react/prop-types": "off",
    "no-unused-expressions": "off",
    "@typescript-eslint/no-unused-vars": "error",
    "@typescript-eslint/explicit-function-return-type": [
      "error",
      {
        "allowExpressions": true
      }
    ],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "ts": "never",
        "tsx": "never"
      }
    ],
    "semi":"off"
  },
  "settings": {
    "import/resolver": {
      "typescript": {}
    }
  }
}

and Here is my package.json devDependencies:

package.json

  "dependencies": {
    ...,
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "^4.0.2"
  }
  "devDependencies": {
    "@types/react-router-dom": "^5.1.7",
    "@types/styled-components": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.14.2",
    "@typescript-eslint/parser": "^4.14.2",
    "eslint": "^7.19.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-config-prettier": "^7.2.0",
    "eslint-import-resolver-typescript": "^2.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-react": "^7.22.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "husky": "^5.0.8",
    "prettier": "^2.2.1",
    "prettier-eslint-cli": "^5.0.0",
    "typescript": "^4.1.3"
  }

Body:
I have installed in my project all this eslint plugins:

"eslint": "^4.19.1"
"eslint-config-airbnb-base": "^12.1.0"
"eslint-import-resolver-babel-plugin-root-import": "^1.1.1"
"eslint-import-resolver-webpack": "^0.9.0"
"eslint-loader": "^2.2.1"
"eslint-plugin-import": "^2.19.1"
"eslint-plugin-jest": "^21.15.1"
"eslint-plugin-react": "^7.17.0"

And I have this config in my .eslintrc.js

const PATHS = require('./../paths');
const rootImportRegex = '~/(components|chains|output-types|utilities)/';

module.exports = {
  parser: 'babel-eslint',
  env: {
    browser: true,
    commonjs: true,
    es6: true,
    node: true
  },
  settings: {
    'import/resolver': {
      webpack: {
        config: `${PATHS.config}/webpack.base.js`
      }
    },
  },
  extends: [
    'airbnb-base',
    'plugin:react/recommended',
    'plugin:jest/recommended'
  ],
  parserOptions: {
    sourceType: 'module',
    ecmaVersion: 6,
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    'max-len': [2, 120, 2],
    'import/no-extraneous-dependencies': ['error', { 'devDependencies': true }],
    'import/no-unresolved': ['error', { ignore: [rootImportRegex] }],
    'import/extensions': ['warning', 'ignorePackages']
  }
};


问:
How to move files in Xcode without causing "Cannot find 'FileName' in Scope"?
I want to make my project more organized, so I created new groups and dragged files into those groups. I am doing all of this in Xcode, not finder or terminal. However, now, Xcode shows "Cannot find 'FileName' in Scope" errors next to references to classes in those files.

How do I solve this problem?

I tried building the project and cleaning the build folder.

答:
I found some "hack" to fix it.

Lets say you wanna move folder Models to your project. Open AppCode and create Model group using IDE tools. Then open XCode, select Model folder and perform Add files to "Model" action. It worked out in my case.

From my understanding, the problem is with forlders, not with files.


问:
ThreeJS animate object to multiple positions using lerp
I'm trying to animate the movement of a sphere along a predefined set of vertices.
I'm able to animate from one point to another using the below code

```<code>function animate() {
  requestAnimationFrame(animate)
  sphere.position.lerp(new THREE.Vector3(100, 2, 0), 0.05)
  render()
}
function render() {
  renderer.render(scene, camera)
}
animate()
</code>```

this works for a single animation from initial position to (100, 2, 0). How do i keep on adding vertices, so that it will be animated in sequence.

答:
You can animate a mesh along a path with plain three.js by defining a curve based on your sequence of points and then using this curve for animation.

let camera, scene, renderer, clock;

let mesh, path;

const duration = 10;
let time = 0;

init();
animate();

function init() {

  camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
  camera.position.set( 3, 2, 3 );

  scene = new THREE.Scene();

  renderer = new THREE.WebGLRenderer( { antialias: true } );
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  clock = new THREE.Clock();

  const controls = new THREE.OrbitControls( camera, renderer.domElement );

  const geometry = new THREE.BoxGeometry();
  const material = new THREE.MeshNormalMaterial();
  mesh = new THREE.Mesh( geometry, material );
  scene.add( mesh );

  scene.add( new THREE.AxesHelper( 2 ) );

  // points and path

  const points = [
    new THREE.Vector3( 0, 0, 0 ),
    new THREE.Vector3( 1, 2, - 2 ),
    new THREE.Vector3( 2, 2, - 0.5 ),
    new THREE.Vector3( 2, 1, - 2 )
    ];

  path = new THREE.CatmullRomCurve3( points, true );

  // visualize the path

  const lineGeometry = new THREE.BufferGeometry().setFromPoints( path.getPoints( 32 ) );
  const lineMaterial = new THREE.LineBasicMaterial();
  const line = new THREE.Line( lineGeometry, lineMaterial );
  scene.add( line );

}

function animate() {

  requestAnimationFrame( animate );

  time += clock.getDelta();

  const t = Math.min( time / duration, 1 );

  if ( t === 1 ) time = 0;

  path.getPointAt( t, mesh.position ); // animating

  renderer.render( scene, camera );

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
}</code>```

```

Body:
I'm trying to animate the movement of a sphere along a predefined set of vertices.
I'm able to animate from one point to another using the below code

function animate() {
  requestAnimationFrame(animate)
  sphere.position.lerp(new THREE.Vector3(100, 2, 0), 0.05)
  render()
}
function render() {
  renderer.render(scene, camera)
}
animate()

this works for a single animation from initial position to (100, 2, 0). How do i keep on adding vertices, so that it will be animated in sequence.

Body:
You can animate a mesh along a path with plain three.js by defining a curve based on your sequence of points and then using this curve for animation.

let camera, scene, renderer, clock;

let mesh, path;

const duration = 10;
let time = 0;

init();
animate();

function init() {

  camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
  camera.position.set( 3, 2, 3 );

  scene = new THREE.Scene();

  renderer = new THREE.WebGLRenderer( { antialias: true } );
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  clock = new THREE.Clock();

  const controls = new THREE.OrbitControls( camera, renderer.domElement );

  const geometry = new THREE.BoxGeometry();
  const material = new THREE.MeshNormalMaterial();
  mesh = new THREE.Mesh( geometry, material );
  scene.add( mesh );

  scene.add( new THREE.AxesHelper( 2 ) );

  // points and path

  const points = [
    new THREE.Vector3( 0, 0, 0 ),
    new THREE.Vector3( 1, 2, - 2 ),
    new THREE.Vector3( 2, 2, - 0.5 ),
    new THREE.Vector3( 2, 1, - 2 )
    ];

  path = new THREE.CatmullRomCurve3( points, true );

  // visualize the path

  const lineGeometry = new THREE.BufferGeometry().setFromPoints( path.getPoints( 32 ) );
  const lineMaterial = new THREE.LineBasicMaterial();
  const line = new THREE.Line( lineGeometry, lineMaterial );
  scene.add( line );

}

function animate() {

  requestAnimationFrame( animate );

  time += clock.getDelta();

  const t = Math.min( time / duration, 1 );

  if ( t === 1 ) time = 0;

  path.getPointAt( t, mesh.position ); // animating

  renderer.render( scene, camera );

}

body {
  margin: 0;
}

<script src="https://cdn.jsdelivr.net/npm/three@0.137.5/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.137.5/examples/js/controls/OrbitControls.js"></script>


问:
Why is LazyHGrid not as high as its items?
I've got a LazyHGrid that shows multiple Text views in one row. That LazyHGrid is inside a VStack. However, the LazyHGrid is higher than it needs to be. What causes the extra space?

```<code>struct ContentView: View {

    let rows = [GridItem()]

    var body: some View {
        VStack {

            ScrollView(.horizontal) {
                LazyHGrid(rows: rows) {
                    ForEach(0..<10) { index in
                        Text("Test \(index)")
                            .padding()
                            .foregroundColor(Color.white)
                            .background(Color.black)
                    }
                }
            }
            .background(Color.green)

            ScrollView(.vertical) {
                VStack {
                    ForEach(0..<100) { index in
                        Text(String(index))
                            .frame(maxWidth: .infinity)
                    }
                }
            }
            .background(Color.blue)
        }
    }
}
</code>```

答:
You just have to add .fixedSize() modifier to your grid, and it works...

```<code>                LazyHGrid(rows: rows) {
                    ForEach(0..<10) { index in
                        Text("Test \(index)")
                            .padding()
                            .foregroundColor(Color.white)
                            .background(Color.black)
                    }
                }
                .fixedSize()
</code>```

Body:
I've got a LazyHGrid that shows multiple Text views in one row. That LazyHGrid is inside a VStack. However, the LazyHGrid is higher than it needs to be. What causes the extra space?

struct ContentView: View {

    let rows = [GridItem()]

    var body: some View {
        VStack {

            ScrollView(.horizontal) {
                LazyHGrid(rows: rows) {
                    ForEach(0..<10) { index in
                        Text("Test \(index)")
                            .padding()
                            .foregroundColor(Color.white)
                            .background(Color.black)
                    }
                }
            }
            .background(Color.green)

            ScrollView(.vertical) {
                VStack {
                    ForEach(0..<100) { index in
                        Text(String(index))
                            .frame(maxWidth: .infinity)
                    }
                }
            }
            .background(Color.blue)
        }
    }
}

Body:
You just have to add .fixedSize() modifier to your grid, and it works...

                LazyHGrid(rows: rows) {
                    ForEach(0..<10) { index in
                        Text("Test \(index)")
                            .padding()
                            .foregroundColor(Color.white)
                            .background(Color.black)
                    }
                }
                .fixedSize()


问:
Updating JSX transform breaks React
I'm trying to upgrade to React 17 and use the new JSX Transform to avoid import React from 'react'. When I remove import React from a component, the page crashes with an error (only when rendering that component).

React is not defined

I thought I could solve this by changing my webpack config:

// module > rules > use > options > presets
{
  presets: [
    ['@babel/preset-react', { runtime: 'automatic' }]
  ]
}
```
<p>(It had previously only been <code>'@babel/preset-react'</code> without the options.)</p>
<p>After compiling, I am presented with several errors in the console:</p>
<blockquote>
<p>Warning: Cannot update a component while rendering a different component.</p>
<p>Warning: Can't perform a React state update on an unmounted component.</p>
<p>Warning: Cannot update during an existing state transition (such as within 'render').</p>
<p>Uncaught Error:
Invalid hook call. Hooks can only be called inside of the body of a function component.</p>
</blockquote>
<p>The app loads more or less okay until it gets to the React-Table, and then won't go any further after the invalid hook call error.</p>
<p>I've updated some packages to ensure they should be on the correct version:</p>
<pre class="lang-json prettyprint-override"><code>{
  "@babel/core": "7.16.0",
  "@babel/preset-env": "7.16.4",
  "@babel/preset-react": "7.16.0",
  "babel-loader": "8.2.3",
}
</code>```

Any idea why adding { runtime: 'automatic' } messes up how React is operating?

答:
I had faced similar issues while trying to adopt JSX Transform.
I would point out two issues you might be having here.

Once you upgrade your React version to 17/ 16.14.x you need to do a npm/yarn clean and reinstall all your dependencies and restart the server. And you have to do this everytime you switch between React <16.x and React 17 branches.

The Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component that you're getting is not related to any of your changes. Maybe you've mistakenly called a hook outside of a functional component,you can check your code for that.Once this is fixed, JSX Transform will work as smooth as butter!!

Title: Updating JSX transform breaks React

Body:
I'm trying to upgrade to React 17 and use the new JSX Transform to avoid import React from 'react'. When I remove import React from a component, the page crashes with an error (only when rendering that component).

React is not defined

I thought I could solve this by changing my webpack config:

// module > rules > use > options > presets
{
  presets: [
    ['@babel/preset-react', { runtime: 'automatic' }]
  ]
}

(It had previously only been '@babel/preset-react' without the options.)

After compiling, I am presented with several errors in the console:

Warning: Cannot update a component while rendering a different component.

Warning: Can't perform a React state update on an unmounted component.

Warning: Cannot update during an existing state transition (such as within 'render').

Uncaught Error:
Invalid hook call. Hooks can only be called inside of the body of a function component.

The app loads more or less okay until it gets to the React-Table, and then won't go any further after the invalid hook call error.

I've updated some packages to ensure they should be on the correct version:

{
  "@babel/core": "7.16.0",
  "@babel/preset-env": "7.16.4",
  "@babel/preset-react": "7.16.0",
  "babel-loader": "8.2.3",
}

Any idea why adding { runtime: 'automatic' } messes up how React is operating?