问:
Message "note: This error originates from a subprocess, and is likely not a problem with pip"
While downloading pip install allennlp==1.0.0 allennlp-models==1.0.0, I faced this problem:

```<code>        [6 lines of output]
        running bdist_wheel
        running build
        running build_py
        running build_ext
        building 'srsly.msgpack._unpacker' extension
        error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
        [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
        ERROR: Failed building wheel for srsly
      Failed to build thinc blis srsly
      ERROR: Could not build wheels for srsly, which is required to install pyproject.toml-based projects
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.
</code>```

I have downloaded:

```<code>pip install -vvv torch
pip install numpy
pip3 install --pre torch -f https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html
</code>```

and it still not working.

I am using Python 3.10.2 on Windows 11 Pro.

What should I do?

答:
I've found a similar question from GitHub, and credits goes to thaibee. Here I quote:

It's a problem with Microsoft products and is
very easy to solve.

If you can't install these plugins as well,
need to download it from other repositories like this one:

https://www.lfd.uci.edu/~gohlke/pythonlibs/ depends on the version of python and the system.

For example: for my Windows 11 (x64) and Python 3.10 I took this file:   pyodbc‑4.0.32‑cp310‑cp310‑win_amd64.whl

It's very easy to install: pip install pyodbc‑4.0.32‑cp310‑cp310‑win_amd64.whl

After it, the system works well and didn't ask you about VC.

This solution I found in problem with the MySQL plugin for Django. I don't understand why - but they also use VC for the installation process.

