问:
Getting ValueError("Confirm that ",img," exists") while grouping same person pics in a folder using DeepFace
I am trying to group same person images in a folder with many pictures. I am using deepface for this.
Mainly I am using DeepFace.verify(). If the verified value is true I am renaming the image.
I thought as I am using Windows OS so may be because of the path extension It may be causing error, but after using correct format, the error still occur.

```<code>
```
1/1 [==============================] - 2s 2s/step
Traceback (most recent call last):
  File "C:\Users\Tejasmaya Sitha\PycharmProjects\FacialRecognitionProject\GroupingFaces.py", line 38, in <module>
    result = DeepFace.verify(img1_path=rf'{img1path}', img2_path=rf'{img2}', model_name="Facenet")
  File "C:\Python\lib\site-packages\deepface\DeepFace.py", line 170, in verify
    img2_representation = represent(img_path = img2_path
  File "C:\Python\lib\site-packages\deepface\DeepFace.py", line 754, in represent
    img = functions.preprocess_face(img = img_path
  File "C:\Python\lib\site-packages\deepface\commons\functions.py", line 175, in preprocess_face
    img = load_image(img)
  File "C:\Python\lib\site-packages\deepface\commons\functions.py", line 90, in load_image
    raise ValueError("Confirm that ",img," exists")
ValueError: ('Confirm that ', 'C:\\Users\\Tejasmaya Sitha\\OneDrive\\Desktop\\New folder\\IMG_20210325_231110.jpg', ' exists')
```

</code>```

The Program :

```<code>
```
# take some pics for training datasets
testing_dataset = []

print("Enter upto 10 pics for Training DataSet")

def takepics():
    trainpic = input("Enter the path of the pic: ").strip('"')
    # trainpic = 'r"'+trainpic+'"'
    if trainpic == "" or len(testing_dataset) == 10:
        pass
    elif len(testing_dataset) == 10:
        print('Max no of testing pics')
    else:
        testing_dataset.append(trainpic)
        takepics()

takepics()  # Take pics for training dataset
print(testing_dataset)

import os
from deepface import DeepFace

print()
testing_directory = input('Enter the directory( Containing only IMAGES ) for testing for similar pic: ')
testing_directory = testing_directory
print('Provided directory:', testing_directory)
if os.path.isdir(rf'{testing_directory}'):
    # os.chdir(testing_directory)
    files = os.listdir(rf'{testing_directory}')
    # print(files)
    # os.mkdir('Result Set')
    for img1 in files:
        for img2 in testing_dataset:
            print(img1, img2)
            img1path = testing_directory + '\\' + img1
            result = DeepFace.verify(img1_path=rf'{img1path}', img2_path=rf'{img2}', model_name="Facenet")
            if result['verified']:
                print(img1)
                i = 0
                newname = 'Manita' + str(i) + ".jpg"
                oldname = testing_directory + '\\\\' + img1
                newname = testing_directory + '\\\\' + newname
                os.rename(oldname, newname)
                i += 1
            else:
                continue

else:
    print('The Entered path is not a directory.')

```

</code>```

If anyone can find the solution please help...

The program should take upto 10 confirmed image paths for training dataset/comparing dataset and then take the folder path to test all images in it.

I am getting error while it compares the folder image with comparing image.

Body:
I am trying to group same person images in a folder with many pictures. I am using deepface for this.
Mainly I am using DeepFace.verify(). If the verified value is true I am renaming the image.
I thought as I am using Windows OS so may be because of the path extension It may be causing error, but after using correct format, the error still occur.

```
1/1 [==============================] - 2s 2s/step
Traceback (most recent call last):
  File "C:\Users\Tejasmaya Sitha\PycharmProjects\FacialRecognitionProject\GroupingFaces.py", line 38, in <module>
    result = DeepFace.verify(img1_path=rf'{img1path}', img2_path=rf'{img2}', model_name="Facenet")
  File "C:\Python\lib\site-packages\deepface\DeepFace.py", line 170, in verify
    img2_representation = represent(img_path = img2_path
  File "C:\Python\lib\site-packages\deepface\DeepFace.py", line 754, in represent
    img = functions.preprocess_face(img = img_path
  File "C:\Python\lib\site-packages\deepface\commons\functions.py", line 175, in preprocess_face
    img = load_image(img)
  File "C:\Python\lib\site-packages\deepface\commons\functions.py", line 90, in load_image
    raise ValueError("Confirm that ",img," exists")
ValueError: ('Confirm that ', 'C:\\Users\\Tejasmaya Sitha\\OneDrive\\Desktop\\New folder\\IMG_20210325_231110.jpg', ' exists')
```

The Program :

```
# take some pics for training datasets
testing_dataset = []

print("Enter upto 10 pics for Training DataSet")

def takepics():
    trainpic = input("Enter the path of the pic: ").strip('"')
    # trainpic = 'r"'+trainpic+'"'
    if trainpic == "" or len(testing_dataset) == 10:
        pass
    elif len(testing_dataset) == 10:
        print('Max no of testing pics')
    else:
        testing_dataset.append(trainpic)
        takepics()

takepics()  # Take pics for training dataset
print(testing_dataset)

import os
from deepface import DeepFace

print()
testing_directory = input('Enter the directory( Containing only IMAGES ) for testing for similar pic: ')
testing_directory = testing_directory
print('Provided directory:', testing_directory)
if os.path.isdir(rf'{testing_directory}'):
    # os.chdir(testing_directory)
    files = os.listdir(rf'{testing_directory}')
    # print(files)
    # os.mkdir('Result Set')
    for img1 in files:
        for img2 in testing_dataset:
            print(img1, img2)
            img1path = testing_directory + '\\' + img1
            result = DeepFace.verify(img1_path=rf'{img1path}', img2_path=rf'{img2}', model_name="Facenet")
            if result['verified']:
                print(img1)
                i = 0
                newname = 'Manita' + str(i) + ".jpg"
                oldname = testing_directory + '\\\\' + img1
                newname = testing_directory + '\\\\' + newname
                os.rename(oldname, newname)
                i += 1
            else:
                continue

else:
    print('The Entered path is not a directory.')

```

If anyone can find the solution please help...

The program should take upto 10 confirmed image paths for training dataset/comparing dataset and then take the folder path to test all images in it.

I am getting error while it compares the folder image with comparing image.


来源: stackexchange

问:
How to record a video using CameraX, that correctly saves the video if a crash occurs?
I'm looking for a way to record a video that can survive an app crash, without the file being corrupt.

I've tried to kill my app during a video-recording and ended up with an unplayable mp4-file, however if I have the correct tools I can resotre the video file correctly using some third-party software (which is not what I'm looking for).

I was hoping to find a way to instead do something smart with the video-file when I start the recording and/or during the recording, so that the video-file won't end up corrupt if the app crashes.

Does anyone know how to implement this robustness for a video-recording using the CameraX API?

ContentLicense: CC BY-SA 4.0


问:
How to control touchpad scroll in a carousel component
I am working on a carousel component where elements change on an up and down scroll. When you're scrolling with your mouse everything works pretty nicely but the touchpad scroll sometimes scrolls the elements all the way to the end. The component can be viewed here: https://2r70m7.csb.app/. Is it possible to somehow control a single touchpad scroll, so that no matter how intense it is, it can only move a single element in the carousel?

Thanks


问:
Removing duplicate rows based on some of the columns
I have this problem where I need to remove duplicates from my data base, but the rows aren't identical.

For example, lets say this is my scheme:
(id,name,revirew,uid)

After uploading the data to the database, I have the following rows:

123,Dan,"very good",1000
123,Dan,"very good",2000
```

I want to keep only the first row, because it's the same review but was recorded with different uid, how can I achieve that? (meaning, it's not exactly a duplicate, but in my database it counts as one).

note: my original problem is that I downloaded a reviews dateset that was crawled.
The problem is that there are identical reviews but with different ids generated, so I need to remove them. for simplicity purposes I gave this simple example.

EDIT:
I want to keep the row with lower uid.

I've searched and only found ways for removing duplicate rows, but in this case they are not really identical thus not considered duplicates and won't be removed.

[SOLVED]:
SELECT id,name,revirew, MIN(uid) FROM ... GROUP BY id,name,revirew;
solved the problem, solution from the comments, by @Atom

Body:
I have this problem where I need to remove duplicates from my data base, but the rows aren't identical.

For example, lets say this is my scheme:
(id,name,revirew,uid)

After uploading the data to the database, I have the following rows:

123,Dan,"very good",1000
123,Dan,"very good",2000

I want to keep only the first row, because it's the same review but was recorded with different uid, how can I achieve that? (meaning, it's not exactly a duplicate, but in my database it counts as one).

note: my original problem is that I downloaded a reviews dateset that was crawled.
The problem is that there are identical reviews but with different ids generated, so I need to remove them. for simplicity purposes I gave this simple example.

EDIT:
I want to keep the row with lower uid.

I've searched and only found ways for removing duplicate rows, but in this case they are not really identical thus not considered duplicates and won't be removed.

[SOLVED]:
SELECT id,name,revirew, MIN(uid) FROM ... GROUP BY id,name,revirew;
solved the problem, solution from the comments, by @Atom


问:
NGINX throwing 400 whenever the request is having headers key with space
In below request, second header is having space which is causing the issue. If we remove it and hit the API it works fine otherwise 400 bad request error.

The same curl was working until 1.17 NGINX version, but after that we are facing the issue.
Please suggest any solution for it

Request:

```<code>curl -ks --location --request GET 'https://<hostname>/employees' \
> --header 'emp_id: 110' \
> --header 'abcd xyz: hello'
</code>```

Response:

```<code><html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.23.2</center>
</body>
</html>
</code>```

Body:
In below request, second header is having space which is causing the issue. If we remove it and hit the API it works fine otherwise 400 bad request error.

The same curl was working until 1.17 NGINX version, but after that we are facing the issue.
Please suggest any solution for it

Request:

curl -ks --location --request GET 'https://<hostname>/employees' \
> --header 'emp_id: 110' \
> --header 'abcd xyz: hello'

Response:

<title>400 Bad Request</title>

400 Bad Request

nginx/1.23.2


问:
Vue 3 Carousel unexpected behavior
I have a Vue3 carousel inside a Single file component

package.json

"vue3-carousel": "^0.1.40"

SFC

```<code>import { Carousel, Slide, Navigation } from 'vue3-carousel';
import 'vue3-carousel/dist/carousel.css';
import '@/assets/scss/Carousel.scss';

       <Carousel :wrap-around="true" class="box-carousel" :autoplay="2000" :transition="500">
          <Slide v-for="slide in slides" :key="slide.id">
            <div class="mx-auto w-[85%] md:w-[90%] rounded-lg p-5 bg-blue-secondary-5 h-full dark:bg-blue-secondary-5 dark:text-black-dark-100">
              <!-- Box Description -->
              <div class="grid grid-cols-5 gap-5 mb-5">
                  <div class="col-span-1">
                    <div class="rounded-full h-11 w-11 bg-black-20 flex items-center justify-center">
                      <p class="uppercase font-bold text-sm">{{slide.title}}</p>
                    </div>
                  </div>
                  <div class="col-span-4 text-left">
                    <div class="ml-3 md:ml-0">
                      <p class="font-bold">{{slide.name}}</p>
                      <p class="text-black-40 text-xs">{{slide.date}}</p>
                    </div>
                  </div>
              </div>
              <!-- End Box Description -->

              <!-- Box Comment -->
              <div class="text-left mb-8">
                <p class="text-sm  ">
                  {{slide.comment.substring(0,130)}}
                </p>
              </div>
              <!-- End Box Comment -->

              <!-- Box Actions -->
              <div class="grid grid-cols-6 gap-5 absolute bottom-5">
                <div class="col-span-2">
                  <a href="javascript:void(0)" class="flex items-center text-xs md:text-sm relative top-1 text-blue-secondary-100">
                    <UndoIcon width="10" class="fill-blue-secondary-100 mr-2 hidden md:block" />
                    Responder
                  </a>
                </div>
                <div class="col-span-2">
                  <a href="javascript:void(0)" class="flex items-center text-xs md:text-sm relative top-1 text-black-40 underline">
                    Ver contexto
                  </a>
                </div>
                <div class="col-span-2">
                  <p class="text-xs md:text-sm flex items-center justify-end md:justify-start relative top-1">
                    <span class="h-2 w-2 rounded-full bg-green-primary-100 inline-block mr-5 md:mr-1 relative top-[-1px]"></span>
                    <span class="hidden md:block">aprovado</span>
                  </p>
                </div>
              </div>
              <!-- End Box Actions -->

            </div>
          </Slide>

          <template #addons>
            <Navigation />
          </template>
        </Carousel>
</code>```

But the transition behavior of the slides is not as expected. It is just changing withouth the transition/translate position effect

This is how it is:

Expected effect: (by the way, the carousel sometimes spontaneously display the expected behavior like when after some hot module replacement refresh happens after saving some edit in VSCode and there is a refresh in the vue app like this):

Thanks in advance for any advice!! Happy new year !!

Title: Vue 3 Carousel unexpected behavior

Body:
I have a Vue3 carousel inside a Single file component

package.json

"vue3-carousel": "^0.1.40"

SFC

import { Carousel, Slide, Navigation } from 'vue3-carousel';
import 'vue3-carousel/dist/carousel.css';
import '@/assets/scss/Carousel.scss';

       <Carousel :wrap-around="true" class="box-carousel" :autoplay="2000" :transition="500">
          <Slide v-for="slide in slides" :key="slide.id">

{{slide.title}}

{{slide.name}}

{{slide.date}}

                  {{slide.comment.substring(0,130)}}

                    <UndoIcon width="10" class="fill-blue-secondary-100 mr-2 hidden md:block" />
                    Responder

                    Ver contexto

                    aprovado

          </Slide>

          <template #addons>
            <Navigation />
          </template>
        </Carousel>

But the transition behavior of the slides is not as expected. It is just changing withouth the transition/translate position effect

This is how it is:

Expected effect: (by the way, the carousel sometimes spontaneously display the expected behavior like when after some hot module replacement refresh happens after saving some edit in VSCode and there is a refresh in the vue app like this):

Thanks in advance for any advice!! Happy new year !!


问:
Couchbase Java SDK subdocument mutation
Hi Im running couchabse server 7.1.3 docker container and trying to use the 3.3.4 couchbase java sdk version. I am facing an issue while performing subdocument mutation using the upsert command.

The issue I am facing is when I use the collection.mutateIn() method to perform a subdocument mutation using the upsert command, I am expecting to get the result of the operation as a MutateInResult object. when I try to use the MutateInResult.contentAs(0, String.class) to see the response I get the Index 0 is invalid error. I see that the operation as in is successful in the DB, I can see the desired json path has the updated value.

P.S: I only have a single mutation to perform which is the upsert command.

can someone please help if I am missing something here?

Title: Couchbase Java SDK subdocument mutation


问:
Gitattributes ignored by github
I have uploaded some projects on my GitHub using the web interface. The project is code written in a py file and a rapport + code written in ipynb. This has led to Jupiter notebook becoming my top languages. I don’t want that.

I have tried to add a reposetoryname.gitattributes file and this line of code in the file

```<code>Prosjekt_Teknisk_fysikk.ipynb linguist-detectable=false
</code>```

I expected this to show python as the only language used in the repo. This however did not happen, and the ratio is unchanged. I know github uses caching and it takes a while for the change to show. I have waited more than 10 hours, so I don’t think It has to do with that. I have also tried to delete and reupload using the web browser.

Edit also tried

```<code>Prosjekt_Biofysikk.ipynb -linguist-vendored
</code>```

nothing happened

Title: Gitattributes ignored by github

Body:
I have uploaded some projects on my GitHub using the web interface. The project is code written in a py file and a rapport + code written in ipynb. This has led to Jupiter notebook becoming my top languages. I don’t want that.

I have tried to add a reposetoryname.gitattributes file and this line of code in the file

Prosjekt_Teknisk_fysikk.ipynb linguist-detectable=false

I expected this to show python as the only language used in the repo. This however did not happen, and the ratio is unchanged. I know github uses caching and it takes a while for the change to show. I have waited more than 10 hours, so I don’t think It has to do with that. I have also tried to delete and reupload using the web browser.

Edit also tried

Prosjekt_Biofysikk.ipynb -linguist-vendored

nothing happened


问:
How To Add Migrations Function By C# Code and run it on created database in EF but Not By PackageManagerConsole
I have written a program that is running and I cannot delete the database. Now I want to add a series of new properties to the database tables. I know that I should use migration, but the point is that I have written the connection string manually with ConfigurationManager class and its functions, not in app.config. But now I have encountered a problem to add a new migration and update the database.

My question here is how to do the new migration and database update as code functions in C# instead of using package manager console and its commands i.e add-migration & update-database.

After many searches, I found a series of solutions like this link https://stackoverflow.com/questions/20216147/entity-framework-change-connection-at-runtime?answertab=modifieddesc#tab-top and using IDBConnectionIntercaptor, but in The test environment creates this database face with the error Cannot attach the file '***' as database '+++' .

my connection function is :
`

```<code>public static bool Connect(bool force = false)
        {
            bool result = false;

            var selectedDb = new EventsDataContext();

            selectedDb.ChangeDatabase
                (
                    initialCatalog: Maincsb.InitialCatalog,
                    userId: "",
                    password: "",
                    dataSource: Maincsb.DataSource
                );
            EventsDataContext odb = null;
            try
            {
                ConnectionInterceptor connectionInterceptor = new ConnectionInterceptor
                {
                    connectionString = ConnectionManager.Maincsb.ConnectionString
                };
                DbInterception.Add(connectionInterceptor);
                DbInterception.Add(new ModifyYeKeIntercpetor());

                odb = new EventsDataContext();
                odb.Database.Initialize(force);

                Seeder(Maincsb.ConnectionString);
                result = true;
            }
            catch (Exception e)
            {
                ErrorMessage.Show(e);
                result = false;
            }
            finally
            {
                odb.Dispose();
                odb = null;
            }
            return result;
        }
</code>```

`

And if the database has already been created, it will face the error that the database has changed and new features will not be added to the database.

Body:
I have written a program that is running and I cannot delete the database. Now I want to add a series of new properties to the database tables. I know that I should use migration, but the point is that I have written the connection string manually with ConfigurationManager class and its functions, not in app.config. But now I have encountered a problem to add a new migration and update the database.

My question here is how to do the new migration and database update as code functions in C# instead of using package manager console and its commands i.e add-migration & update-database.

After many searches, I found a series of solutions like this link https://stackoverflow.com/questions/20216147/entity-framework-change-connection-at-runtime?answertab=modifieddesc#tab-top and using IDBConnectionIntercaptor, but in The test environment creates this database face with the error Cannot attach the file '***' as database '+++' .

my connection function is :
`

public static bool Connect(bool force = false)
        {
            bool result = false;

            var selectedDb = new EventsDataContext();

            selectedDb.ChangeDatabase
                (
                    initialCatalog: Maincsb.InitialCatalog,
                    userId: "",
                    password: "",
                    dataSource: Maincsb.DataSource
                );
            EventsDataContext odb = null;
            try
            {
                ConnectionInterceptor connectionInterceptor = new ConnectionInterceptor
                {
                    connectionString = ConnectionManager.Maincsb.ConnectionString
                };
                DbInterception.Add(connectionInterceptor);
                DbInterception.Add(new ModifyYeKeIntercpetor());

                odb = new EventsDataContext();
                odb.Database.Initialize(force);

                Seeder(Maincsb.ConnectionString);
                result = true;
            }
            catch (Exception e)
            {
                ErrorMessage.Show(e);
                result = false;
            }
            finally
            {
                odb.Dispose();
                odb = null;
            }
            return result;
        }

`

And if the database has already been created, it will face the error that the database has changed and new features will not be added to the database.


问:
How To Change Seek bar Color in Android?
I'm just wondering if the seekbar changed in Android 2.1 . I tried to create one but it showing up as a green line with a circle on it instead of the usual yellow rectangle. If so, is there any other option to create a similar seekbar to control volume on 2.1? Thanks</p>

ContentLicense: CC BY-SA 3.0


问:
How to connect ODBC source to on-premises data gateway in power bi server?
Every time I am trying to create an on-premises data source using ODBC, I am getting this error. Can anyone explain to me what the problem is??

This error occurs every time

The ODBC connection used for the same report in power bi desktop


问:
Cookies in .NET Core 6
I am trying to make web application with .NET on the backend and React on the frontend. I make session on the backend and I want to save it on Application > Cookies in the browser.

When I make request for login and it is successfull server return in response header set-cookie property in which is the session. But it is not added in Application > Cookie.

That's how I make the request:

```<code>axios.post(`https://localhost:7153/login`, {
            username: username,
            password: password
        }, {
            withCredentials: true
        })
        .catch(error => {
            console.log(error)
        })

</code>```

Title: Cookies in .NET Core 6

Body:
I am trying to make web application with .NET on the backend and React on the frontend. I make session on the backend and I want to save it on Application > Cookies in the browser.

When I make request for login and it is successfull server return in response header set-cookie property in which is the session. But it is not added in Application > Cookie.

That's how I make the request:

axios.post(`https://localhost:7153/login`, {
            username: username,
            password: password
        }, {
            withCredentials: true
        })
        .catch(error => {
            console.log(error)
        })