Body:
While downloading pip install allennlp==1.0.0 allennlp-models==1.0.0, I faced this problem:

        [6 lines of output]
        running bdist_wheel
        running build
        running build_py
        running build_ext
        building 'srsly.msgpack._unpacker' extension
        error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
        [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
        ERROR: Failed building wheel for srsly
      Failed to build thinc blis srsly
      ERROR: Could not build wheels for srsly, which is required to install pyproject.toml-based projects
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.

I have downloaded:

pip install -vvv torch
pip install numpy
pip3 install --pre torch -f https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html

and it still not working.

I am using Python 3.10.2 on Windows 11 Pro.

What should I do?


来源: stackexchange

问:
Edit button jquery function
How do I make my to do list able edit input through the edit button using jquery? It is a to do list and i want users to be able to edit the input
Thanks in advance

To Do List

  Home

    <input type="text" class="note" placeholder="Input new note..">
    <button id="addButton">Add</button>

```

答:
I've modify your code and added the edit functionality. It's supposed to work as you will expect so I will not say much. Kindly try this

$(document).ready(function() {
    var $note   = $('.note');
    var $taskId = $('.task-id');

    $('#addButton').click(function() {
        var task = $note.val().trim();
        var id   = $taskId.val();

        if( task.trim() === '' ){
            // do nothing
        }else if( id !== '' ){ // edit
            $(".todo-list").find('[data-id="'+id+'"] .task').text(task);
        }else{ // add todo
            id = new Date().getTime(); // you can make it more unique
            $(".todo-list").append(`

                    ${task}

                        <button class="deleteButton">Delete</button>
                        <button class="editButton">Edit</button>

            `);
        }

        $note.val('').focus();
        $taskId.val('');
        $(this).text('Add');
    });

    // delete and edit action
    $(document).on('click', '.deleteButton', function() {
        $(this).closest('li').remove();
    }).on('click', '.editButton', function(){
        let $li = $(this).closest('li');

        $note.val( $li.find('.task').text() );
        $taskId.val( $li.data('id') );
        $('#addButton').text('Update');
    });

    // cancel update if .note text is cleared
    $('.note').on('input', function(){
        if( $(this).val() === '' ){
            $taskId.val('').focus();
            $('#addButton').text('Add');
        }
    })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input">
    <input type="text" class="note" placeholder="Input new note..">
    <input type="hidden" class="task-id">
    <button id="addButton">Add</button>
</div>
<ul class="todo-list"></ul></code>```

ContentLicense: CC BY-SA 4.0

Title: Edit button jquery function

Body:
I've modify your code and added the edit functionality. It's supposed to work as you will expect so I will not say much. Kindly try this

$(document).ready(function() {
    var $note   = $('.note');
    var $taskId = $('.task-id');

    $('#addButton').click(function() {
        var task = $note.val().trim();
        var id   = $taskId.val();

        if( task.trim() === '' ){
            // do nothing
        }else if( id !== '' ){ // edit
            $(".todo-list").find('[data-id="'+id+'"] .task').text(task);
        }else{ // add todo
            id = new Date().getTime(); // you can make it more unique
            $(".todo-list").append(`
                <li data-id="${id}">
                    <span class="task">${task}</span>
                    <div class="button-center">
                        <button class="deleteButton">Delete</button>
                        <button class="editButton">Edit</button>
                    </div>
                </li>
            `);
        }

        $note.val('').focus();
        $taskId.val('');
        $(this).text('Add');
    });

    // delete and edit action
    $(document).on('click', '.deleteButton', function() {
        $(this).closest('li').remove();
    }).on('click', '.editButton', function(){
        let $li = $(this).closest('li');

        $note.val( $li.find('.task').text() );
        $taskId.val( $li.data('id') );
        $('#addButton').text('Update');
    });

    // cancel update if .note text is cleared
    $('.note').on('input', function(){
        if( $(this).val() === '' ){
            $taskId.val('').focus();
            $('#addButton').text('Add');
        }
    })
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input">
    <input type="text" class="note" placeholder="Input new note..">
    <input type="hidden" class="task-id">
    <button id="addButton">Add</button>
</div>
<ul class="todo-list"></ul>


问:
Querying Dynamics 365 for specific data based on filter and getting JToken back
I'm debugging a Get request to the string path of

$"{orgname}.api.crm.dynamics.com/api/data/v9.1/accounts?$select=name,accountnumber,accountid&$filter=contains(accountnumber,%27(ellaId)%27)"

It's sending back null values although I know the value of the filter for this specific query (ellaId's value) is correct and in D365. Is the query wrong? I must be missing something obvious from the Microsoft documentation. I've tried replacing %27 with the actual ' instead, but to no avail (if that would even work.)

Any help is greatly appreciated.

答:
The right syntax would be

```<code>$"{orgname}.api.crm.dynamics.com/api/data/v9.1/accounts?$select=name,accountnumber,accountid&$filter=contains(accountnumber,'{ellaId}')"
</code>```

assuming you store the value of your search term inside a variable called ellaId.

However if you use C# I suggest to use the official SDK (you don't need to deal with authentication timeouts by yourself), but if you want you can still use the Web API endpoint. If you need a tool to generate such requests you can use the one I created: Dataverse REST Builder.

It does not generate the C# code but at least you can see the generated endpoint url.

The site has also a Demo available if you want to test it before installing it.

Body:
The right syntax would be

$"{orgname}.api.crm.dynamics.com/api/data/v9.1/accounts?$select=name,accountnumber,accountid&$filter=contains(accountnumber,'{ellaId}')"

assuming you store the value of your search term inside a variable called ellaId.

However if you use C# I suggest to use the official SDK (you don't need to deal with authentication timeouts by yourself), but if you want you can still use the Web API endpoint. If you need a tool to generate such requests you can use the one I created: Dataverse REST Builder.

It does not generate the C# code but at least you can see the generated endpoint url.

The site has also a Demo available if you want to test it before installing it.


问:
Creating a function so that user can input a string and search for matching string within a list of object and return search result of type list
I have created a Class and a list of object using the class.

```<code>class Holiday:

def __init__(self, Destination:str ,Region:str ,Description:str ,Price:float ):
    self.__destination=Destination
    self.__region=Region
    self.__description=Description
    self.__price=Price
</code>```

Now I would like to create a function so that users can input and search for a matching string within the list of objects using the following function.

```<code>def SearchBasedOnRegionOrDescription( searchStr: str, myholiday: list[object]) -> list[object]:
</code>```

I've tried

```<code>def SearchBasedOnRegionOrDescription( searchStr: str, myholiday: list[object]) -> list[object]:
    for myholiday[object] in myholiday:
        if myholiday[object].getDestination()==searchStr:
            print(myholiday[object].getDestination(), myholiday[object].getRegion(), myholiday[object].getDescription(), myholiday[object].getPrice())
</code>```

But the code does not work.

答:
This is a wild guess trying to understand what you meant by "the code does not work":

class Holiday:

    def __init__(self, destination:str, region:str, description:str, price:float):
        self.destination = destination
        self.region = region
        self.description = description
        self.price = price

def search_based_on_region_or_description(searched_name: str, holidays_to_search_in: list[object]) -> list[object]:
    return [
        current_holiday_examined for current_holiday_examined in holidays_to_search_in
        if searched_name in current_holiday_examined.region or searched_name in current_holiday_examined.description
    ]
```

Body:
I have created a Class and a list of object using the class.

class Holiday:

def __init__(self, Destination:str ,Region:str ,Description:str ,Price:float ):
    self.__destination=Destination
    self.__region=Region
    self.__description=Description
    self.__price=Price

Now I would like to create a function so that users can input and search for a matching string within the list of objects using the following function.

def SearchBasedOnRegionOrDescription( searchStr: str, myholiday: list[object]) -> list[object]:

I've tried

def SearchBasedOnRegionOrDescription( searchStr: str, myholiday: list[object]) -> list[object]:
    for myholiday[object] in myholiday:
        if myholiday[object].getDestination()==searchStr:
            print(myholiday[object].getDestination(), myholiday[object].getRegion(), myholiday[object].getDescription(), myholiday[object].getPrice())

But the code does not work.


问:
Should the whole home page be inside main tag?
Lets say I have a website like apple. So should the red section go inside the main tag or the green section?

答: No, it's not necessary. You can keep the upper part in the header, the middle part in main and bottom part in footer. Generally these tags are not used</p>


问:
cvlib detect common objects function doesn't work
I'm new to cvlib module.....

I tried to use the detect_common_objects function from cvlib module but hit the error below.
I'm using cvlib version 0.2.7 and cv2 version 4.5.3.

```<code>import cvlib as cv
import cv2
image2019_0=cv2.imread('/content/drive/MyDrive/Project CV x Traffic/car_image_2019_Jan/0.jpg')
bbox, label, conf = cv.detect_common_objects(image2019_0, model = 'yolov4', enable_gpu = True)
</code>```

error:

答:
Try with the latest version of OpenCV (4.5.5.62). You can upgrade the package to the newest version as below

```<code>pip install --upgrade opencv-python
</code>```

If you want to use older version of OpenCV, downgrade cvlib to 0.2.6 as below

```<code>pip install cvlib==0.2.6
</code>```

The issue you are facing is due to version incompatibility.

Body:
I'm new to cvlib module.....

I tried to use the detect_common_objects function from cvlib module but hit the error below.
I'm using cvlib version 0.2.7 and cv2 version 4.5.3.

import cvlib as cv
import cv2
image2019_0=cv2.imread('/content/drive/MyDrive/Project CV x Traffic/car_image_2019_Jan/0.jpg')
bbox, label, conf = cv.detect_common_objects(image2019_0, model = 'yolov4', enable_gpu = True)

error:

Body:
Try with the latest version of OpenCV (4.5.5.62). You can upgrade the package to the newest version as below

pip install --upgrade opencv-python

If you want to use older version of OpenCV, downgrade cvlib to 0.2.6 as below

pip install cvlib==0.2.6

The issue you are facing is due to version incompatibility.


问:
DsGetDcName and how to "attempt to use the domain controller"
In my program, I am calling DsGetDcName to get a domain controller.

Microsoft's documentation for DsGetDcName says this:

By default, this function does not ensure that the returned domain
controller is currently available. Instead, the caller should attempt
to use the returned domain controller.

I can't ping the domain controller to "use the domain controller" as the firewall might be turned on

So, my question is...how do I "attempt to use the returned domain controller"?

```<code>#include <Windows.h>
#include <DsGetDC.h>
#include <wchar.h>
#pragma comment(lib, "NetApi32.lib")

int main()
{
    PDOMAIN_CONTROLLER_INFOW pdci{};
    ULONG flags = DS_DIRECTORY_SERVICE_REQUIRED;
    DWORD dwRet = DsGetDcNameW(NULL, NULL, NULL, NULL, flags, &pdci);
    wprintf(L"%s\n", pdci->DomainControllerName);
}
</code>```

答:
I assume you're getting the name of a domain controller because you want to do something with it. So just do whatever you're going to do. You don't need to do anything special.

That remark is just a warning that the first time your code does something that will contact the DC, you should handle the case where the DC is not active. In that case, you can do what the documentation goes on to say:

If the domain controller is not available, the caller should call the DsGetDcName function again, specifying the DS_FORCE_REDISCOVERY flag.

Then you can try again with that new DC.

Realistically, this will be a very rare case. The documentation of the DS_FORCE_REDISCOVERY flag explains why:

When the DS_FORCE_REDISCOVERY flag is not specified, DsGetDcName may return cached domain controller data.

So if the computer has already been using a specific DC, then DsGetDcName will return that DC without checking if it is still available. That means that, really, the only time DsGetDcName will return a DC that cannot be contacted is if the DC suddenly cannot be contacted, which could be a network issue, or even the DC being decommissioned.

Body:
In my program, I am calling DsGetDcName to get a domain controller.

Microsoft's documentation for DsGetDcName says this:

By default, this function does not ensure that the returned domain
controller is currently available. Instead, the caller should attempt
to use the returned domain controller.

I can't ping the domain controller to "use the domain controller" as the firewall might be turned on

So, my question is...how do I "attempt to use the returned domain controller"?

#include <Windows.h>
#include <DsGetDC.h>
#include <wchar.h>
#pragma comment(lib, "NetApi32.lib")

int main()
{
    PDOMAIN_CONTROLLER_INFOW pdci{};
    ULONG flags = DS_DIRECTORY_SERVICE_REQUIRED;
    DWORD dwRet = DsGetDcNameW(NULL, NULL, NULL, NULL, flags, &pdci);
    wprintf(L"%s\n", pdci->DomainControllerName);
}


问:
Deployment rejected on migrated Artifactory Instance
We are using Artifactory 6.17.0 on a Linux Server.

We migrated it to a new server by simply tar'ing the installation directory & un-tar'ing it at exactly the same path in the new machine. This directory contains the entire installation.

Retrieval of local & bincentre objects via Artifactory is working ok using maven & pom.xml in a Java project under eclipse.

Deployments are being rejected as follows:

```<code>2022-02-06 14:48:49,779 [http-nio-8081-exec-1] [WARN ] (o.a.r.ArtifactoryResponseBase:125) -
Sending HTTP error code 409:
The repository 'libs-release-local' rejected the resolution of an artifact
'libs-release-local:my/server/0.0.1-SNAPSHOT/securpharm.server-0.0.1-20220206.134849-1.jar'
due to conflict in the snapshot release handling policy.
</code>```

I have updated the <distributionManagement> in my pom.xml to the suggested values fromt the Artifactory Web Admin:

```<code><distributionManagement>
    <repository>
        <id>central</id>
        <name>servername-releases</name>
        <url>http://servername.domain.name.com:8081/artifactory/libs-release</url>
    </repository>
</distributionManagement>
</code>```

Anyone have an idea what the problem might be?

答:
In addtion to the above comment, If you would like to publish both snapshot and release version under the repository "libs-release-local" repository you can select the option "Handle Releases" in the libs-release-local repository configuration page and publish the version. As shown in the screenshot here.

Please note, it is always recommended to have separate repositories for handling release and snapshot version.

Body:
We are using Artifactory 6.17.0 on a Linux Server.

We migrated it to a new server by simply tar'ing the installation directory & un-tar'ing it at exactly the same path in the new machine. This directory contains the entire installation.

Retrieval of local & bincentre objects via Artifactory is working ok using maven & pom.xml in a Java project under eclipse.

Deployments are being rejected as follows:

2022-02-06 14:48:49,779 [http-nio-8081-exec-1] [WARN ] (o.a.r.ArtifactoryResponseBase:125) -
Sending HTTP error code 409:
The repository 'libs-release-local' rejected the resolution of an artifact
'libs-release-local:my/server/0.0.1-SNAPSHOT/securpharm.server-0.0.1-20220206.134849-1.jar'
due to conflict in the snapshot release handling policy.

I have updated the <distributionManagement> in my pom.xml to the suggested values fromt the Artifactory Web Admin:

<distributionManagement>
    <repository>
        <id>central</id>
        <name>servername-releases</name>
        <url>http://servername.domain.name.com:8081/artifactory/libs-release</url>
    </repository>
</distributionManagement>

Anyone have an idea what the problem might be?


问:
Input 0 of layer "max_pooling2d_30" is incompatible with the layer: expected ndim=4, found ndim=5
I'm just starting to approach ml, and I'm trying to train a model on an image dataset obtained from directories of images using tf.keras.utils.image_dataset_from_directory (then pickling it), so that it can predict which letter is fingerspelled in the image.

So, this is how I unpickle my sets of data:

```<code>#PICKLE LOAD

#TRAIN
  #images
with open('x_train.pkl', 'rb') as x_train_pickle:
  x_train_data = pickle.load(x_train_pickle)
  #labels
with open('y_train.pkl', 'rb') as y_train_pickle:
  y_train_data = pickle.load(y_train_pickle)

#VALIDATION
with open('x_val.pkl', 'rb') as x_val_pickle:
  x_val_data = pickle.load(x_val_pickle)

with open('y_val.pkl', 'rb') as y_val_pickle:
  y_val_data = pickle.load(y_val_pickle)

#TEST
with open('x_test.pkl', 'rb') as x_test_pickle:
  x_test_data = pickle.load(x_test_pickle)

with open('y_test.pkl', 'rb') as y_test_pickle:
  y_test_data = pickle.load(y_test_pickle)
</code>```

Then I convert my array of batches of images to tensor:

```<code>xTrainTensor = tf.convert_to_tensor(x_train_data)

yTrainTensor =  tf.convert_to_tensor(y_train_data)
</code>```

(same thing for val and test set)

xTrainTensor.shape is (160, 32, 180, 180, 3) -> so I have 160 batches of 32 images, each image being described by width, height and RGBchannel.

yTrainTensor.shape (labels) is (160, 32)

If I print the first batch of labels (yTrainTensor[0]), what I obtain seems actually correct:

[21  3 11  2  7 20  5 12 10  7 14 17 10 17 10  6  9 13 14  2 13 11 15  6
0 11  5  9 15 15 21  2]

-> 32 labels in range 0-21 (I have 22 classes/letters)

Now, the thing is: when I try to model.fit using this architecture:

```<code>model = tf.keras.Sequential([
  #tf.keras.layers.InputLayer(input_shape=(32,180,180,3)),
  tf.keras.layers.Rescaling(1./255),
  tf.keras.layers.Conv2D(32, 3, activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(32, 3, activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(32, 3, activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(len(class_names))
])
model.compile(
  optimizer='adam',
  loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
  metrics=['accuracy']
)

epochs = 5
history = model.fit(
  xTrainTensor,
  yTrainTensor,
  validation_data=(x_val_data, y_val_data),
  epochs=epochs
)
</code>```

I get this error:

```<code>ValueError: Exception encountered when calling layer "sequential_12" (type Sequential).

Input 0 of layer "max_pooling2d_30" is incompatible with the layer: expected ndim=4,
found ndim=5. Full shape received: (32, 32, 178, 178, 32)

Call arguments received:
  • inputs=tf.Tensor(shape=(32, 32, 180, 180, 3), dtype=float32)
  • training=True
  • mask=None
</code>```

Can anybody please help me understand why this happens? I really can't figure it out, since I believe I have specified the input shape in the first layer...
Thank you in advance and please be kind, I'm just starting!

UPDATE

Even though using tf.keras.utils.image_dataset_from_directory I obtain an already batched dataset, I reshaped the corresponding tensor so that instead of having shape (160, 32, 180, 180, 3) it has shape (160*32, 180, 180, 3) - using tf.reshape, manually...
And it actually works for me! Hope it makes sense doing it this way, I found no other ways of "unbatching" the dataset created from directory of images...
Thanks everybody for the hints.

答:
You are giving 5D data to Conv2d instead of 4D.So, either your data should be in the shape (batch_size*32, 180, 180, 3)
or
You can use the TimeDistributed layer wrapper to apply the same convolution layer on all the images in the 5D tensor. For example:</p>
```<code>model = Sequential()
model.add(tf.keras.layers.TimeDistributed(tf.keras.layers.Conv2D(32, 3, activation='relu')))

model.summary()
</code>```

Body:
I'm just starting to approach ml, and I'm trying to train a model on an image dataset obtained from directories of images using tf.keras.utils.image_dataset_from_directory (then pickling it), so that it can predict which letter is fingerspelled in the image.

So, this is how I unpickle my sets of data:

#PICKLE LOAD

#TRAIN
  #images
with open('x_train.pkl', 'rb') as x_train_pickle:
  x_train_data = pickle.load(x_train_pickle)
  #labels
with open('y_train.pkl', 'rb') as y_train_pickle:
  y_train_data = pickle.load(y_train_pickle)

#VALIDATION
with open('x_val.pkl', 'rb') as x_val_pickle:
  x_val_data = pickle.load(x_val_pickle)

with open('y_val.pkl', 'rb') as y_val_pickle:
  y_val_data = pickle.load(y_val_pickle)

#TEST
with open('x_test.pkl', 'rb') as x_test_pickle:
  x_test_data = pickle.load(x_test_pickle)

with open('y_test.pkl', 'rb') as y_test_pickle:
  y_test_data = pickle.load(y_test_pickle)

Then I convert my array of batches of images to tensor:

xTrainTensor = tf.convert_to_tensor(x_train_data)

yTrainTensor =  tf.convert_to_tensor(y_train_data)

(same thing for val and test set)

xTrainTensor.shape is (160, 32, 180, 180, 3) -> so I have 160 batches of 32 images, each image being described by width, height and RGBchannel.

yTrainTensor.shape (labels) is (160, 32)

If I print the first batch of labels (yTrainTensor[0]), what I obtain seems actually correct:

[21  3 11  2  7 20  5 12 10  7 14 17 10 17 10  6  9 13 14  2 13 11 15  6
0 11  5  9 15 15 21  2]

-> 32 labels in range 0-21 (I have 22 classes/letters)

Now, the thing is: when I try to model.fit using this architecture:

model = tf.keras.Sequential([
  #tf.keras.layers.InputLayer(input_shape=(32,180,180,3)),
  tf.keras.layers.Rescaling(1./255),
  tf.keras.layers.Conv2D(32, 3, activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(32, 3, activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(32, 3, activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(len(class_names))
])
model.compile(
  optimizer='adam',
  loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
  metrics=['accuracy']
)

epochs = 5
history = model.fit(
  xTrainTensor,
  yTrainTensor,
  validation_data=(x_val_data, y_val_data),
  epochs=epochs
)

I get this error:

ValueError: Exception encountered when calling layer "sequential_12" (type Sequential).

Input 0 of layer "max_pooling2d_30" is incompatible with the layer: expected ndim=4,
found ndim=5. Full shape received: (32, 32, 178, 178, 32)

Call arguments received:
  • inputs=tf.Tensor(shape=(32, 32, 180, 180, 3), dtype=float32)
  • training=True
  • mask=None

Can anybody please help me understand why this happens? I really can't figure it out, since I believe I have specified the input shape in the first layer...
Thank you in advance and please be kind, I'm just starting!

UPDATE

Even though using tf.keras.utils.image_dataset_from_directory I obtain an already batched dataset, I reshaped the corresponding tensor so that instead of having shape (160, 32, 180, 180, 3) it has shape (160*32, 180, 180, 3) - using tf.reshape, manually...
And it actually works for me! Hope it makes sense doing it this way, I found no other ways of "unbatching" the dataset created from directory of images...
Thanks everybody for the hints.

Body:
You are giving 5D data to Conv2d instead of 4D.So, either your data should be in the shape (batch_size*32, 180, 180, 3)
or
You can use the TimeDistributed layer wrapper to apply the same convolution layer on all the images in the 5D tensor. For example:

model = Sequential()
model.add(tf.keras.layers.TimeDistributed(tf.keras.layers.Conv2D(32, 3, activation='relu')))

model.summary()


问:
Join different DataFrames using loop in Pyspark
I have 5 CSV files in a file, and want to join them in one data frame in Pyspark: I use the code below:

```<code>name_file =['A', 'B', 'C', 'D', 'V']
for n in name_file:
n= spark.read.csv(fullpath+n+'.csv'
                ,header=False,
                inferSchema= True)
full_data=full_data.join(n,["id"])
</code>```

Error: I  got an unexpected result > The last dataframe joined just with itself.

Expected Result: There should be 6 columns, each CSV has 2 data frames one of them in common with others. The join should be on this column. As a result, the final data frame should have a common column and 5 special columns from each CSV file.

答:
There seem to be several things wrong with the code or perhaps you have not provided the complete code.

Have you defined fullpath?

You have set header=False then how will spark know that there is an
"id" column?

Your indentation looks wrong under the for loop.

full_data has not been defined yet, so how are you using it on the
right side of the evaluation within the for loop? I suspect you have
initialized this to the first csv file and then attempting to join
it with first csv again.

I ran a small test on the below code which worked for me and addresses the questions I've raised above. You can adjust it to your need.

```<code>fullpath = '/content/sample_data/'
full_data = spark.read.csv(fullpath+'Book1.csv'
                      ,header=True,
                      inferSchema= True)
name_file =['Book2', 'Book3']
for n in name_file:
  n= spark.read.csv(fullpath+n+'.csv'
                      ,header=True,
                      inferSchema= True)
  full_data=full_data.join(n,["id"])
full_data.show(5)
</code>```

Body:
I have 5 CSV files in a file, and want to join them in one data frame in Pyspark: I use the code below:

name_file =['A', 'B', 'C', 'D', 'V']
for n in name_file:
n= spark.read.csv(fullpath+n+'.csv'
                ,header=False,
                inferSchema= True)
full_data=full_data.join(n,["id"])

Error: I  got an unexpected result > The last dataframe joined just with itself.

Expected Result: There should be 6 columns, each CSV has 2 data frames one of them in common with others. The join should be on this column. As a result, the final data frame should have a common column and 5 special columns from each CSV file.

Body:
There seem to be several things wrong with the code or perhaps you have not provided the complete code.

Have you defined fullpath?

You have set header=False then how will spark know that there is an
"id" column?

Your indentation looks wrong under the for loop.

full_data has not been defined yet, so how are you using it on the
right side of the evaluation within the for loop? I suspect you have
initialized this to the first csv file and then attempting to join
it with first csv again.

I ran a small test on the below code which worked for me and addresses the questions I've raised above. You can adjust it to your need.

fullpath = '/content/sample_data/'
full_data = spark.read.csv(fullpath+'Book1.csv'
                      ,header=True,
                      inferSchema= True)
name_file =['Book2', 'Book3']
for n in name_file:
  n= spark.read.csv(fullpath+n+'.csv'
                      ,header=True,
                      inferSchema= True)
  full_data=full_data.join(n,["id"])
full_data.show(5)


问:
What is the usage of guard let self = self else { return }
I just learned how to use the Result type recently from Sean Allen's video, and I get the idea of using it. However, while I was writing a code, there is a line I don't understand.

The line is 87 in the picture (or this -> guard let self = self else { return } )
At first, I was just doing the same stuff as he did, but I wonder why he add the line in the code. I think he wrote it because the self can be nil and wanted to make sure if the self is not nil and return from the function if it gets nil.

And my question is

when or in which situation the self can be nil?
and

if self gets nil, I think it won't trigger the following line (the one for checking the result), so both of the updateUI function and presentGFAlert... function won't be triggered and nothing shows up on the screen, right?

答: Its because the closure defines its reference to self as being weak, this means if self is released, the block closure will not prevent self from being destructed, getting a reference count of 0. You can deal with this in the code in the closure, by using all references to self as self?, but this mean self could became nil mid way being executed, by using guard let self = self else { return }, you are saying if execution gets here, I want a strong reference to it, so the object will continue being available until the execution of the of the closure complete, basically all or nothing. This in the past could only happen with multi threaded apps, but with apples new async thread model making cooperative threads more common this is potential more possible.


问:
Is an end-2-end javascript stack secure?
I want to build a multi tenent cloud app. My stack is javascript / json end-2-end: The user inputs data in the browser which jquery turns to json, sends to my node.js server, which in turn stores it as json in couchdb. When fetching data json goes the other way around. If the user injects something to this json is there anywhere in the above stack this json is actually evaludated? If yes I need to sanitize it. How robust is json sanitization? Or will a sandbox help? how robust is it?

This is a multi tenent environment and a lot of secret data of users and companies will be there.

答:
I suggest defense-in-depth (i.e. multiple overlapping security mechanisms. Richard and Pasha both make excellent suggestions.

Something else to do is use CouchDB data validation features. You write a validate_doc_update function in Javascript. This function will run for every change to the database. The function can decide whether the data is acceptable or not.

Validation runs deep, in the CouchDB server itself. Therefore, if you have a good validation function, it is impossible for bad data to be stored at all.

ContentLicense: CC BY-SA 3.0


问: how to extract a link inside

答:
You can use a regular expressions pattern:</p>
```<code>import re
...

print(re.search(r'"playUrl":"(.*)"', str(soup)).group(1))
</code>```

Title: how to extract a link inside <script> tag

Body:
I'm trying to get a .mp3 file in a link from TikTok sounds
the problem is I can't extract it because it's inside <"script"> tag

I'm using pycurl instead of requests

all i need is to extract this from the response then extract the URL from UrlList"
"playUrl":{"Uri":"musically-maliva-obj/7038595527327419141.mp3","UrlList":["https://sf16-ies-music-va.tiktokcdn.com/obj/musically-maliva-obj/7038595527327419141.mp3"]}

import pycurl
from io import BytesIO
import certifi
from bs4 import BeautifulSoup

url = "https://vm.tiktok.com/ZML1t1vW7/"
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.CAINFO, certifi.where())
c.setopt(c.URL, url)
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.SSL_VERIFYHOST, 0)
c.setopt(pycurl.HTTPHEADER, ["User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"])
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.FOLLOWLOCATION, True)
c.perform()
c.close()
body = buffer.getvalue()
response = body.decode('utf-8')
#response = response.split('"')
#response = response[1]
#response = response.split('.html?')
#response= response[0]
a = response.split("'")  # gives me a list and i don't know how to search in it
soup = BeautifulSoup(response, 'html.parser')  # cause response is a string
link = soup.find("script", id="sigi-persisted-data")  #i tried to use bs4 but i couldn't find a reasult
print(link)

Body:
You can use a regular expressions pattern:

import re
...

print(re.search(r'"playUrl":"(.*)"', str(soup)).group(1))


问:
How to use REGEX on SQLLite3 with JPA?
I found out that in order to filter a column of my SQLLite3 database (a number phone) I need to use REGEX because there is a formation rule and on my database I have some valid phone numbers and invalid ones. I can not update the database, it is read only, and I have a RGEX to validate the numbers.

The problem is that by default SQLite does not provide implementation for the regular expression comparison, so you have to provide one. It's done by implementing the regexp() custom SQL function.

I googled around to know better how to d it but I still have doubts.
So far I found

SQLite query with regex

Writing user defined SQL functions for SQLite using Java or Groovy?

https://github.com/xerial/sqlite-jdbc/issues/60

https://gitanswer.com/sqlite-jdbc-no-such-function-regexp-java-111823316

Well I really don't know where to start.

Where should I implement the REGEX operator?

My best guess is inside the SQLLite3 Dialect.  Is it right? How?
Does it make sense what I did below?
I am assuming it is required to use registerFunction.  How should I do it?

```<code>package com.jumia.db.dialect;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.regex.Pattern;

import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.identity.IdentityColumnSupport;
import org.hibernate.type.StandardBasicTypes;
import org.sqlite.Function;

public class SQLiteDialect extends Dialect {

    public SQLiteDialect() {
        registerColumnType(Types.BIT, "integer");
        registerColumnType(Types.TINYINT, "tinyint");
        registerColumnType(Types.SMALLINT, "smallint");
        registerColumnType(Types.INTEGER, "integer");
        registerColumnType(Types.BIGINT, "bigint");
        registerColumnType(Types.FLOAT, "float");
        registerColumnType(Types.REAL, "real");
        registerColumnType(Types.DOUBLE, "double");
        registerColumnType(Types.NUMERIC, "numeric");
        registerColumnType(Types.DECIMAL, "decimal");
        registerColumnType(Types.CHAR, "char");
        registerColumnType(Types.VARCHAR, "varchar");
        registerColumnType(Types.LONGVARCHAR, "longvarchar");
        registerColumnType(Types.DATE, "date");
        registerColumnType(Types.TIME, "time");
        registerColumnType(Types.TIMESTAMP, "timestamp");
        registerColumnType(Types.BINARY, "blob");
        registerColumnType(Types.VARBINARY, "blob");
        registerColumnType(Types.LONGVARBINARY, "blob");
        registerColumnType(Types.BLOB, "blob");
        registerColumnType(Types.CLOB, "clob");
        registerColumnType(Types.BOOLEAN, "integer");

        //How to do it?
registerFunction( "REGEXP", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "?1 REGEXP ?2"));
    }

    public static void createREGEXP(Connection connection) throws SQLException
    {
        Function.create(connection, "REGEXP", new Function()
        {
            @Override
            protected void xFunc() throws SQLException
            {
                String expression = value_text(0);
                String value = value_text(1);
                if (value == null)
                value = "";
                Pattern pattern=Pattern.compile(expression);
                result(pattern.matcher(value).find() ? 1 : 0);
            }
        });
    }
    public boolean dropConstraints() {
        return false;
    }

    public String getAddColumnString() {
        return "add column";
    }

    public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable, String[] primaryKey, boolean referencesPrimaryKey) {
        return "";
    }

    public String getAddPrimaryKeyConstraintString(String constraintName) {
        return "";
    }

    public String getDropForeignKeyString() {
        return "";
    }

    public String getForUpdateString() {
        return "";
    }

    public IdentityColumnSupport getIdentityColumnSupport() {
        return new SQLiteIdentityColumnSupport();
    }

    public boolean hasAlterTable() {
        return false;
    }

    public boolean supportsCascadeDelete() {
        return false;
    }

    public boolean supportsIfExistsBeforeTableName() {
        return true;
    }

    public boolean supportsOuterJoinForUpdate() {
        return false;
    }
}
</code>```

EDIT:
On my Repositry I know that I need to create a method like below.

```<code>    @Query(value = "SELECT * FROM Customer c WHERE c.phone REGEXP :regex", nativeQuery = true)
    public Page<Customer> findAllValid(Pageable pageable, @Param("regex") String regex);
</code>```

Although I have registered this Dialect I still get errors like it was not registered.

2022-02-07 09:50:25.681 ERROR 101004 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not prepare statement; nested exception is org.hibernate.exception.GenericJDBCException: could not prepare statement] with root cause

org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such function: REGEXP)
at org.sqlite.core.DB.newSQLException(DB.java:1030) ~[sqlite-jdbc-3.36.0.3.jar:na]
at org.sqlite.core.DB.newSQLException(DB.java:1042) ~[sqlite-jdbc-3.36.0.3.jar:na]

答: You should check when you receive user input, not in the database. Depending on a database-specific function or feature is not a good choice.</p>

Title: How to use REGEX on SQLLite3 with JPA?

Body:
I found out that in order to filter a column of my SQLLite3 database (a number phone) I need to use REGEX because there is a formation rule and on my database I have some valid phone numbers and invalid ones. I can not update the database, it is read only, and I have a RGEX to validate the numbers.

The problem is that by default SQLite does not provide implementation for the regular expression comparison, so you have to provide one. It's done by implementing the regexp() custom SQL function.

I googled around to know better how to d it but I still have doubts.
So far I found

SQLite query with regex

Writing user defined SQL functions for SQLite using Java or Groovy?

https://github.com/xerial/sqlite-jdbc/issues/60

https://gitanswer.com/sqlite-jdbc-no-such-function-regexp-java-111823316

Well I really don't know where to start.

Where should I implement the REGEX operator?

My best guess is inside the SQLLite3 Dialect.  Is it right? How?
Does it make sense what I did below?
I am assuming it is required to use registerFunction.  How should I do it?

package com.jumia.db.dialect;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.regex.Pattern;

import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.identity.IdentityColumnSupport;
import org.hibernate.type.StandardBasicTypes;
import org.sqlite.Function;

public class SQLiteDialect extends Dialect {

    public SQLiteDialect() {
        registerColumnType(Types.BIT, "integer");
        registerColumnType(Types.TINYINT, "tinyint");
        registerColumnType(Types.SMALLINT, "smallint");
        registerColumnType(Types.INTEGER, "integer");
        registerColumnType(Types.BIGINT, "bigint");
        registerColumnType(Types.FLOAT, "float");
        registerColumnType(Types.REAL, "real");
        registerColumnType(Types.DOUBLE, "double");
        registerColumnType(Types.NUMERIC, "numeric");
        registerColumnType(Types.DECIMAL, "decimal");
        registerColumnType(Types.CHAR, "char");
        registerColumnType(Types.VARCHAR, "varchar");
        registerColumnType(Types.LONGVARCHAR, "longvarchar");
        registerColumnType(Types.DATE, "date");
        registerColumnType(Types.TIME, "time");
        registerColumnType(Types.TIMESTAMP, "timestamp");
        registerColumnType(Types.BINARY, "blob");
        registerColumnType(Types.VARBINARY, "blob");
        registerColumnType(Types.LONGVARBINARY, "blob");
        registerColumnType(Types.BLOB, "blob");
        registerColumnType(Types.CLOB, "clob");
        registerColumnType(Types.BOOLEAN, "integer");

        //How to do it?
registerFunction( "REGEXP", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "?1 REGEXP ?2"));
    }

    public static void createREGEXP(Connection connection) throws SQLException
    {
        Function.create(connection, "REGEXP", new Function()
        {
            @Override
            protected void xFunc() throws SQLException
            {
                String expression = value_text(0);
                String value = value_text(1);
                if (value == null)
                value = "";
                Pattern pattern=Pattern.compile(expression);
                result(pattern.matcher(value).find() ? 1 : 0);
            }
        });
    }
    public boolean dropConstraints() {
        return false;
    }

    public String getAddColumnString() {
        return "add column";
    }

    public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable, String[] primaryKey, boolean referencesPrimaryKey) {
        return "";
    }

    public String getAddPrimaryKeyConstraintString(String constraintName) {
        return "";
    }

    public String getDropForeignKeyString() {
        return "";
    }

    public String getForUpdateString() {
        return "";
    }

    public IdentityColumnSupport getIdentityColumnSupport() {
        return new SQLiteIdentityColumnSupport();
    }

    public boolean hasAlterTable() {
        return false;
    }

    public boolean supportsCascadeDelete() {
        return false;
    }

    public boolean supportsIfExistsBeforeTableName() {
        return true;
    }

    public boolean supportsOuterJoinForUpdate() {
        return false;
    }
}

EDIT:
On my Repositry I know that I need to create a method like below.

    @Query(value = "SELECT * FROM Customer c WHERE c.phone REGEXP :regex", nativeQuery = true)
    public Page<Customer> findAllValid(Pageable pageable, @Param("regex") String regex);

Although I have registered this Dialect I still get errors like it was not registered.

2022-02-07 09:50:25.681 ERROR 101004 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not prepare statement; nested exception is org.hibernate.exception.GenericJDBCException: could not prepare statement] with root cause

org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such function: REGEXP)
at org.sqlite.core.DB.newSQLException(DB.java:1030) ~[sqlite-jdbc-3.36.0.3.jar:na]
at org.sqlite.core.DB.newSQLException(DB.java:1042) ~[sqlite-jdbc-3.36.0.3.jar:na]


问:
API I'm using can't be accessed unless Captcha is completed
I am trying to access API data from CraftingStore Public API.

When I am trying it on localhost, everything works like it should (1st pic, also printing results for to show).
However, when I am trying to view it on the actual website (2nd pic), it is not working but instead saying to enable cookies and to complete captcha.

When on localhost:

When on website:

Also code for accessing the API:

```<code>    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.craftingstore.net/v7/payments?page=1');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'token:'.$cs_token
    ));

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    $obj = json_decode($result);
    $dononame = $obj->data[0]->inGameName;
    $donobuy = $obj->data[0]->packageName;
</code>```

What can I do?

答:
This is quite usual for API's with Cloudflare. You'll need to make a page rule for the API domain/URI to disable the Browser Integrity Check.

Source: https://support.cloudflare.com/hc/en-us/articles/200504045-Using-Cloudflare-with-your-API

Body:
I am trying to access API data from CraftingStore Public API.

When I am trying it on localhost, everything works like it should (1st pic, also printing results for to show).
However, when I am trying to view it on the actual website (2nd pic), it is not working but instead saying to enable cookies and to complete captcha.

When on localhost:

When on website:

Also code for accessing the API:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.craftingstore.net/v7/payments?page=1');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'token:'.$cs_token
    ));

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    $obj = json_decode($result);
    $dononame = $obj->data[0]->inGameName;
    $donobuy = $obj->data[0]->packageName;

What can I do?


问:
Cannot read properties of null (reading 'id') [Discord Slash Commands]
I'm trying to get a little familiar with the slash command handler, but I get an error when trying to grab the member id, this happens with just about everything I try to grab.

Here at the top is directly my command, where I try to send a message with the content "user.id".

this is my command:

```<code>const { SlashCommandBuilder } = require("@discordjs/builders");

module.exports = {
    data: new SlashCommandBuilder()
    .setName("avatar")
    .setDescription("SERVUSSS")
    .addUserOption(option => option.setName("member").setDescription("memberdings").setRequired(true)),
    async execute(interaction) {
        const user = interaction.options.getUser('target');
        await interaction.reply(`${user.id}`);
    }
}
</code>```

this is my deploy file:

```<code>require("dotenv").config();
const fs = require("fs");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const commands = [];

const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));

commandFiles.forEach(commandFile => {
    const command = require(`./commands/${commandFile}`);
    commands.push(command.data.toJSON());
});

const restClient = new REST({version: "9"}).setToken(process.env.TOKEN);

restClient.put(Routes.applicationGuildCommands(process.env.APPLICATION_ID, process.env.GUILD_ID),
{body: commands }).then(() => console.log("success")).catch(console.error);
</code>```

my index file:

```<code>require("dotenv").config();
const { Client, Collection } = require("discord.js");
const fs = require("fs");

const client = new Client({intents: []});
client.commands = new Collection();

const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));

commandFiles.forEach(commandFile => {
    const command = require(`./commands/${commandFile}`);
    client.commands.set(command.data.name, command);
});

client.once("ready", () => {
    console.log("ready!!");
});

client.on("interactionCreate", async (interaction) => {
    if(!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName)

    if(command) {
        try {
            await command.execute(interaction)
        } catch(error) {
            console.log(error)

            if(interaction.deferred || interaction.replied) {
                interaction.editReply("error")
            } else {
                interaction.reply("error")
            }
        }
    }
})

client.login(process.env.TOKEN)
</code>```

I actually stick to it pretty much all the time
https://discordjs.guide/ just do not understand what I'm doing wrong

答:
Since option name is member then it's going to be

const user = interaction.options.getUser('member');
```