问:
error CS0103: The name 'Host' does not exist in the current context
I created a .NET Framework 4.8 Console application in Visual Studio 2019, to which I added the nuget package Microsoft.Extensions.Hosting, that means, in the .csproj file I added the line:

```<code><PackageReference Include="Microsoft.Extensions.Hosting" />
</code>```

Program.cs looks as follows:

```<code>using System;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            using (IHost host = Host.CreateDefaultBuilder(args).Build())
            {
                Console.WriteLine("ok");
                Console.ReadKey();
            }
        }
    }
}
</code>```

When I compile, I get the error:

```<code>1>C:\temp\ConsoleApp4\Program.cs(22,33,22,37): error CS0103: The name 'Host' does not exist in the current context
</code>```

However the Host class is in the namespace Microsoft.Extensions.Hosting.

How can I make this work?

Which is the correct way to use dependency injection in .NET Framework 4.8 Console application?

Body:
I created a .NET Framework 4.8 Console application in Visual Studio 2019, to which I added the nuget package Microsoft.Extensions.Hosting, that means, in the .csproj file I added the line:

<PackageReference Include="Microsoft.Extensions.Hosting" />

Program.cs looks as follows:

using System;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            using (IHost host = Host.CreateDefaultBuilder(args).Build())
            {
                Console.WriteLine("ok");
                Console.ReadKey();
            }
        }
    }
}