Body:
I'm trying to get a little familiar with the slash command handler, but I get an error when trying to grab the member id, this happens with just about everything I try to grab.

Here at the top is directly my command, where I try to send a message with the content "user.id".

this is my command:

const { SlashCommandBuilder } = require("@discordjs/builders");

module.exports = {
    data: new SlashCommandBuilder()
    .setName("avatar")
    .setDescription("SERVUSSS")
    .addUserOption(option => option.setName("member").setDescription("memberdings").setRequired(true)),
    async execute(interaction) {
        const user = interaction.options.getUser('target');
        await interaction.reply(`${user.id}`);
    }
}

this is my deploy file:

require("dotenv").config();
const fs = require("fs");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const commands = [];

const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));

commandFiles.forEach(commandFile => {
    const command = require(`./commands/${commandFile}`);
    commands.push(command.data.toJSON());
});

const restClient = new REST({version: "9"}).setToken(process.env.TOKEN);

restClient.put(Routes.applicationGuildCommands(process.env.APPLICATION_ID, process.env.GUILD_ID),
{body: commands }).then(() => console.log("success")).catch(console.error);

my index file:

require("dotenv").config();
const { Client, Collection } = require("discord.js");
const fs = require("fs");

const client = new Client({intents: []});
client.commands = new Collection();

const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));

commandFiles.forEach(commandFile => {
    const command = require(`./commands/${commandFile}`);
    client.commands.set(command.data.name, command);
});

client.once("ready", () => {
    console.log("ready!!");
});

client.on("interactionCreate", async (interaction) => {
    if(!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName)

    if(command) {
        try {
            await command.execute(interaction)
        } catch(error) {
            console.log(error)

            if(interaction.deferred || interaction.replied) {
                interaction.editReply("error")
            } else {
                interaction.reply("error")
            }
        }
    }
})

client.login(process.env.TOKEN)

I actually stick to it pretty much all the time
https://discordjs.guide/ just do not understand what I'm doing wrong


问:
Native web component: style host differently depending on slotted content
Say I have a native web component with an HTML template like so:

<wc-grid>
    <slot></slot>
</wc-grid>
```
<p>Now I have the following two use cases (one with a text input the other with a radio):</p>
```<wc-grid>  <input type="text">   </wc-grid>
<wc-grid>  <input type="radio">  </wc-grid>
```
<p>Is it possible to style the <code><wc-grid></code> differently depending on when whether it contains a text or radio type input?</p>
<p>e.g. If <code>has()</code> was around it would be something like this: (trying to change whether the grid is vertical or horizontal depending on the widget inside of it):</p>
```:host:has(> input[type="text"])  { flex-direction: row; }
:host:has(> input[type="radio"]) { flex-direction: column; }
```

Research has lead me to learn about :has(), but that has not landed yet.
And as far as I can tell :host-context would not help either as it looks up, not down, besides its poor support.

答:
The easiest and cleanest implementation of such a problem I can solve by using a named slot.

example of web component

```<code>  class MyComp extends HTMLElement {
    constructor() {
      super();
      const shadow = this.attachShadow({ mode: 'open' });
      this.shadowRoot.innerHTML = `
      <style>
        .flex {
          display: flex;
          justify-content: space-between;
        }
        .row {
          flex-direction: row;
          background: red;
        }
        .column {
          flex-direction: column;
          background: green;
        }
      </style>
      <div>
        <div class="flex row"><slot name="row"></slot></div>
        <div class="flex column"><slot name="column"></slot></div>
      </div>`;
    }
  }

  customElements.define('my-comp', MyComp);

</code>```

usage in HTML

```<code>    <my-comp>
        <div slot="row">This is row 1</div>
        <div slot="row">this is row 2</div>
        <div slot="row">This is row 3</div>
    </my-comp>
    <my-comp>
        <div slot="column">This is colum 1</div>
        <div slot="column">This is colum 2</div>
        <div slot="column">This is colum 3</div>
    </my-comp>
</code>```

example screenshot

Another good way to have a attribute which can add respective classes to root elements to modify css based on it

Body:
Say I have a native web component with an HTML template like so:

<wc-grid>
    <slot></slot>
</wc-grid>

Now I have the following two use cases (one with a text input the other with a radio):

<wc-grid>  <input type="text">   </wc-grid>
<wc-grid>  <input type="radio">  </wc-grid>

Is it possible to style the <wc-grid> differently depending on when whether it contains a text or radio type input?

e.g. If has() was around it would be something like this: (trying to change whether the grid is vertical or horizontal depending on the widget inside of it):

:host:has(> input[type="text"])  { flex-direction: row; }
:host:has(> input[type="radio"]) { flex-direction: column; }

Research has lead me to learn about :has(), but that has not landed yet.
And as far as I can tell :host-context would not help either as it looks up, not down, besides its poor support.

Body:
The easiest and cleanest implementation of such a problem I can solve by using a named slot.

example of web component

  class MyComp extends HTMLElement {
    constructor() {
      super();
      const shadow = this.attachShadow({ mode: 'open' });
      this.shadowRoot.innerHTML = `
      <style>
        .flex {
          display: flex;
          justify-content: space-between;
        }
        .row {
          flex-direction: row;
          background: red;
        }
        .column {
          flex-direction: column;
          background: green;
        }
      </style>
      <div>
        <div class="flex row"><slot name="row"></slot></div>
        <div class="flex column"><slot name="column"></slot></div>
      </div>`;
    }
  }

  customElements.define('my-comp', MyComp);

usage in HTML

    <my-comp>
        <div slot="row">This is row 1</div>
        <div slot="row">this is row 2</div>
        <div slot="row">This is row 3</div>
    </my-comp>
    <my-comp>
        <div slot="column">This is colum 1</div>
        <div slot="column">This is colum 2</div>
        <div slot="column">This is colum 3</div>
    </my-comp>

example screenshot

Another good way to have a attribute which can add respective classes to root elements to modify css based on it


问:
clusterProfiler cannot load package
I am trying to load clusterProfiler, but regardless of how I install the package or whether I un-install or re-install, I continue to get the below error when I attempt to load it. I have also recently installed and loaded patchwork. Appreciate any tips.

Error: package or namespace load failed for ‘clusterProfiler’:
 object ‘patchworkGrob’ is not exported by 'namespace:patchwork'```

答:
I had the same issue, and I solved it by loading the library(patchwork) before loading clusterProfiler.

Hope it helps~

Title: clusterProfiler cannot load package


问:
Quarter function in Snowflake
I have written the "select" query for the quarter function in SAP HANA.

```<code>select QUARTER (CURRENT_DATE, 8) FROM DUMMY;

output: 2021-Q3
</code>```

Can someone please help me with the equivalent query in Snowflake?

Title: Quarter function in Snowflake

Body:
I have written the "select" query for the quarter function in SAP HANA.

select QUARTER (CURRENT_DATE, 8) FROM DUMMY;

output: 2021-Q3

Can someone please help me with the equivalent query in Snowflake?

Body:
As Lukasz points out the second parameter is the start_month SAP doc's

So this is really two parts, to know what year-quarter something is with respect to an offset, you just need to subtract the offset month, from the date you have and then year and quarter the adjusted date. AND formatting the STRING

The later point it seems cannot be done with one TO_CHAR with a format command. otherwise it would be really nice. So for now we will have to stick to YEAR(adj_date) || '-Q' || QUARTER(adj_date).

The long winded explaining SQL:

SELECT
    8 as first_month_of_fin_year
    ,first_month_of_fin_year - 1 as month_adj
    ,to_date(column1,'yyyy-mm') as in_date
    ,dateadd(month,-month_adj, in_date) as adj_date
    ,year(adj_date) as y
    ,quarter(adj_date) as q
    ,y::text || '-Q' || q::text as answer
FROM VALUES
  ('2021-06'),
  ('2021-07'),
  ('2021-08'),
  ('2021-09'),
  ('2021-10'),
  ('2021-11'),
  ('2021-12'),
  ('2022-01'),
  ('2022-02'),
  ('2022-03'),
  ('2022-04'),
  ('2022-05'),
  ('2022-06'),
  ('2022-07'),
  ('2022-08'),
  ('2022-09'),
  ('2022-10')
ORDER BY 1;

gives:

FIRST_MONTH_OF_FIN_YEAR
MONTH_ADJ
IN_DATE
ADJ_DATE
Y
Q
ANSWER

8
7
2021-06-01
2020-11-01
2020
4
2020-Q4

8
7
2021-07-01
2020-12-01
2020
4
2020-Q4

8
7
2021-08-01
2021-01-01
2021
1
2021-Q1

8
7
2021-09-01
2021-02-01
2021
1
2021-Q1

8
7
2021-10-01
2021-03-01
2021
1
2021-Q1

8
7
2021-11-01
2021-04-01
2021
2
2021-Q2

8
7
2021-12-01
2021-05-01
2021
2
2021-Q2

8
7
2022-01-01
2021-06-01
2021
2
2021-Q2

8
7
2022-02-01
2021-07-01
2021
3
2021-Q3

8
7
2022-03-01
2021-08-01
2021
3
2021-Q3

8
7
2022-04-01
2021-09-01
2021
3
2021-Q3

8
7
2022-05-01
2021-10-01
2021
4
2021-Q4

8
7
2022-06-01
2021-11-01
2021
4
2021-Q4

8
7
2022-07-01
2021-12-01
2021
4
2021-Q4