When I compile, I get the error:

1>C:\temp\ConsoleApp4\Program.cs(22,33,22,37): error CS0103: The name 'Host' does not exist in the current context

However the Host class is in the namespace Microsoft.Extensions.Hosting.

How can I make this work?

Which is the correct way to use dependency injection in .NET Framework 4.8 Console application?


问:
Webpack: Module parse failed: Unexpected token
Getting this error with loadable components after building using webpack.
I have tried lots of solutions from stackoverflow but nothing works for me.

```<code>ERROR in ../src/pages/EngineeringUI/index.js 9:14
Module parse failed: Unexpected token (9:14)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import PageLoader from '@xyz/atoms/PageLoader';
| const LoadableEngineeringUI = loadable(() => import('./EngineeringUI'), {
>     fallback: <PageLoader />,
| });
| export default LoadableEngineeringUI;
 @ ./src/web/NestedRouter.js 29:0-132 142:29-42
 @ ./src/web/MainRouter.js 4:0-42 18:15-27
 @ ./src/web/App.js 26:0-38 77:95-105
 @ ./src/web/index.js 4:0-24 7:50-53
 @ ./src/index.js
</code>```

here is my devDependancies:-

```<code>"devDependencies": {
        "@babel/core": "^7.3.4",
        "@babel/plugin-proposal-class-properties": "^7.18.6",
        "@babel/plugin-syntax-dynamic-import": "^7.7.4",
        "@babel/polyfill": "^7.7.0",
        "@babel/preset-env": "^7.7.4",
        "@babel/preset-flow": "^7.7.4",
        "@babel/preset-react": "^7.7.4",
        "@loadable/babel-plugin": "^5.13.2",
        "@loadable/webpack-plugin": "^5.15.2",
        "ajv": "^8.11.2",
        "babel-loader": "^8.0.5",
        "babel-preset-es2015": "6.3.13",
        "cheerio": "^1.0.0-rc.12",
        "clean-webpack-plugin": "^4.0.0",
        "css-loader": "^3.2.1",
        "cz-conventional-changelog": "^3.0.2",
        "exports-loader": "^0.6.4",
        "file-loader": "^5.1.0",
        "html-loader": "^0.5.1",
        "less-loader": "^4.0.5",
        "react-app-rewired": "2.1.8",
        "script-loader": "^0.7.1",
        "semantic-ui": "^2.4.2",
        "standard-version": "^7.0.1",
        "style-loader": "^1.0.1",
        "terser-webpack-plugin": "^2.3.5",
        "url-loader": "^3.0.0",
        "webpack": "^5.38.1",
        "webpack-cli": "^4.9.1",
        "webpack-dev-server": "^4.11.1"
    },
</code>```

also added these rules in webpack.config.js file-

```<code>module: {
      rules: [{
          test: /\.m?(js|ts)x?$/,
          include: [
             path.resolve(__dirname, 'src'),
             path.resolve(__dirname, 'packages/apis/src'),
             path.resolve(__dirname, 'packages/atoms/src'),
             path.resolve(__dirname, 'packages/molecules/src'),
             path.resolve(__dirname, 'packages/organisms/src'),
             path.resolve(__dirname, 'packages/pages/src'),
             path.resolve(__dirname, 'packages/units/src'),
             path.resolve(__dirname, 'packages/themes/themes'),
             path.resolve(__dirname, 'packages/store/src'),
          ],
          resolve: {
            fullySpecified: false,
          },
          use: {
            loader: 'babel-loader',
            // options: {
            //   presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-flow', {
            //     'plugins': ['@babel/plugin-proposal-class-properties']
            //   }]
            // },
          },

        },
        {
          test: /\.xlsx$/,
          loader: "xlsx-loader"
        },
        {
          test: /\.html$/,
          use: {
            loader: 'html-loader',
            options: {
              attrs: false,
            },
          },
        },
        {
          test: /\.less$/,
          use: [{
              loader: 'style-loader',
            },
            {
              loader: 'css-loader',
            },
            {
              loader: 'less-loader',
            },
          ],
        },
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader'],
        },
        {
          test: /\.(woff|woff2|eot|ttf)$/,
          use: {
            loader: 'url-loader',
            options: {
              name: 'fonts/[contenthash].[ext]',
            },
          },
        },
        {
          test: /\.(jpg|jpeg|png|svg|gif)$/,
          use: {
            loader: 'url-loader',
            options: {
              name: 'img/[contenthash].[ext]',
            },
          },
        },
      ],
    },
</code>```

I have tried lots of solution from stack overflow like adding presets options but nothing work for me

Body:
Getting this error with loadable components after building using webpack.
I have tried lots of solutions from stackoverflow but nothing works for me.

ERROR in ../src/pages/EngineeringUI/index.js 9:14
Module parse failed: Unexpected token (9:14)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import PageLoader from '@xyz/atoms/PageLoader';
| const LoadableEngineeringUI = loadable(() => import('./EngineeringUI'), {
>     fallback: <PageLoader />,
| });
| export default LoadableEngineeringUI;
 @ ./src/web/NestedRouter.js 29:0-132 142:29-42
 @ ./src/web/MainRouter.js 4:0-42 18:15-27
 @ ./src/web/App.js 26:0-38 77:95-105
 @ ./src/web/index.js 4:0-24 7:50-53
 @ ./src/index.js

here is my devDependancies:-

"devDependencies": {
        "@babel/core": "^7.3.4",
        "@babel/plugin-proposal-class-properties": "^7.18.6",
        "@babel/plugin-syntax-dynamic-import": "^7.7.4",
        "@babel/polyfill": "^7.7.0",
        "@babel/preset-env": "^7.7.4",
        "@babel/preset-flow": "^7.7.4",
        "@babel/preset-react": "^7.7.4",
        "@loadable/babel-plugin": "^5.13.2",
        "@loadable/webpack-plugin": "^5.15.2",
        "ajv": "^8.11.2",
        "babel-loader": "^8.0.5",
        "babel-preset-es2015": "6.3.13",
        "cheerio": "^1.0.0-rc.12",
        "clean-webpack-plugin": "^4.0.0",
        "css-loader": "^3.2.1",
        "cz-conventional-changelog": "^3.0.2",
        "exports-loader": "^0.6.4",
        "file-loader": "^5.1.0",
        "html-loader": "^0.5.1",
        "less-loader": "^4.0.5",
        "react-app-rewired": "2.1.8",
        "script-loader": "^0.7.1",
        "semantic-ui": "^2.4.2",
        "standard-version": "^7.0.1",
        "style-loader": "^1.0.1",
        "terser-webpack-plugin": "^2.3.5",
        "url-loader": "^3.0.0",
        "webpack": "^5.38.1",
        "webpack-cli": "^4.9.1",
        "webpack-dev-server": "^4.11.1"
    },

also added these rules in webpack.config.js file-

module: {
      rules: [{
          test: /\.m?(js|ts)x?$/,
          include: [
             path.resolve(__dirname, 'src'),
             path.resolve(__dirname, 'packages/apis/src'),
             path.resolve(__dirname, 'packages/atoms/src'),
             path.resolve(__dirname, 'packages/molecules/src'),
             path.resolve(__dirname, 'packages/organisms/src'),
             path.resolve(__dirname, 'packages/pages/src'),
             path.resolve(__dirname, 'packages/units/src'),
             path.resolve(__dirname, 'packages/themes/themes'),
             path.resolve(__dirname, 'packages/store/src'),
          ],
          resolve: {
            fullySpecified: false,
          },
          use: {
            loader: 'babel-loader',
            // options: {
            //   presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-flow', {
            //     'plugins': ['@babel/plugin-proposal-class-properties']
            //   }]
            // },
          },

        },
        {
          test: /\.xlsx$/,
          loader: "xlsx-loader"
        },
        {
          test: /\.html$/,
          use: {
            loader: 'html-loader',
            options: {
              attrs: false,
            },
          },
        },
        {
          test: /\.less$/,
          use: [{
              loader: 'style-loader',
            },
            {
              loader: 'css-loader',
            },
            {
              loader: 'less-loader',
            },
          ],
        },
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader'],
        },
        {
          test: /\.(woff|woff2|eot|ttf)$/,
          use: {
            loader: 'url-loader',
            options: {
              name: 'fonts/[contenthash].[ext]',
            },
          },
        },
        {
          test: /\.(jpg|jpeg|png|svg|gif)$/,
          use: {
            loader: 'url-loader',
            options: {
              name: 'img/[contenthash].[ext]',
            },
          },
        },
      ],
    },

I have tried lots of solution from stack overflow like adding presets options but nothing work for me


问:
Setting "traffic-split" Parameter for multiple models deployed on vertex ai
I want to update the traffic as 50% and 50% for two deployed models on same endpoint(Vertex AI). I am using following command but it is not working.

gcloud ai endpoints update 2003578466645041111 --region=us-central1 --traffic-split=[DEPLOYED_MODEL_ID=4779212008081850368=50,DEPLOYED_MODEL_ID=6143661957686755328=50]  --service-account= ********* --project= **********

In --traffic-split parameter I am passing the IDs of models deployed and percentage of traffic I wanted to set. I tried with many values instead of 50 such as 0.5, .5 etc but its not working. Even I tried removing the word "DEPLOYED_MODEL_ID" and just kept model id and value in the list.

gcloud ai endpoints update 2003578466645041111 --region=us-central1 --traffic-split=[4779212008081850368=50,6143661957686755328=50]  --service-account= ********* --project= **********


问:
Nuxt 3 render same page on multiple routes
I'm having a nuxt 3 app with file routing activated. I'm having a problem where I have two routes that should render the same dynamic page.

My pages directory looks like this:

This is how I want my paths render the pages:

```<code>(1) /          --> [lang]/index.vue
(2) /DE        --> [lang]/index.vue
(3) /EN        --> [lang]/index.vue
(4) /DE/Header --> [lang]/Header/index.vue
(5) /EN/Header --> [lang]/Header/index.vue
</code>```

Routes 2 to 5 render correctly. My problem is that route 1 renders /index.vue (which is an expected behaviour), but I want it to render the content from [lang]/index.vue. At the moment I copied the content to have it synced in both index.vue files, but I want to avoid copying the whole file.

I already tried a navigateTo() inside the root index.vue, but that causes both pages to render. Also, I tried to add some router options file like that:

```<code>export default <RouterConfig>{
  routes: (_routes) => [
    {
      name: 'index',
      path: '/',
      component: () => import('~/pages/[id]/index.vue'),
    },
  ],
}
</code>```

but then no child routes are working anymore.

How can I achieve that route 1 (/) renders the page under pages/[lang]/index.vue?

Body:
I'm having a nuxt 3 app with file routing activated. I'm having a problem where I have two routes that should render the same dynamic page.

My pages directory looks like this:

This is how I want my paths render the pages:

(1) /          --> [lang]/index.vue
(2) /DE        --> [lang]/index.vue
(3) /EN        --> [lang]/index.vue
(4) /DE/Header --> [lang]/Header/index.vue
(5) /EN/Header --> [lang]/Header/index.vue

Routes 2 to 5 render correctly. My problem is that route 1 renders /index.vue (which is an expected behaviour), but I want it to render the content from [lang]/index.vue. At the moment I copied the content to have it synced in both index.vue files, but I want to avoid copying the whole file.

I already tried a navigateTo() inside the root index.vue, but that causes both pages to render. Also, I tried to add some router options file like that:

export default <RouterConfig>{
  routes: (_routes) => [
    {
      name: 'index',
      path: '/',
      component: () => import('~/pages/[id]/index.vue'),
    },
  ],
}

but then no child routes are working anymore.

How can I achieve that route 1 (/) renders the page under pages/[lang]/index.vue?


问:
docker - RTMP nginx server access only from phone
I am quite new to this Docker universe. What I am trying to do is creating a RTMP server which I can stream to from my phone and then use VLC media player to playback the network stream.

I installed this container tiangolo/nginx-rtmp and ran it. My first problem was finding the right IP, but I found out it being the WSL ethernet IP). From my own PC where I have docker, I am able to stream (via OBS) to the RTMP server and pickup the networkstream with VLC. However, when I try to stream from my phone, the URL or network connection can not connect to the server. It must be a network or portforward problem. I've attached my /etc/nginx/nginx.conf file that I have tried to add a some things to hopefully make it accessible from my phone as well. I've found the commands from this list of commands for nginx.

```<code>worker_processes auto;
rtmp_auto_push on;
events {}
rtmp {
    server {
        listen 1935;
        listen [::]:1935 ipv6only=on;

        application webcam {
            live on;
            record off;
            allow publish 127.0.0.1;
            pull rtmp://172.24.160.1/webcam;
            allow play all;
            allow publish all;
        }
    }
}
</code>```

I've not done anything else but to install docker, install the image and edited the conf without luck.

I've tried to change the configuration file of nginx to have the right network settings, but I am still not able to connect to the RTMP from my phone.

Body:
I am quite new to this Docker universe. What I am trying to do is creating a RTMP server which I can stream to from my phone and then use VLC media player to playback the network stream.

I installed this container tiangolo/nginx-rtmp and ran it. My first problem was finding the right IP, but I found out it being the WSL ethernet IP). From my own PC where I have docker, I am able to stream (via OBS) to the RTMP server and pickup the networkstream with VLC. However, when I try to stream from my phone, the URL or network connection can not connect to the server. It must be a network or portforward problem. I've attached my /etc/nginx/nginx.conf file that I have tried to add a some things to hopefully make it accessible from my phone as well. I've found the commands from this list of commands for nginx.

worker_processes auto;
rtmp_auto_push on;
events {}
rtmp {
    server {
        listen 1935;
        listen [::]:1935 ipv6only=on;

        application webcam {
            live on;
            record off;
            allow publish 127.0.0.1;
            pull rtmp://172.24.160.1/webcam;
            allow play all;
            allow publish all;
        }
    }
}

I've not done anything else but to install docker, install the image and edited the conf without luck.

I've tried to change the configuration file of nginx to have the right network settings, but I am still not able to connect to the RTMP from my phone.


问:
passing multiple arguments to a thread pool executor
I am writing a code to run pool executor and use a function with two arguments.

```<code>    args=[(0,users[0]),(1,users[1]),(2,users[2]),(3,users[3]),(4,users[4]),(5,users[5]),(6,users[6])]

    if __name__ == '__main__':
        with concurrent.futures.ThreadPoolExecutor() as executor:
            results=[executor.submit(do_all,(a,b)) for (a,b) in args]

            for result in concurrent.futures.as_completed(results):
                print(result)`
</code>```

I think the problem here is in the unpacking, but I couldn't do it with all trials

Please need support

I need to run it as expected

Body:
I am writing a code to run pool executor and use a function with two arguments.

    args=[(0,users[0]),(1,users[1]),(2,users[2]),(3,users[3]),(4,users[4]),(5,users[5]),(6,users[6])]

    if __name__ == '__main__':
        with concurrent.futures.ThreadPoolExecutor() as executor:
            results=[executor.submit(do_all,(a,b)) for (a,b) in args]

            for result in concurrent.futures.as_completed(results):
                print(result)`

I think the problem here is in the unpacking, but I couldn't do it with all trials

Please need support

I need to run it as expected


问:
RJS error in rails
I am working in rails 2.3.8 and I got following rjs error in my rails application.

```<code>RJS error:
TypeError: $("#create_event_dialog") is nul
</code>```

Then I click ok, then come another one.

```<code>Element.update("create_event", "<form action=\"/countries\" class=\"new_country\"   id=\"new_country\" method=\"post\" onsubmit=\"new Ajax.Request('/countries', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"authenticity_token\" type=\"hidden\" value=\"qWXCu2zMmlMhJG+GRf35kMbAIfzYAtFBee142ThmmMw=\" /></div>\n <p>\n    <label for=\"country_name\">Name</label><br />\n    <input id=\"country_name\" name=\"country[name]\" size=\"30\" type=\"text\" />\n  </p>\n  <p>\n    <input id=\"country_submit\" name=\"commit\" type=\"submit\" value=\"Create\" />\n  </p>\n</form>");
$('#create_event_dialog').dialog({
    title: 'New Event',
    modal: true,
    width: 500,
    close: function(event, ui) { $('#create_event_dialog').dialog('destroy') }

});
</code>```

Here's my code...

```<code><%= link_to_remote 'Add new countries', :url => {:controller => 'countries', :action => 'new'} %>

<div id = "create_event_dialog" style ="display:none;">
<div id = "create_event"></div>
</div>
</code>```

new.js.rjs::

```<code>page.replace_html 'create_event', :partial => 'form'
page<< "$('#create_event_dialog').dialog({
    title: 'New Event',
    modal: true,
    width: 500,
    close: function(event, ui) { $('#create_event_dialog').dialog('destroy') }

});"
</code>```

create.js.rjs

```<code>if @country
if @country.save

page<<"$('#create_event_dialog').dialog('destroy')"
else
page.alert @country.errors.full_messages(',').join("\n")
end
end
</code>```

_form.html.erb

```<code><%remote_form_for @country, :url => {:controller => 'countries', :action => 'create' } do |f| %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
</code>```

Can anybody help me? Why did I get this error?

Title: RJS error in rails

Body:
I am working in rails 2.3.8 and I got following rjs error in my rails application.

RJS error:
TypeError: $("#create_event_dialog") is nul

Then I click ok, then come another one.

Element.update("create_event", "<form action=\"/countries\" class=\"new_country\"   id=\"new_country\" method=\"post\" onsubmit=\"new Ajax.Request('/countries', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\">
<input name=\"authenticity_token\" type=\"hidden\" value=\"qWXCu2zMmlMhJG+GRf35kMbAIfzYAtFBee142ThmmMw=\" />
\n
\n    Name
\n    <input id=\"country_name\" name=\"country[name]\" size=\"30\" type=\"text\" />\n
\n
\n    <input id=\"country_submit\" name=\"commit\" type=\"submit\" value=\"Create\" />\n
\n</form>");
$('#create_event_dialog').dialog({
    title: 'New Event',
    modal: true,
    width: 500,
    close: function(event, ui) { $('#create_event_dialog').dialog('destroy') }

});

Here's my code...

<%= link_to_remote 'Add new countries', :url => {:controller => 'countries', :action => 'new'} %>

new.js.rjs::

page.replace_html 'create_event', :partial => 'form'
page<< "$('#create_event_dialog').dialog({
    title: 'New Event',
    modal: true,
    width: 500,
    close: function(event, ui) { $('#create_event_dialog').dialog('destroy') }

});"

create.js.rjs

if @country
if @country.save

page<<"$('#create_event_dialog').dialog('destroy')"
else
page.alert @country.errors.full_messages(',').join("\n")
end
end

_form.html.erb

<%remote_form_for @country, :url => {:controller => 'countries', :action => 'create' } do |f| %>

<%= f.label :name %>

<%= f.text_field :name %>

<%= f.submit 'Create' %>

<% end %>

Can anybody help me? Why did I get this error?


问:
How do you create a component with a default Slot and include it in the main layout in Qwik?
Let's say I want to create my own Link.

```<code>const Link = ({ href, style }) => {
    return <a href={href} class={style}>
        <Slot />
    </a>
}
</code>```

Now I want to use this Link in the Menu of my website, and the Menu component is imported inside the main layout.

```<code>// main layout

<Menu />
<Slot />
<Footer />
</code>```

Here, I get this error:

[vite] Internal server error:  can not be rendered because one of its ancestor is already a .
This goes against the HTML spec: https://html.spec.whatwg.org/multipage/dom.html#interactive-content