8
7
2022-08-01
2022-01-01
2022
1
2022-Q1

8
7
2022-09-01
2022-02-01
2022
1
2022-Q1

8
7
2022-10-01
2022-03-01
2022
1
2022-Q1

Smaller SQL

So a smaller/compact SQL can be written once we see what steps we are following as:

SELECT
    8 as start_month
    ,to_date(column1,'yyyy-mm') as in_date
    ,year(dateadd(month,-(start_month - 1), in_date)) || '-Q'
        || quarter(dateadd(month,-(start_month - 1), in_date)) as answer
FROM ...

or if you know you only want 8, and current_date

SELECT
    year(dateadd(month,-7, current_date)) || '-Q'
         || quarter(dateadd(month,-7, current_date)) as answer
;


问:
Angular 12, set variable from function
I'm developing a little tool where I need to populate a variable on component creation.
I've declared variable here:

```<code>export class HomeComponent implements OnInit {
myVar: any
</code>```

and try to set its value here:

```<code>  ngOnInit(): void {
    setInterval(() => this.myFunction(5), 3000);
  }

  myFunction(arg: number): void {
    this.data.forEach(function (this: HomeComponent, element: any) {
      if (element.id === number) {
        this.myVar = element.id;
      }
    });
  }
</code>```

but no value was passed and I get this error:
"ERROR TypeError: this is undefined"

Any idea?
Thank you in advice!

答:
It's not possible just to reference this: HomeComponent and send data to HomeComponent. Using this,that references belong to vanilla JS world, let's leave them there.

You have declared myFunction takes in one param type of number. Why haven't you supplied a number in setTimeout()? It can never work like that.

I don't see where is this.data coming from, so I am going to assume what you want to achieve here is when components are sharing data.

I am going to create an example for you where child component HelloComponent will send data to parent component AppComponent. A) When you click button send data and B) like your example, with setTimeout() delay.

We create a an event, that we emit from child and parent will catch the event and then show the data (string) carried by the event.

Child