Why does this happen? It's because inside the main layout, we practically included another <Slot /> by including <Menu /> which contains <Link /> components.

So, what do you think we should do here?

If we ask all developers to specify the name of the slot, that's highly inefficient and dirty:

```<code><Link href="/">
    <span q:slot='link'>About us</span>
</Link>
</code>```

This is very ugly and inefficient. I don't have many slots in my Link component. I have one Slot. I should not be specifying a name for it.

What should I do?

Body:
Let's say I want to create my own Link.

const Link = ({ href, style }) => {
    return
        <Slot />

}

Now I want to use this Link in the Menu of my website, and the Menu component is imported inside the main layout.

// main layout

<Menu />
<Slot />

Here, I get this error:

[vite] Internal server error:  can not be rendered because one of its ancestor is already a .
This goes against the HTML spec: https://html.spec.whatwg.org/multipage/dom.html#interactive-content

Why does this happen? It's because inside the main layout, we practically included another <Slot /> by including <Menu /> which contains <Link /> components.

So, what do you think we should do here?

If we ask all developers to specify the name of the slot, that's highly inefficient and dirty:

<Link href="/">
    About us
</Link>

This is very ugly and inefficient. I don't have many slots in my Link component. I have one Slot. I should not be specifying a name for it.

What should I do?


问:
Error parsing custom _id type in go mongodb project
I'm building a go project using mongodb as a database.

In order to make the code easily maintainable, i created a mongo provider package that is the single point of contact between my project and mongo-driver/mongo. That way I only use my own implementations in the rest of the project.

I wrapped the whole native driver with my own implementations. The only problem I encounter is with the primitive.ObjectID type.

Obviously, my structures are stored in an internal models package like this :

type StoredUser struct {
     Id       my_mongo_driver.Id `bson:"_id,omitempty"`
     Username string             `bson:"username"`
}
```

As you see, the models package does not have any contact with the native mongo-driver/mongo package. This is what I want.

In the my_mongo_driver package, I tried reimplementing the Id type by two different ways :

type Id primitive.ObjectID

type Id struct {primitive.ObjectID}

In both cases, I get an error when parsing the database results :

First approach : error decoding key _id: cannot decode objectID into an array

Second approach : error decoding key _id: cannot decode objectID into a my_mongo_driver.Id

How can I properly isolate my packages if my models need to use the exact native type for the parsing to work ?

Body:
I'm building a go project using mongodb as a database.

In order to make the code easily maintainable, i created a mongo provider package that is the single point of contact between my project and mongo-driver/mongo. That way I only use my own implementations in the rest of the project.

I wrapped the whole native driver with my own implementations. The only problem I encounter is with the primitive.ObjectID type.

Obviously, my structures are stored in an internal models package like this :

type StoredUser struct {
     Id       my_mongo_driver.Id `bson:"_id,omitempty"`
     Username string             `bson:"username"`
}

As you see, the models package does not have any contact with the native mongo-driver/mongo package. This is what I want.

In the my_mongo_driver package, I tried reimplementing the Id type by two different ways :

type Id primitive.ObjectID

type Id struct {primitive.ObjectID}

In both cases, I get an error when parsing the database results :

First approach : error decoding key _id: cannot decode objectID into an array

Second approach : error decoding key _id: cannot decode objectID into a my_mongo_driver.Id

How can I properly isolate my packages if my models need to use the exact native type for the parsing to work ?


问:
Converting column names to date within a pandas dataframe - warning of deprecated date comparison
I have a pandas dataframe where only a few columns are dates.

Example of a dataframe (dates here for the sake of example are str but in my case they are an object):

```<code>df = pd.DataFrame({
    "activity": ["clean dishes", "fix porch", "slep on couch"],
    "finished": ["NaT", "NaT", "2022-12-29"],
    "2022-12-27 00:00:00": [1,1,1],
    "2022-12-28 00:00:00": [1,1,1],
    "2022-12-29 00:00:00": [1,1,0]
})

    print(df.columns)
    Index(['activity', 'finished', 2022-12-27 00:00:00, 2022-12-28 00:00:00, 2022-12-29 00:00:00], dtype='object')
</code>```

I want to convert the last three column names to date (don't want the timestamp included) so that I can compare the dates in the finished column with the different column names and place a zero where activity is finished before.
I tried using this approach but did not work (including suggestion in the comments).

To achieve my goal I created this:

```<code>from datetime import datetime
import pandas as pd

    def format_header_dates(dataframe):
        """Converting the dates in the header to date"""
        for column in dataframe.columns:
            if isinstance(column, pd.Timestamp):
                new_column = pd.Timestamp(column).date()
                dataframe = dataframe.rename(columns={column: new_column})

        return dataframe

df = format_header_dates(df)
</code>```

However I get this warning:

```<code>FutureWarning: Comparison of Timestamp with datetime.date is deprecated in order to match the standard library behavior. In a future version these will be considered non-comparable. Use 'ts == pd.Timestamp(date)' or 'ts.date() == date' instead.
  return key in self._engine
</code>```

This leaves me with two questions:

Is there a better way to convert a subset of column names to date?

What exactly is causing this warning (isinstance?) and how can I make the necessary corrections?

Solution:

After spending two days scratching my head and googling, I could not pinpoint the root cause of the FutureWarning but got my way around it.

Step 1: Convert every date to datetime64[ns] and normalize it (to set h:m:s:ns to zero as I have no interest in such precision) with the following: pd.to_datetime(column).normalize().to_datetime64()

Step 2: Do whatever operations I wanted to, which in my case required comparing dates.

Step 3: Cosmetically adjust the dates by keeping only the date component with: pd.to_datetime(column).to_datetime64().astype('datetime64[D]')

This allowed me to do any date operations I wanted and no longer displayed the FutureWarning: Comparison of Timestamp with datetime.date is deprecated...

Body:
I have a pandas dataframe where only a few columns are dates.

Example of a dataframe (dates here for the sake of example are str but in my case they are an object):

df = pd.DataFrame({
    "activity": ["clean dishes", "fix porch", "slep on couch"],
    "finished": ["NaT", "NaT", "2022-12-29"],
    "2022-12-27 00:00:00": [1,1,1],
    "2022-12-28 00:00:00": [1,1,1],
    "2022-12-29 00:00:00": [1,1,0]
})

    print(df.columns)
    Index(['activity', 'finished', 2022-12-27 00:00:00, 2022-12-28 00:00:00, 2022-12-29 00:00:00], dtype='object')

I want to convert the last three column names to date (don't want the timestamp included) so that I can compare the dates in the finished column with the different column names and place a zero where activity is finished before.
I tried using this approach but did not work (including suggestion in the comments).

To achieve my goal I created this:

from datetime import datetime
import pandas as pd

    def format_header_dates(dataframe):
        """Converting the dates in the header to date"""
        for column in dataframe.columns:
            if isinstance(column, pd.Timestamp):
                new_column = pd.Timestamp(column).date()
                dataframe = dataframe.rename(columns={column: new_column})

        return dataframe

df = format_header_dates(df)

However I get this warning:

FutureWarning: Comparison of Timestamp with datetime.date is deprecated in order to match the standard library behavior. In a future version these will be considered non-comparable. Use 'ts == pd.Timestamp(date)' or 'ts.date() == date' instead.
  return key in self._engine

This leaves me with two questions:

Is there a better way to convert a subset of column names to date?

What exactly is causing this warning (isinstance?) and how can I make the necessary corrections?

Solution:

After spending two days scratching my head and googling, I could not pinpoint the root cause of the FutureWarning but got my way around it.

Step 1: Convert every date to datetime64[ns] and normalize it (to set h:m:s:ns to zero as I have no interest in such precision) with the following: pd.to_datetime(column).normalize().to_datetime64()

Step 2: Do whatever operations I wanted to, which in my case required comparing dates.

Step 3: Cosmetically adjust the dates by keeping only the date component with: pd.to_datetime(column).to_datetime64().astype('datetime64[D]')

This allowed me to do any date operations I wanted and no longer displayed the FutureWarning: Comparison of Timestamp with datetime.date is deprecated...


问:
Save StreamTitle tag in recording
Some streams have StreamTitle tag set and it changes from time to time. Is that information send only when it changes in the stream? For example in this stream StreamTitle is used to tell the artist and the name of current song:

```<code>ffprobe -v error -show_entries format_tags http://st.downtime.fi/sun.mp3
</code>```

Is the StreamTitle tag exclusive to MP3 streams? Can one have it in Opus streams as well?

Can such information be added to the output file created when recording the stream by ffmpeg for example, to be able to see which song is playing when playing the recording later? Could another tag be used to tell program name which may also alter in time?

Title: Save StreamTitle tag in recording

Body:
Some streams have StreamTitle tag set and it changes from time to time. Is that information send only when it changes in the stream? For example in this stream StreamTitle is used to tell the artist and the name of current song:

ffprobe -v error -show_entries format_tags http://st.downtime.fi/sun.mp3

Is the StreamTitle tag exclusive to MP3 streams? Can one have it in Opus streams as well?

Can such information be added to the output file created when recording the stream by ffmpeg for example, to be able to see which song is playing when playing the recording later? Could another tag be used to tell program name which may also alter in time?


问:
.OBJ File - Texture mapping
I am trying to understand the texture mapping of an OBJ File.

Lets say we have a String line that looks like this:

f 11/27/2 9/61/2 41/62/2 25/28/2, with f indicating that the line is reffering to the face of a Polygon.

This is the line no. 8114 of the file wooden watch tower2.obj for which I put a link
here.

The format of line matches the one right here:

f <integer A_V>/<integer A_VT>/<integer A_VN> <integer B_V>/...  (see article: Wavefront - Wikipedia),

with <integer A_VT> being a texture coordinate index e.g. 27 referencing vt 0.4877 0.2630,

which I suppose when scaled up by the textures dimensions 0.4877 * texture.width and 0.2630 * texture.height gives you some x and y coordinate to a pixel of the texture (Wood_Tower_Col.jpg in my case).

But if that would be correct, the number of texture coordinates (4018) would match up with  the number of vertices (3845). What am I doing wrong?

Title: .OBJ File - Texture mapping


问:
How we can know what accesses to the specific address on armeabi-v7a?
I am have android game and there is address for Player Camera, and I want to know what accesses to the Player Camera Address?
for example when I am run same game on android emulator (game loop emulator), and get camera address on cheat engine and choose "find out what accesses this address" cheat engine show me what addresses accesses to the camera address.
how we can do that inside android without ceserver? I know we can find that by "ptrace" but I dont have any source. any idea?

I tried to using ceserver but all time there is crash because that game using anti debug.


问:
How can I fix ModuleNotFoundError: No module named 'similarity.normalized_levenshtein'?
So I keep having this error ModuleNotFoundError: No module named 'similarity.normalized_levenshtein' in my error log for some reasons.

This is what I was trying to do:

```<code>from similarity.normalized_levenshtein import NormalizedLevenshtein
normalized_levenshtein = NormalizedLevenshtein()
</code>```

This is what was shown:

```<code>Traceback (most recent call last):
  File "API.py", line 10, in <module>
    import nlp3_model
  File "C:\Users\Admin\ai-challenge\nlp-3-api\fastml\lib\site-packages\import_ipynb.py", line 61, in load_module
    exec(code, mod.__dict__)
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'similarity.normalized_levenshtein'
(fastml)
</code>```

I have already installed similarity, python-levenshtein, and Levenshtein according to what was in pip list.

Also it's weird because when I tried to run my .ipynb notebook with this line, it works fine, there were no errors. When I imported the .ipynb to a python file, there was this error. I have tried to uninstall and reinstall the package several times and have already double-checked to see that it is in my venv.

I would really appreciate all the support. Thank you so much

Body:
So I keep having this error ModuleNotFoundError: No module named 'similarity.normalized_levenshtein' in my error log for some reasons.

This is what I was trying to do:

from similarity.normalized_levenshtein import NormalizedLevenshtein
normalized_levenshtein = NormalizedLevenshtein()

This is what was shown:

Traceback (most recent call last):
  File "API.py", line 10, in <module>
    import nlp3_model
  File "C:\Users\Admin\ai-challenge\nlp-3-api\fastml\lib\site-packages\import_ipynb.py", line 61, in load_module
    exec(code, mod.__dict__)
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'similarity.normalized_levenshtein'
(fastml)

I have already installed similarity, python-levenshtein, and Levenshtein according to what was in pip list.

Also it's weird because when I tried to run my .ipynb notebook with this line, it works fine, there were no errors. When I imported the .ipynb to a python file, there was this error. I have tried to uninstall and reinstall the package several times and have already double-checked to see that it is in my venv.

I would really appreciate all the support. Thank you so much


问:
How do I make my object property value dynamic?
I have an array of all objects stored in a state variable.
I also have another state variable that grabs a user input value from a drop down menu.

The all objects state is filtered and creates a new array with just the filtered values.

My issue is that I don't know how to make the object property dynamic so I can return the value.

 const SnowboardArray = [
     {
       id: 1,
       name: "Thunder Bolt",
       availability: "in stock",
       shape: "directional",
       Level: "Expert",
       size: "156",
       price: "500",
       sprite: thunderBolt,
     },
     {
       id: 2,
       name: "Surfer",
       availability: "in stock",
       shape: "directional",
       Level: "Expert",
       size: "154",
       price: "800",
       sprite: surfer,
     }
     ]

 // Function to filter the main array with the selected filter value stored in the state
 function getFilteredList() {
  if (!filteredObjects) {
    return allObjects;
  }

  // object grabs the object in the array / size refers to the property (this needs to be dynamic) / filteredObjects is the user input which refers to the proeprty value.

    return allObjects.filter((object) => object.size === filteredObjects

    )
 }```


问:
Multidimensional integration using python
Problem: Write a code that asks the user to input a functon with multiple variables and then integrates it using as limits numbers given by the user

This is the code that I have written so far

```<code>from sympy import Symbol, integrate, parse_expr
import time
import math

class Control():
    def __init__(self):
        self.run()

    def one_variable(self):
        func = input("Enter a mathematical function with one variable(x): ")

        x_lower,x_upper = input("Enter the lower and upper limit for the x variable: ").split(',')

        x = Symbol('x')
        parsed_func = parse_expr(func)

        start = time.time()
        result = integrate(parsed_func, (x, x_lower, x_upper))
        end = time.time()
        t = end - start
        print(result)
        print('It took', t, 'seconds to calculate the integral')

    def two_variables(self):
        func = input("Enter a mathematical function with two variables(x,y): ")

        x_lower,x_upper = input("Enter the lower and upper limit for the x variable: ").split(',')
        y_lower,y_upper = input("Enter the lower and upper limit for the y variable: ").split(',')

        x = Symbol('x')
        y = Symbol('y')
        parsed_func = parse_expr(func)

        start = time.time()
        result = integrate(parsed_func, (x, x_lower, x_upper), (y, y_lower, y_upper))
        end = time.time()
        t = end - start
        print(result)
        print('It took', t, 'seconds to calculate the integral')

    def three_variables(self):
        func = input("Enter a mathematical function with three variables(x,y,z): ")

        x_lower,x_upper = input("Enter the lower and upper limit for the x variable: ").split(',')
        y_lower,y_upper = input("Enter the lower and upper limit for the y variable: ").split(',')
        z_lower,z_upper = input("Enter the lower and upper limit for the z variable: ").split(',')

        x = Symbol('x')
        y = Symbol('y')
        z = Symbol('z')
        parsed_func = parse_expr(func)

        start = time.time()
        result = integrate(parsed_func, (x, x_lower, x_upper), (y, y_lower, y_upper), (z, z_lower, z_upper))
        end = time.time()
        t = end - start
        print(result)
        print( 'It took', t, 'seconds to calculate the integral')
    def four_variables(self):
        func = input("Enter a mathematical function with four variables(x,y,z,w): ")

        x_lower,x_upper = input("Enter the lower and upper limit for the x variable: ").split(',')
        y_lower,y_upper = input("Enter the lower and upper limit for the y variable: ").split(',')
        z_lower,z_upper = input("Enter the lower and upper limit for the z variable: ").split(',')
        w_lower,w_upper = input("Enter the lower and upper limit for the w variable: ").split(',')

        x = Symbol('x')
        y = Symbol('y')
        z = Symbol('z')
        w = Symbol('w')
        parsed_func = parse_expr(func)
        start = time.time()

        result = integrate(parsed_func, (x, x_lower, x_upper), (y, y_lower, y_upper), (z, z_lower, z_upper), (w, w_lower, w_upper))
        end = time.time()
        t = end - start
        print(result)
        print('It took', t, 'seconds to calculate the integral')

    def run(self):
        while True:
            print('Choose the number of variables (1-4)')
            reply = input("... ")
            if not reply: break
            if reply == '1':
                self.one_variable()
            if reply == '2':
                self.two_variables()
            if reply == '3':
                self.three_variables()
            if reply == '4':
                self.four_variables()

if __name__ == "__main__":
    Control()
</code>```

I would like to know if there is a more efficient way to do it and also how to add a graphical user interface to the code using tkinter

Body:
Problem: Write a code that asks the user to input a functon with multiple variables and then integrates it using as limits numbers given by the user

This is the code that I have written so far

from sympy import Symbol, integrate, parse_expr
import time
import math

class Control():
    def __init__(self):
        self.run()

    def one_variable(self):
        func = input("Enter a mathematical function with one variable(x): ")

        x_lower,x_upper = input("Enter the lower and upper limit for the x variable: ").split(',')

        x = Symbol('x')
        parsed_func = parse_expr(func)

        start = time.time()
        result = integrate(parsed_func, (x, x_lower, x_upper))
        end = time.time()
        t = end - start
        print(result)
        print('It took', t, 'seconds to calculate the integral')

    def two_variables(self):
        func = input("Enter a mathematical function with two variables(x,y): ")

        x_lower,x_upper = input("Enter the lower and upper limit for the x variable: ").split(',')
        y_lower,y_upper = input("Enter the lower and upper limit for the y variable: ").split(',')

        x = Symbol('x')
        y = Symbol('y')
        parsed_func = parse_expr(func)

        start = time.time()
        result = integrate(parsed_func, (x, x_lower, x_upper), (y, y_lower, y_upper))
        end = time.time()
        t = end - start
        print(result)
        print('It took', t, 'seconds to calculate the integral')

    def three_variables(self):
        func = input("Enter a mathematical function with three variables(x,y,z): ")

        x_lower,x_upper = input("Enter the lower and upper limit for the x variable: ").split(',')
        y_lower,y_upper = input("Enter the lower and upper limit for the y variable: ").split(',')
        z_lower,z_upper = input("Enter the lower and upper limit for the z variable: ").split(',')

        x = Symbol('x')
        y = Symbol('y')
        z = Symbol('z')
        parsed_func = parse_expr(func)

        start = time.time()
        result = integrate(parsed_func, (x, x_lower, x_upper), (y, y_lower, y_upper), (z, z_lower, z_upper))
        end = time.time()
        t = end - start
        print(result)
        print( 'It took', t, 'seconds to calculate the integral')
    def four_variables(self):
        func = input("Enter a mathematical function with four variables(x,y,z,w): ")

        x_lower,x_upper = input("Enter the lower and upper limit for the x variable: ").split(',')
        y_lower,y_upper = input("Enter the lower and upper limit for the y variable: ").split(',')
        z_lower,z_upper = input("Enter the lower and upper limit for the z variable: ").split(',')
        w_lower,w_upper = input("Enter the lower and upper limit for the w variable: ").split(',')

        x = Symbol('x')
        y = Symbol('y')
        z = Symbol('z')
        w = Symbol('w')
        parsed_func = parse_expr(func)
        start = time.time()

        result = integrate(parsed_func, (x, x_lower, x_upper), (y, y_lower, y_upper), (z, z_lower, z_upper), (w, w_lower, w_upper))
        end = time.time()
        t = end - start
        print(result)
        print('It took', t, 'seconds to calculate the integral')

    def run(self):
        while True:
            print('Choose the number of variables (1-4)')
            reply = input("... ")
            if not reply: break
            if reply == '1':
                self.one_variable()
            if reply == '2':
                self.two_variables()
            if reply == '3':
                self.three_variables()
            if reply == '4':
                self.four_variables()

if __name__ == "__main__":
    Control()

I would like to know if there is a more efficient way to do it and also how to add a graphical user interface to the code using tkinter


问:
Keras classification model with pure numpy classification layer
I have a multiclass(108 classes) classification model which I want to apply transfer learning to the classification layer. I want to deploy this model in a low computing resource device (Raspberry Pi) and I thought to implement the classification layer in pure numpy instead of using Keras or TF.
Below is my original model.

```<code>from tensorflow.keras.models import Sequential, Model, LSTM, Embedding
model = Sequential()
model.add(Embedding(108, 50, input_length=10))
model.add((LSTM(32, return_sequences=False)))
model.add(Dense(108, activation="softmax"))

model.compile(loss="categorical_crossentropy", optimizer=Adam(lr=0.001), metrics=['accuracy'])
model.summary()
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3)
history = model.fit(X_train, y_train, epochs=10, batch_size=32, validation_split=0.5, callbacks=[es]).history
</code>```