@Component({
  selector: 'hello',
  template: `<h1><button (click)="sendMessage()">Send Message</button>`,
  styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
  message: string = 'Receiving Message from child';
  @Output() messageEvent = new EventEmitter<string>();

  ngOnInit(): void {
    setInterval(
      () => this.messageEvent.emit('hello, I am delayed meesage'),
      5000
    );
  }

  sendMessage() {
    this.messageEvent.emit(this.message);
  }
}
```
<p>Parent</p>
<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  message:string='';

  receiveMessage(sentMessage: string): void {
    this.message = sentMessage;
  }

}
</code>```

{{message}}
<hello (messageEvent)="receiveMessage($event)"></hello>

```

Here is a working example: https://stackblitz.com/edit/angular-child-parent-1-s9q62k?file=src%2Fapp%2Fhello.component.ts

Here is more info how to use @Input/@Output decorators. https://angular.io/guide/inputs-outputs

Title: Angular 12, set variable from function

Body:
I'm developing a little tool where I need to populate a variable on component creation.
I've declared variable here:

export class HomeComponent implements OnInit {
myVar: any

and try to set its value here:

  ngOnInit(): void {
    setInterval(() => this.myFunction(5), 3000);
  }

  myFunction(arg: number): void {
    this.data.forEach(function (this: HomeComponent, element: any) {
      if (element.id === number) {
        this.myVar = element.id;
      }
    });
  }

but no value was passed and I get this error:
"ERROR TypeError: this is undefined"

Any idea?
Thank you in advice!

Body:
It's not possible just to reference this: HomeComponent and send data to HomeComponent. Using this,that references belong to vanilla JS world, let's leave them there.

You have declared myFunction takes in one param type of number. Why haven't you supplied a number in setTimeout()? It can never work like that.

I don't see where is this.data coming from, so I am going to assume what you want to achieve here is when components are sharing data.

I am going to create an example for you where child component HelloComponent will send data to parent component AppComponent. A) When you click button send data and B) like your example, with setTimeout() delay.

We create a an event, that we emit from child and parent will catch the event and then show the data (string) carried by the event.

Child

@Component({
  selector: 'hello',
  template: `<h1><button (click)="sendMessage()">Send Message</button>`,
  styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
  message: string = 'Receiving Message from child';
  @Output() messageEvent = new EventEmitter<string>();

  ngOnInit(): void {
    setInterval(
      () => this.messageEvent.emit('hello, I am delayed meesage'),
      5000
    );
  }

  sendMessage() {
    this.messageEvent.emit(this.message);
  }
}

Parent

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  message:string='';

  receiveMessage(sentMessage: string): void {
    this.message = sentMessage;
  }

}

{{message}}
<hello (messageEvent)="receiveMessage($event)"></hello>

Here is a working example: https://stackblitz.com/edit/angular-child-parent-1-s9q62k?file=src%2Fapp%2Fhello.component.ts

Here is more info how to use @Input/@Output decorators. https://angular.io/guide/inputs-outputs


问:
GSON unable to serialize exception with Java 17
The following code used to work on Java 11:

```<code>new Gson().toJson(new Exception())
</code>```

On JDK 17 I get the following error:

```<code>Unable to make field private java.lang.String java.lang.Throwable.detailMessage accessible: module java.base does not "opens java.lang" to unnamed module @147ed70f
</code>```

From reading this page, I think I could resolve it with --add-opens java.base/java.lang=ALL-UNNAMED. Is there a better way however? Perhaps with a custom de/serializer?

答:
I had this yesterday. I was using Java 17. I went back to Java 11 and it worked fine.

I think it's because of this: https://bugs.openjdk.java.net/browse/JDK-8256358

I am lazy and using the GSON default reflection type adapter.

You have to implement your own TypeAdapter to fix it. Or perhaps use another JSON deserializer like Jackson, which I might do later.

Body:
The following code used to work on Java 11:

new Gson().toJson(new Exception())

On JDK 17 I get the following error:

Unable to make field private java.lang.String java.lang.Throwable.detailMessage accessible: module java.base does not "opens java.lang" to unnamed module @147ed70f

From reading this page, I think I could resolve it with --add-opens java.base/java.lang=ALL-UNNAMED. Is there a better way however? Perhaps with a custom de/serializer?


问:
How to apply classList.toggle("active") in reactjs
How to apply classList.toggle("active") in reactjs.
i create a two buttons and give onclick function togglePopup and define it at top. but i'm confused how to apply document.getElementById('popup-1').classList.toggle("active")in react. i apply this method in javaScript and i don't know how it is work in react?

Popup.jsx

```<code>const Filter = () => {
    const togglePopup = () => {
    document.getElementById('popup-1').classList.toggle("active")
    }
    return (
        <>
<button className='p-3 border bg-blue-400'>click</button>
            <div className="popup" id="popup-1">
                <div className="overlay"></div>
                <div className="content">
                    <div className="close-btn" onClick={togglePopup}>×</div>
                    <h1 className='text-2xl font-bold'>title</h1>
                    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Non debitis officia neque nostrum, perspiciatis sed quaerat veritatis numquam, explicabo dolorum aliquam illo dolor at nemo maxime consequatur facilis magni laudantium! Ipsa eveniet quam, illum quos laudantium a placeat temporibus dolores libero pariatur quibusdam atque impedit magnam nam ipsum, rerum sapiente?</p>
                </div>
            </div>
</code>```

Popup.css

```<code>.popup .overlay{
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100vw;
    height: 100vh;
    background:rgba(0, 0, 0, 0.7);
    z-index: 1;
    display: none;
}
.popup .content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    background: #fff;
    width: 450px;
    height: fit-content;
    z-index: 2;
    text-align: center;
    padding: 20px;
    box-sizing: border-box;
}

.popup .close-btn{
    position: absolute;
    right: 20px;
    top: 20px;
    width: 30px;
    height: 30px;
    background: #222;
    color: #fff;
    font-size: 25px;
    font-weight: 600;
    line-height:30px;
    text-align:center;
    border-radius: 50%;
    cursor: pointer;
}

.popup:active .overlay{
    display: block;
}
.popup:active .content{
    transition: all 300ms ease-in-out;
    transform: translate(-50%, -50%) scale(1);

}
</code>```

答:
You should not be querying or manipulating the DOM from React. If you want to toggle a class have your button update your component’s state and then render the markup according to that state.</p>
```<code>function MyComponent () {
  const [active, setActive] = useState(false);

  return (
    <div className={active ? 'active' : ''}>
      <button onClick={() => setActive(!active)}>Toggle</button>
    </div>
  )

}
</code>```

Body:
How to apply classList.toggle("active") in reactjs.
i create a two buttons and give onclick function togglePopup and define it at top. but i'm confused how to apply document.getElementById('popup-1').classList.toggle("active")in react. i apply this method in javaScript and i don't know how it is work in react?

Popup.jsx

const Filter = () => {
    const togglePopup = () => {
    document.getElementById('popup-1').classList.toggle("active")
    }
    return (
        <>
<button className='p-3 border bg-blue-400'>click</button>

×

title

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Non debitis officia neque nostrum, perspiciatis sed quaerat veritatis numquam, explicabo dolorum aliquam illo dolor at nemo maxime consequatur facilis magni laudantium! Ipsa eveniet quam, illum quos laudantium a placeat temporibus dolores libero pariatur quibusdam atque impedit magnam nam ipsum, rerum sapiente?

Popup.css

.popup .overlay{
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100vw;
    height: 100vh;
    background:rgba(0, 0, 0, 0.7);
    z-index: 1;
    display: none;
}
.popup .content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    background: #fff;
    width: 450px;
    height: fit-content;
    z-index: 2;
    text-align: center;
    padding: 20px;
    box-sizing: border-box;
}

.popup .close-btn{
    position: absolute;
    right: 20px;
    top: 20px;
    width: 30px;
    height: 30px;
    background: #222;
    color: #fff;
    font-size: 25px;
    font-weight: 600;
    line-height:30px;
    text-align:center;
    border-radius: 50%;
    cursor: pointer;
}

.popup:active .overlay{
    display: block;
}
.popup:active .content{
    transition: all 300ms ease-in-out;
    transform: translate(-50%, -50%) scale(1);

}

Body:
You should not be querying or manipulating the DOM from React. If you want to toggle a class have your button update your component’s state and then render the markup according to that state.

function MyComponent () {
  const [active, setActive] = useState(false);

  return (
    <div className={active ? 'active' : ''}>
      <button onClick={() => setActive(!active)}>Toggle</button>
    </div>
  )

}


问:
TensorFlow: how to create training and testing image datasets
I've been looking forever on the internet trying to create, train and test my own tensorflow model. But I have unsuccessfully done that. From investigating my code, I think it's how I create my dataset of images. Most online tutorials would just import a prepared dataset, but my dataset is specifically for use-case diagrams and holds each element within those diagrams. My aim is to train a tensorflow model to predict each element in a diagram and hopefully the errors too. Here's the code:

```<code>def createDataSet(labelList, label, filePath, width, height):
    dataList = []
    for img in os.listdir(filePath):
        filename = str(img)
        if filename[len(filename) - 3:len(filename)] != "npy":
            pic = cv.imread(os.path.join(filePath, img))
            pic = cv.cvtColor(pic, cv.COLOR_BGR2RGB)
            pic = cv.resize(pic, (width, height))
            dataList.append(pic)
            labelList.append(label)
return dataList, labelList
# appending the pics to the training data list
training_dataset, train_labels = createDataSet(train_labels, train_label, path, width, height)
test_dataset, test_labels = createDataSet(test_labels, test_label, path2, width, height)
#converting the list to numpy array and saving it to a file using #numpy.save
np.save(os.path.join(path,train_label),np.array(training_dataset))
np.save(os.path.join(path2,test_label),np.array(test_dataset))
#loading the saved file once again
train_images = np.array(training_dataset)
test_images = np.array(test_dataset)
</code>```

As of now, the function creates a list which will be saved as a numpy array and that numpy array will be used for my model. But it causes errors like UNIMPLEMENTED: Cast string to float is not supported.
I'm sure that I'm creating the train, test data and the labels for both incorrectly

答:
You can use tf.keras.utils.image_dataset_from_directory function read images form directory and split the data into training and validation. Find the below is sample code.

```<code>main_directory/
...class_a/
......a_image_1.jpg
......a_image_2.jpg
...class_b/
......b_image_1.jpg
......b_image_2.jpg

import tensorflow as tf
batch_size = 32
img_height = 224
img_width = 224

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

class_names = train_ds.class_names

val_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)
</code>```

Body:
I've been looking forever on the internet trying to create, train and test my own tensorflow model. But I have unsuccessfully done that. From investigating my code, I think it's how I create my dataset of images. Most online tutorials would just import a prepared dataset, but my dataset is specifically for use-case diagrams and holds each element within those diagrams. My aim is to train a tensorflow model to predict each element in a diagram and hopefully the errors too. Here's the code:

def createDataSet(labelList, label, filePath, width, height):
    dataList = []
    for img in os.listdir(filePath):
        filename = str(img)
        if filename[len(filename) - 3:len(filename)] != "npy":
            pic = cv.imread(os.path.join(filePath, img))
            pic = cv.cvtColor(pic, cv.COLOR_BGR2RGB)
            pic = cv.resize(pic, (width, height))
            dataList.append(pic)
            labelList.append(label)
return dataList, labelList
# appending the pics to the training data list
training_dataset, train_labels = createDataSet(train_labels, train_label, path, width, height)
test_dataset, test_labels = createDataSet(test_labels, test_label, path2, width, height)
#converting the list to numpy array and saving it to a file using #numpy.save
np.save(os.path.join(path,train_label),np.array(training_dataset))
np.save(os.path.join(path2,test_label),np.array(test_dataset))
#loading the saved file once again
train_images = np.array(training_dataset)
test_images = np.array(test_dataset)

As of now, the function creates a list which will be saved as a numpy array and that numpy array will be used for my model. But it causes errors like UNIMPLEMENTED: Cast string to float is not supported.
I'm sure that I'm creating the train, test data and the labels for both incorrectly

Body:
You can use tf.keras.utils.image_dataset_from_directory function read images form directory and split the data into training and validation. Find the below is sample code.

main_directory/
...class_a/
......a_image_1.jpg
......a_image_2.jpg
...class_b/
......b_image_1.jpg
......b_image_2.jpg

import tensorflow as tf
batch_size = 32
img_height = 224
img_width = 224

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

class_names = train_ds.class_names

val_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)


问:
TypeError: unsupported operand type(s) for +=: 'dict' and 'str'
student scores:

```<code>student_scores = {
  "Harry": 81,
  "Ron": 78,
  "Hermione": 99,
  "Draco": 74,
  "Neville": 62,
}
</code>```

My goal is to print a dictionary with the students and the scores.

E.g. '{'Harry': 'Exceeds Expectations', 'Ron': 'Acceptable', 'Hermione': 'Outstanding', 'Draco': 'Acceptable', 'Neville': 'Fail'}'

Here is the scoring criteria:

Scores 91 - 100: Grade = "Outstanding"

Scores 81 - 90: Grade = "Exceeds Expectations"

Scores 71 - 80: Grade = "Acceptable"

Scores 70 or lower: Grade = "Fail"

Here is my code:

```<code>student_scores = {
  "Harry": 81,
  "Ron": 78,
  "Hermione": 99,
  "Draco": 74,
  "Neville": 62,

student_grades = {}

for key in student_scores:
    if student_scores[key] >= 91:
        student_scores[key] = "Outstanding"
    elif student_scores[key] >= 81:
        student_scores[key] = "Exceeds Expectations"
    elif student_scores[key] >= 71:
        student_scores[key] = "Acceptable"
    elif student_scores[key] <= 70:
        student_scores[key] = "Fail"
    student_grades += key
    student_grades[key] += student_scores[key]

print(student_grades)
</code>```

When I tried to run my code, I got this error:

```<code>Traceback (most recent call last):
  File "main.py", line 23, in <module>
    student_grades += key
TypeError: unsupported operand type(s) for +=: 'dict' and 'str'
</code>```

What did I do wrong?

答:
As the exception message points out, the line student_grades += key isn't doing anything that makes sense. student_grades is an (initially empty) dictionary, and key is a string with the name of a student in it. You can't add those things together. I'm not even sure what you intended it to do, so I can't exactly tell you what to do differently to achieve your objective.

What I do see is that you're modifying the dictionary with the input scores in place in the if/elif blocks. Perhaps you don't want to be doing that? If you changed all the assignment statements to use student_grades instead of student_scores (while leaving the references to students_scores in the if and elif conditions), you'd probably get what you wanted, without any extra steps:

```<code>for key in student_scores:
    if student_scores[key] >= 91:
        student_grades[key] = "Outstanding"   # change to student_grades here
    elif student_scores[key] >= 81:
        student_grades[key] = "Exceeds Expectations"  # and here
    elif student_scores[key] >= 71:
        student_grades[key] = "Acceptable"            # and here
    elif student_scores[key] <= 70:
        student_grades[key] = "Fail"                  # here too
</code>```

As a bonus, you won't have clobbered the student_scores dict after this loop, so you can still refer back to it if necessary.

Body:
student scores:

student_scores = {
  "Harry": 81,
  "Ron": 78,
  "Hermione": 99,
  "Draco": 74,
  "Neville": 62,
}

My goal is to print a dictionary with the students and the scores.

E.g. '{'Harry': 'Exceeds Expectations', 'Ron': 'Acceptable', 'Hermione': 'Outstanding', 'Draco': 'Acceptable', 'Neville': 'Fail'}'

Here is the scoring criteria:

Scores 91 - 100: Grade = "Outstanding"

Scores 81 - 90: Grade = "Exceeds Expectations"

Scores 71 - 80: Grade = "Acceptable"

Scores 70 or lower: Grade = "Fail"

Here is my code:

student_scores = {
  "Harry": 81,
  "Ron": 78,
  "Hermione": 99,
  "Draco": 74,
  "Neville": 62,

student_grades = {}

for key in student_scores:
    if student_scores[key] >= 91:
        student_scores[key] = "Outstanding"
    elif student_scores[key] >= 81:
        student_scores[key] = "Exceeds Expectations"
    elif student_scores[key] >= 71:
        student_scores[key] = "Acceptable"
    elif student_scores[key] <= 70:
        student_scores[key] = "Fail"
    student_grades += key
    student_grades[key] += student_scores[key]

print(student_grades)

When I tried to run my code, I got this error:

Traceback (most recent call last):
  File "main.py", line 23, in <module>
    student_grades += key
TypeError: unsupported operand type(s) for +=: 'dict' and 'str'

What did I do wrong?

Body:
As the exception message points out, the line student_grades += key isn't doing anything that makes sense. student_grades is an (initially empty) dictionary, and key is a string with the name of a student in it. You can't add those things together. I'm not even sure what you intended it to do, so I can't exactly tell you what to do differently to achieve your objective.

What I do see is that you're modifying the dictionary with the input scores in place in the if/elif blocks. Perhaps you don't want to be doing that? If you changed all the assignment statements to use student_grades instead of student_scores (while leaving the references to students_scores in the if and elif conditions), you'd probably get what you wanted, without any extra steps:

for key in student_scores:
    if student_scores[key] >= 91:
        student_grades[key] = "Outstanding"   # change to student_grades here
    elif student_scores[key] >= 81:
        student_grades[key] = "Exceeds Expectations"  # and here
    elif student_scores[key] >= 71:
        student_grades[key] = "Acceptable"            # and here
    elif student_scores[key] <= 70:
        student_grades[key] = "Fail"                  # here too

As a bonus, you won't have clobbered the student_scores dict after this loop, so you can still refer back to it if necessary.


问:
How to select all text in a tk input box (ruby)
Just coming up to speed with tk / ruby.

I have a very simple window with a one line text input area, a "go" button, and a feedback label.

The desired behavior is that a user enters some text, hits the "go" button, and the code does some work.

When its all over the input box should have the text entered, but it should be highlighted and the focus in the input box, so that if the user begins typing again what was in the box will be overwritten.

In .net this was pretty easy, just say .selectall to the input field.  can't figure out how to do it in tk.

```<code>    root = TkRoot.new {title "Test App"}
content = Tk::Tile::Frame.new(root) {padding "3 3 12 12"}.grid( :sticky => 'nsew')
TkGrid.columnconfigure root, 0, :weight => 1; TkGrid.rowconfigure root, 0, :weight => 1
$job= TkVariable.new; $status = TkVariable.new
$j = Tk::Tile::Entry.new(content) {
      width 14; textvariable $job}.grid( :column => 1, :row => 1, :sticky => 'we' )
Tk::Tile::Button.new(content) {
         text 'Find Job'
         command {go_do_something}
       }.grid( :column => 2, :row => 1, :sticky => 'w')

    def go_do_something
       # ... do some processing, then I want to...
       # $j.focus
       # $j.select_all
    end
</code>```

Thanks in advance

答:
Looks like you need to add all of the widget's text to the special "sel" (selection) tag.

What your sw adds to the sel tag will become selected on the screen.

See docs

Body:
Just coming up to speed with tk / ruby.

I have a very simple window with a one line text input area, a "go" button, and a feedback label.

The desired behavior is that a user enters some text, hits the "go" button, and the code does some work.

When its all over the input box should have the text entered, but it should be highlighted and the focus in the input box, so that if the user begins typing again what was in the box will be overwritten.

In .net this was pretty easy, just say .selectall to the input field.  can't figure out how to do it in tk.

    root = TkRoot.new {title "Test App"}
content = Tk::Tile::Frame.new(root) {padding "3 3 12 12"}.grid( :sticky => 'nsew')
TkGrid.columnconfigure root, 0, :weight => 1; TkGrid.rowconfigure root, 0, :weight => 1
$job= TkVariable.new; $status = TkVariable.new
$j = Tk::Tile::Entry.new(content) {
      width 14; textvariable $job}.grid( :column => 1, :row => 1, :sticky => 'we' )
Tk::Tile::Button.new(content) {
         text 'Find Job'
         command {go_do_something}
       }.grid( :column => 2, :row => 1, :sticky => 'w')

    def go_do_something
       # ... do some processing, then I want to...
       # $j.focus
       # $j.select_all
    end

Thanks in advance


问:
Bucket names not being appended to a list
I'm trying to append to the public_buckets list all the bucket names of buckets that have BlockPublicAcls and BlockPublicPolicy set to False. For this, I'm using a counter that means the bucket is public when it is equal to 2.

```<code>filtered_buckets = list(filter(lambda item: not list_in_list(exceptions, item['Name']), buckets))
public_buckets = []

def check_bucket_access_block():
    for bucket in filtered_buckets:
        try:
            response = s3client.get_public_access_block(Bucket=bucket['Name'])
            for key, value in response['PublicAccessBlockConfiguration'].items():
                logger.info('Bucket: {}, {}: {}'.format(bucket['Name'], key, value))
                count = 0
                if key == response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and value == False:
                    count += 1
                if key == response['PublicAccessBlockConfiguration']['BlockPublicPolicy'] and value == False:
                    count += 1
                if count == 2 and bucket['Name'] not in public_buckets:
                    public_buckets.append(bucket['Name'])
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchPublicAccessBlockConfiguration':
                print("Bucket: {} has no Public Access Block Configuration".format(bucket['Name']))
            else:
                print("unexpected error: %s" % (e.response))
</code>```

I know there are a few buckets in the filtered_buckets list with both key values set to False. However, they are not being appended to the list.

When I print the public_buckets list it returns an empty [].

This is the response syntax:

```<code>{
    'PublicAccessBlockConfiguration': {
        'BlockPublicAcls': True|False,
        'IgnorePublicAcls': True|False,
        'BlockPublicPolicy': True|False,
        'RestrictPublicBuckets': True|False
    }
}
</code>```

I don't know if that's a logical mistake - in the if statements - or maybe a type mismatch.

Any idea?

答:
Your logic in this line isn't doing what you expect:

```<code>if key == response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and value == False:
</code>```

response['PublicAccessBlockConfiguration']['BlockPublicAcls'] will return True or False -- it's returning the Value for that dictionary entry, not the Key.

Instead, you could use:

if not response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and not response['PublicAccessBlockConfiguration']['BlockPublicPolicy'] and bucket['Name'] not in public_buckets:
    public_buckets.append(bucket['Name'])
```

This will append the bucket name if BlockPublicAcls and BlockPublicAcls are both False and the bucket is not already in the list.

Body:
I'm trying to append to the public_buckets list all the bucket names of buckets that have BlockPublicAcls and BlockPublicPolicy set to False. For this, I'm using a counter that means the bucket is public when it is equal to 2.

filtered_buckets = list(filter(lambda item: not list_in_list(exceptions, item['Name']), buckets))
public_buckets = []

def check_bucket_access_block():
    for bucket in filtered_buckets:
        try:
            response = s3client.get_public_access_block(Bucket=bucket['Name'])
            for key, value in response['PublicAccessBlockConfiguration'].items():
                logger.info('Bucket: {}, {}: {}'.format(bucket['Name'], key, value))
                count = 0
                if key == response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and value == False:
                    count += 1
                if key == response['PublicAccessBlockConfiguration']['BlockPublicPolicy'] and value == False:
                    count += 1
                if count == 2 and bucket['Name'] not in public_buckets:
                    public_buckets.append(bucket['Name'])
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchPublicAccessBlockConfiguration':
                print("Bucket: {} has no Public Access Block Configuration".format(bucket['Name']))
            else:
                print("unexpected error: %s" % (e.response))

I know there are a few buckets in the filtered_buckets list with both key values set to False. However, they are not being appended to the list.

When I print the public_buckets list it returns an empty [].

This is the response syntax:

{
    'PublicAccessBlockConfiguration': {
        'BlockPublicAcls': True|False,
        'IgnorePublicAcls': True|False,
        'BlockPublicPolicy': True|False,
        'RestrictPublicBuckets': True|False
    }
}

I don't know if that's a logical mistake - in the if statements - or maybe a type mismatch.

Any idea?

Body:
Your logic in this line isn't doing what you expect:

if key == response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and value == False:

response['PublicAccessBlockConfiguration']['BlockPublicAcls'] will return True or False -- it's returning the Value for that dictionary entry, not the Key.

Instead, you could use:

if not response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and not response['PublicAccessBlockConfiguration']['BlockPublicPolicy'] and bucket['Name'] not in public_buckets:
    public_buckets.append(bucket['Name'])

This will append the bucket name if BlockPublicAcls and BlockPublicAcls are both False and the bucket is not already in the list.


问:
Ng-select style issue
After install ng-select with :

```<code>npm install --save @ng-select/ng-select
</code>```

I'm importing the material style to styles.scss with :

```<code>@import "~@ng-select/ng-select/themes/material.theme.css";
</code>```

body {

But after all, the component is being presented with a very strange appearance.

Lookin at node_modules folder I can't see the ng-select folder to look at it's themes folder.

Any ideas please ?

答:
In Angular 13
Add this code in your angular.json styles block :</p>
```<code>       "styles": [
         ....
         ....
          "node_modules/@ng-select/ng-select/themes/default.theme.css",
        ],
</code>```

Title: Ng-select style issue

Body:
After install ng-select with :

npm install --save @ng-select/ng-select

I'm importing the material style to styles.scss with :

@import "~@ng-select/ng-select/themes/material.theme.css";

body {

But after all, the component is being presented with a very strange appearance.

Lookin at node_modules folder I can't see the ng-select folder to look at it's themes folder.

Any ideas please ?

Body:
In Angular 13
Add this code in your angular.json styles block :

       "styles": [
         ....
         ....
          "node_modules/@ng-select/ng-select/themes/default.theme.css",
        ],


问:
How to input value from different table range in SQL
I want to ask how to enter NULL in Table 2 with values in LITHOLOGY column.

Thanks

Table 1

LITHOLOGY
SITE_ID
DEPTH_FROM
DEPTH_TO

BXg
DB-01
0.00
4.50

BXg2
DB-01
4.50
10.00

BXg2
DB-02
4.00
10.00

BXg2
DB-02
0.00
4.00

Table 2

SITE_ID
DEPTH_FROM
DEPTH_TO
CORE_RECOV
LITHOLOGY

DB-01
0.00
2.00
0.20

DB-01
2.00
4.00
0.30

DB-01
4.00
6.00
0.22

DB-01
6.00
8.00
0.32

DB-01
8.00
10.00
0.42

DB-02
0.00
3.00
0.12

DB-02
3.00
5.00
0.42

DB-02
5.00
10.00
0.92

答:
As per your question, the below will put NULL in every LITHOLOGY column where LITHOLOGY is not null.

If you want to replace blank fields with null use WHERE LITHOLOGY = '' instead

```<code>UPDATE Table2
SET LITHOLOGY = NULL
WHERE LITHOLOGY IS NOT NULL;
</code>```

Body:
As per your question, the below will put NULL in every LITHOLOGY column where LITHOLOGY is not null.

If you want to replace blank fields with null use WHERE LITHOLOGY = '' instead

UPDATE Table2
SET LITHOLOGY = NULL
WHERE LITHOLOGY IS NOT NULL;


问:
Protobuf-net - Serialize only a few properties
It is possible to serialize only a few properties of the class?
ex:

```<code>public class Client
{
   [ProtoMember(1)]
   public int Id { get; set; }

   [ProtoMember(2)]
   public string Name { get; set; }

   public int Age { get; set; }

   [ProtoMember(3)]
   public string Guid { get; set; }
}
</code>```

Thus, I get the value of "Id" incorrect. The other properties are correct.
If I fill it with "[ProtoMember]" all the properties, the value of "id" is correct.
Why?

Actually the error is caused by other reasons you may be able to help me.

I convert String to Stream to perform tasks. In time to reverse this conversion I have error in the value of Id

```<code>var cli = new Client
{ Id = 222, Guid = "52369-fe5r6-74e2g-j1i4e", Age = 29, Name = "José"};

//Serialize
var ms = new MemoryStream();
Serializer.Serialize(ms, cli);
ms.Position = 0;
var reader = new StreamReader(ms);
var strStream = reader.ReadToEnd();

//Deserialize
var ms2 = new MemoryStream(Encoding.UTF8.GetBytes(strStream));

var obj = Serializer.Deserialize<Client>(ms2);
</code>```

Thus, any value above 127, is converted to a different Int. Ex: 3104751

My conversion is wrong?

Obs: I'm sorry the poor English

答: It is. Just make sure to include the [ProtoContract] attribute for the class and use the exact same contract when serializing and deserializing.</p>

Body:
It is possible to serialize only a few properties of the class?
ex:

public class Client
{
   [ProtoMember(1)]
   public int Id { get; set; }

   [ProtoMember(2)]
   public string Name { get; set; }

   public int Age { get; set; }

   [ProtoMember(3)]
   public string Guid { get; set; }
}

Thus, I get the value of "Id" incorrect. The other properties are correct.
If I fill it with "[ProtoMember]" all the properties, the value of "id" is correct.
Why?

Actually the error is caused by other reasons you may be able to help me.

I convert String to Stream to perform tasks. In time to reverse this conversion I have error in the value of Id

var cli = new Client
{ Id = 222, Guid = "52369-fe5r6-74e2g-j1i4e", Age = 29, Name = "José"};

//Serialize
var ms = new MemoryStream();
Serializer.Serialize(ms, cli);
ms.Position = 0;
var reader = new StreamReader(ms);
var strStream = reader.ReadToEnd();

//Deserialize
var ms2 = new MemoryStream(Encoding.UTF8.GetBytes(strStream));

var obj = Serializer.Deserialize<Client>(ms2);

Thus, any value above 127, is converted to a different Int. Ex: 3104751

My conversion is wrong?

Obs: I'm sorry the poor English