I split this model into two parts, encoder and decoder as follows. decoder is the classification layer which I want to convert into NumPy model and then do the on-device transfer learning later.

```<code>encoder = Sequential([
    Embedding(108, 50, input_length=10),
    GRU(32, return_sequences=False)
])

decoder = Sequential([
    Dense(108, activation="softmax")
])

model = Model(inputs=encoder.input, outputs=decoder(encoder.output))

model.compile(loss="categorical_crossentropy", optimizer=Adam(lr=0.001), metrics=['accuracy'])
model.summary()
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3)
history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.5, callbacks=[es]).history
</code>```

I have a few questions related to this approach.

Only way i know to train this model is, first to train the encoder and decoder. then
train NumPy classification layer using trained encoder outputs.
Is there any way i can train the NumPy model at the same time when i train the encoder (without using the above Keras decoder part and Model)? I can't use Model as I can't use Keras or TF in raspberry Pi during the transfer learning.

If there is no any way to train encoder and Numpy model at the same time,
How to use learned decoder weights as the starting weights of the Numpy Model instead of starting from random weights?

What is the most efficient code (or way) to implement the Numpy classification layer (decoder)? It requires a highly efficient model as i do the transfer learning on Raspberry Pi for incoming streaming data.
Once i trained the model for reasonable data, i plan to convert the encoder into TFLite and do the inference

Highly appreciate any help or guidance to achieve this as I'm new to NumPy-based NN implementations.
Thanks in advance

Body:
I have a multiclass(108 classes) classification model which I want to apply transfer learning to the classification layer. I want to deploy this model in a low computing resource device (Raspberry Pi) and I thought to implement the classification layer in pure numpy instead of using Keras or TF.
Below is my original model.

from tensorflow.keras.models import Sequential, Model, LSTM, Embedding
model = Sequential()
model.add(Embedding(108, 50, input_length=10))
model.add((LSTM(32, return_sequences=False)))
model.add(Dense(108, activation="softmax"))

model.compile(loss="categorical_crossentropy", optimizer=Adam(lr=0.001), metrics=['accuracy'])
model.summary()
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3)
history = model.fit(X_train, y_train, epochs=10, batch_size=32, validation_split=0.5, callbacks=[es]).history

I split this model into two parts, encoder and decoder as follows. decoder is the classification layer which I want to convert into NumPy model and then do the on-device transfer learning later.

encoder = Sequential([
    Embedding(108, 50, input_length=10),
    GRU(32, return_sequences=False)
])

decoder = Sequential([
    Dense(108, activation="softmax")
])

model = Model(inputs=encoder.input, outputs=decoder(encoder.output))

model.compile(loss="categorical_crossentropy", optimizer=Adam(lr=0.001), metrics=['accuracy'])
model.summary()
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3)
history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.5, callbacks=[es]).history

I have a few questions related to this approach.

Only way i know to train this model is, first to train the encoder and decoder. then
train NumPy classification layer using trained encoder outputs.
Is there any way i can train the NumPy model at the same time when i train the encoder (without using the above Keras decoder part and Model)? I can't use Model as I can't use Keras or TF in raspberry Pi during the transfer learning.

If there is no any way to train encoder and Numpy model at the same time,
How to use learned decoder weights as the starting weights of the Numpy Model instead of starting from random weights?

What is the most efficient code (or way) to implement the Numpy classification layer (decoder)? It requires a highly efficient model as i do the transfer learning on Raspberry Pi for incoming streaming data.
Once i trained the model for reasonable data, i plan to convert the encoder into TFLite and do the inference

Highly appreciate any help or guidance to achieve this as I'm new to NumPy-based NN implementations.
Thanks in advance


问:
How we can store jenkins build id in firebase using jenkins deploy pipeline?
I want to connect Jenkins with Firebase and want to store current build id in Firebase.

I didn't found any plugin in jenkins to connect with firebase and have little bit knowledge of jenkins so unable find working solution which helps me.


问:
Getting current X, Y coordinate from a bezier curve moving object
I want to find the x, y coordinate of an object moving in a bezier curve after it moved for a certain amount of time.

I have included a simple graph of the object trajectory here.

Consider the following known attributes of the object:

```<code>startingXY = [900, 450]
destinationXY = [-300, -600]
innerXY = [100, -50]
move_time = 15 # Moving duration in seconds
</code>```

I tried using the below formula to calculate the (x,y), but it does not appear to be correct.

```<code>   def calculate(a, b, c, d, t):
        return math.pow(1 - t, 3) * a + 3 * t * math.pow(1 - t, 2) * b + 3 * math.pow(t, 2) * (1 - t) * c + math.pow(t, 3) * d

   t = (now - start_time) * 0.1
   x = calculate(0, startx, innerx, destinationx, t)
   y = calculate(0, starty, innery, destinationy, t)
</code>```

I somewhat solved my problem with the following fomula:

```<code>    def the_math(a, b, c, t, p, f):
        return (math.pow((1 - t), 2) * a + 2 * math.pow((1 - t), t) * b + math.pow(t, 2) * c) + p * f

    elapsed_time = round(now - start)
    t = elapsed_time / self.config.move_time[fish.fish_type]
    x = the_math(path[0][0], path[1][0], path[2][0], t, 667, 0.85)
    y = the_math(path[0][1], path[1][1], path[2][1], t, 375, 0.8)
    print(x,y)
</code>```

What would be a better formula to calculate the (x,y) coordinates?

Body:
I want to find the x, y coordinate of an object moving in a bezier curve after it moved for a certain amount of time.

I have included a simple graph of the object trajectory here.

Consider the following known attributes of the object:

startingXY = [900, 450]
destinationXY = [-300, -600]
innerXY = [100, -50]
move_time = 15 # Moving duration in seconds

I tried using the below formula to calculate the (x,y), but it does not appear to be correct.

   def calculate(a, b, c, d, t):
        return math.pow(1 - t, 3) * a + 3 * t * math.pow(1 - t, 2) * b + 3 * math.pow(t, 2) * (1 - t) * c + math.pow(t, 3) * d

   t = (now - start_time) * 0.1
   x = calculate(0, startx, innerx, destinationx, t)
   y = calculate(0, starty, innery, destinationy, t)

I somewhat solved my problem with the following fomula:

    def the_math(a, b, c, t, p, f):
        return (math.pow((1 - t), 2) * a + 2 * math.pow((1 - t), t) * b + math.pow(t, 2) * c) + p * f

    elapsed_time = round(now - start)
    t = elapsed_time / self.config.move_time[fish.fish_type]
    x = the_math(path[0][0], path[1][0], path[2][0], t, 667, 0.85)
    y = the_math(path[0][1], path[1][1], path[2][1], t, 375, 0.8)
    print(x,y)

What would be a better formula to calculate the (x,y) coordinates?


问:
Jquery Ajax call to PHP don't give me any data back with dataType JSON
I'm working everyday with ajax and php at work, so it's nothing new. But now i tried a little project at home and i can't get it to work. I really don't know what i have done wrong. I just select a value from a dropdown and press a Button. The button has a onclick to a function calles "showTable". It selects the value of the dropdown and send it via ajax call to my index.php where i do a simple select to my database and wanna return the results, so i can build a table with it. But my ajax call always go to the error case, even if the result of the select is correct.

If i console.log my error, it just says "parseerror" but the network part always says 200 ok

So, this is my function within my index.html...

```<code><script>

    function showTable() {

        var coin = $('#selectCoin').val();

        $.ajax({
            type: 'POST',
            url: 'index.php',
            dataType: "json",
            data: {
                act: 'showTable',
                'coin' : coin
            },
            success: function(data) {

                alert("ok")

            },
            error: function(request, error) {
                alert("error")
            }
        });
    }
</script>
</code>```

And this is my php part

```<code>if($_POST) {
    switch ($_POST["act"]) {

        case 'showTable':

            $token = $_POST["coin"];
            $token_buy = $token.'_buy';
            $token_sell = $token.'_sell';

            $sql = "SELECT * FROM $token_buy";
            $stmt = $PDO->prepare($sql);
            $stmt->execute(array());
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode($result);

            break;
    }
}
</code>```

I tried to update the composer and added the

```<code>"ext-json": "*"
</code>```

Also i tried to remove the dataType Attribute from my ajax call. After that it don't get into the error case, but also i don't get my data from backend.

If i let me show the error with following function

```<code>error: function(jqXhr, status, error) {
   alert(status + ':' + error + ':' + jqXhr.responseText)
}
</code>```

It says:

parseerror: SyntaxError: unexpected token "<", "<!DOCTYPE"...is not valid JSON:  and continue with the whole html part in the error message

Body:
I'm working everyday with ajax and php at work, so it's nothing new. But now i tried a little project at home and i can't get it to work. I really don't know what i have done wrong. I just select a value from a dropdown and press a Button. The button has a onclick to a function calles "showTable". It selects the value of the dropdown and send it via ajax call to my index.php where i do a simple select to my database and wanna return the results, so i can build a table with it. But my ajax call always go to the error case, even if the result of the select is correct.

If i console.log my error, it just says "parseerror" but the network part always says 200 ok

So, this is my function within my index.html...

And this is my php part

if($_POST) {
    switch ($_POST["act"]) {

        case 'showTable':

            $token = $_POST["coin"];
            $token_buy = $token.'_buy';
            $token_sell = $token.'_sell';

            $sql = "SELECT * FROM $token_buy";
            $stmt = $PDO->prepare($sql);
            $stmt->execute(array());
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode($result);

            break;
    }
}

I tried to update the composer and added the

"ext-json": "*"

Also i tried to remove the dataType Attribute from my ajax call. After that it don't get into the error case, but also i don't get my data from backend.

If i let me show the error with following function

error: function(jqXhr, status, error) {
   alert(status + ':' + error + ':' + jqXhr.responseText)
}

It says:

parseerror: SyntaxError: unexpected token "<", "<!DOCTYPE"...is not valid JSON:  and continue with the whole html part in the error message


问:
Runtime error in cucumber playwright using javascript
While trying to run the cucumber playwright script in visual studio code getting below error
Error:

```<code>You're calling functions(e.g "Given") on an instance of cucumber that isn't running.
</code>```

This means you have an invalid installation

```<code>Command: npx cucumber -js
</code>```

I tried to find if duplicate dependency of cucumber exists that is not working

Installed cucumber multiple times and checked that is also not working
Expectation: able to run the script successfully

Body:
While trying to run the cucumber playwright script in visual studio code getting below error
Error:

You're calling functions(e.g "Given") on an instance of cucumber that isn't running.

This means you have an invalid installation

Command: npx cucumber -js

I tried to find if duplicate dependency of cucumber exists that is not working

Installed cucumber multiple times and checked that is also not working
Expectation: able to run the script successfully


问:
Populating a listbox in a seperate window gives me a InvalidOperationException. I'm using WPF and .NET 6.0
As I was trying to learn how to use multiple windows in WPF, I stumbled upon a problem. I have a MainWindow containing all the logic for a blackjack game. Now I wanted a second Window with the last 10 games played by the user.
These last 10 games were stored in

```<code>public static ListBoxItem[] historiekArray = new ListBoxItem[10];
</code>```

In the 'Speler' class (Player in Dutch). Now when I try to populate the HistoryWindow Listbox, everything goes well the first time, but the second time I open up the window this error occurs:

```<code>System.InvalidOperationException: 'Element already has a logical parent. It must be detached from the old parent before it is attached to a new one.'
</code>```

This is the C# code in the HistoryWindow.xaml.cs

```<code>public HistoriekWindow()
{
    InitializeComponent();

    // empty the listbox
    LbxHistoriek.Items.Clear();

    // Populate listbox with array items
    for (int i = 0; i < Speler.historiekArray.Length - 1; i++)
    {
        ListBoxItem temp = new ListBoxItem();
        temp = Speler.historiekArray[i];
        LbxHistoriek.Items.Add(temp);
    }
}
</code>```

Looking at other posts on StackOverflow and learn.microsoft, I thought the problem might be that my ListBoxItem was being reused, but after placing ListboxItem temp = new ListboxItem() inside the for-loop, nothing much changed.

SOLUTION

The array of ListboxItems was changed into an Array of strings.

```<code>public static string[] historiekArray = new string[10];
</code>```

And the for-loop sets the .Content of the ListBoxItem to the corresponding Array item.

```<code>for (int i = 0; i < Speler.historiekArray.Length - 1; i++)
            {
                ListBoxItem temp = new ListBoxItem();
                temp.Content = Speler.historiekArray[i];
                LbxHistoriek.Items.Add(temp);
            }
</code>```

Please excuse my formatting, this is my first post on StackOverflow and English is not my native language.

Body:
As I was trying to learn how to use multiple windows in WPF, I stumbled upon a problem. I have a MainWindow containing all the logic for a blackjack game. Now I wanted a second Window with the last 10 games played by the user.
These last 10 games were stored in

public static ListBoxItem[] historiekArray = new ListBoxItem[10];

In the 'Speler' class (Player in Dutch). Now when I try to populate the HistoryWindow Listbox, everything goes well the first time, but the second time I open up the window this error occurs:

System.InvalidOperationException: 'Element already has a logical parent. It must be detached from the old parent before it is attached to a new one.'

This is the C# code in the HistoryWindow.xaml.cs

public HistoriekWindow()
{
    InitializeComponent();

    // empty the listbox
    LbxHistoriek.Items.Clear();

    // Populate listbox with array items
    for (int i = 0; i < Speler.historiekArray.Length - 1; i++)
    {
        ListBoxItem temp = new ListBoxItem();
        temp = Speler.historiekArray[i];
        LbxHistoriek.Items.Add(temp);
    }
}

Looking at other posts on StackOverflow and learn.microsoft, I thought the problem might be that my ListBoxItem was being reused, but after placing ListboxItem temp = new ListboxItem() inside the for-loop, nothing much changed.

SOLUTION

The array of ListboxItems was changed into an Array of strings.

public static string[] historiekArray = new string[10];

And the for-loop sets the .Content of the ListBoxItem to the corresponding Array item.

for (int i = 0; i < Speler.historiekArray.Length - 1; i++)
            {
                ListBoxItem temp = new ListBoxItem();
                temp.Content = Speler.historiekArray[i];
                LbxHistoriek.Items.Add(temp);
            }

Please excuse my formatting, this is my first post on StackOverflow and English is not my native language.


问:
Better logging with JdbcDatabaseTester
I'm using JdbcDatabaseTester to load some XML files during testing.

Something like:

```<code>    JdbcDatabaseTester databaseTester = new
    JdbcDatabaseTester(DB_DRIVER_CLASS, CONNECTION_URL);
    try (FileInputStream fis = new FileInputStream(name)) {
        XmlDataSet dataSet = new XmlDataSet(fis);
        databaseTester.setSchema(CONNECTION_SCHEMA);
        databaseTester.setDataSet(dataSet);
        databaseTester.onSetup();
    } catch (Exception e) {
        System.out.println("Could not do it " + e.getMessage());
        throw e;
    }
</code>```

Whenever there is a failure, I will see the SQL error, something like:

```<code>MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`my_table`, CONSTRAINT `my_constraint` FOREIGN KEY (`my_key`) REFERENCES `foreign_table` (`foreign_primary_key`)

</code>```

Which is okish, but not ideal.

Is there a way for JDBCUnit to give me exactly the xml element that has failed?

Title: Better logging with JdbcDatabaseTester

Body:
I'm using JdbcDatabaseTester to load some XML files during testing.

Something like:

    JdbcDatabaseTester databaseTester = new
    JdbcDatabaseTester(DB_DRIVER_CLASS, CONNECTION_URL);
    try (FileInputStream fis = new FileInputStream(name)) {
        XmlDataSet dataSet = new XmlDataSet(fis);
        databaseTester.setSchema(CONNECTION_SCHEMA);
        databaseTester.setDataSet(dataSet);
        databaseTester.onSetup();
    } catch (Exception e) {
        System.out.println("Could not do it " + e.getMessage());
        throw e;
    }

Whenever there is a failure, I will see the SQL error, something like:

MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`my_table`, CONSTRAINT `my_constraint` FOREIGN KEY (`my_key`) REFERENCES `foreign_table` (`foreign_primary_key`)

Which is okish, but not ideal.

Is there a way for JDBCUnit to give me exactly the xml element that has failed?


问:
s3 resource download is a directory error
Trying to retrieve a CSV file from s3 using boto3 resource but getting this error:

```<code>---------------------------------------------------------------------------
IsADirectoryError                         Traceback (most recent call last)
Cell In[31], line 1
----> 1 my_bucket.download_file('archive/x/2022-12-29-08-01-05/d.csv', '/Users/devarshi/Documents/s3_downloads/x/')

IsADirectoryError: [Errno 21] Is a directory: '/Users/devarshi/Documents/s3_downloads/x/.F1BaaDAe' -> '/Users/devarshi/Documents/s3_downloads/x/'
</code>```

Ideally, the function should download the file mentioned in the first parameter into the location mentioned in the second parameter.
how does the value .F1BaaDAe get appended to the parent path?
& How can I remove this issue?

Body:
Trying to retrieve a CSV file from s3 using boto3 resource but getting this error:

---------------------------------------------------------------------------
IsADirectoryError                         Traceback (most recent call last)
Cell In[31], line 1
----> 1 my_bucket.download_file('archive/x/2022-12-29-08-01-05/d.csv', '/Users/devarshi/Documents/s3_downloads/x/')

IsADirectoryError: [Errno 21] Is a directory: '/Users/devarshi/Documents/s3_downloads/x/.F1BaaDAe' -> '/Users/devarshi/Documents/s3_downloads/x/'

Ideally, the function should download the file mentioned in the first parameter into the location mentioned in the second parameter.
how does the value .F1BaaDAe get appended to the parent path?
& How can I remove this issue?


问:
Swift: How to avoid UnsafeMutablePointer.allocate crash?
Here's an example code on how I decompressed a lz4-decompress data object:

```<code>extension Data {
    var calculatedResult: Data? {
        var result: Data?
        let size = 15_000_000
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)

        // Write data to buffer
        let resultLength = ... // calculate the length of the result data
        result = Data(bytes: buffer, count: read)
        buffer.deallocate()
        return result
    }
}

</code>```

However I recently I'v been getting crashes:

And the logs say "Could not allocate memory":

As I understand, this is caused by insufficient RAM space when creating the buffer. Is there anyway I can check whether the RAM is adequate before calling UnsafeMutablePointer<Int8>.allocate()?

Thanks in advance guys.

Body:
Here's an example code on how I decompressed a lz4-decompress data object:

extension Data {
    var calculatedResult: Data? {
        var result: Data?
        let size = 15_000_000
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)

        // Write data to buffer
        let resultLength = ... // calculate the length of the result data
        result = Data(bytes: buffer, count: read)
        buffer.deallocate()
        return result
    }
}

However I recently I'v been getting crashes:

And the logs say "Could not allocate memory":

As I understand, this is caused by insufficient RAM space when creating the buffer. Is there anyway I can check whether the RAM is adequate before calling UnsafeMutablePointer<Int8>.allocate()?

Thanks in advance guys.


问:
AttributeError in when i am trying to make a really simple progrma
```<code>import PySimpleGUI as psg
abc=psg.Button("hi")
psg.Window("hi",layout=[[abc]]).read()
</code>```

error:
i am having this error

```<code>C:\Users\makka\Desktop\coding\Scripts\python.exe C:\Users\makka\Desktop\Coding\Coding\ideas\rough.py
Traceback (most recent call last):
  File "C:\Users\makka\Desktop\Coding\Coding\ideas\rough.py", line 1, in <module>
    import PySimpleGUI as psg
  File "C:\Users\makka\Desktop\coding\lib\site-packages\PySimpleGUI\__init__.py", line 2, in <module>
    from .PySimpleGUI import *
  File "C:\Users\makka\Desktop\coding\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 163, in <module>
    import random
  File "C:\Users\makka\Desktop\coding\random.py", line 4, in <module>
    [sg.Text("hi")],
AttributeError: partially initialized module 'PySimpleGUI' has no attribute 'Text' (most likely due to a circular import)

Process finished with exit code 1
</code>```

i was exprecting it to work smoothly

Body:
import PySimpleGUI as psg
abc=psg.Button("hi")
psg.Window("hi",layout=[[abc]]).read()

error:
i am having this error

C:\Users\makka\Desktop\coding\Scripts\python.exe C:\Users\makka\Desktop\Coding\Coding\ideas\rough.py
Traceback (most recent call last):
  File "C:\Users\makka\Desktop\Coding\Coding\ideas\rough.py", line 1, in <module>
    import PySimpleGUI as psg
  File "C:\Users\makka\Desktop\coding\lib\site-packages\PySimpleGUI\__init__.py", line 2, in <module>
    from .PySimpleGUI import *
  File "C:\Users\makka\Desktop\coding\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 163, in <module>
    import random
  File "C:\Users\makka\Desktop\coding\random.py", line 4, in <module>
    [sg.Text("hi")],
AttributeError: partially initialized module 'PySimpleGUI' has no attribute 'Text' (most likely due to a circular import)

Process finished with exit code 1

i was exprecting it to work smoothly