问:
Custom filter for KNP Pagination Filter
I am using knp pagination filter but i was trying to add a custom filter with LIKE. But nothing return. Maybe someone can help me.
Thank you so much.

```<code>``
$dql   = "SELECT e FROM App\Entity\EventLocation e";
            $query = $em->createQuery($dql);
if ($request->query->getAlnum('filterValue')) {
$dql   = "SELECT e FROM App\Entity\EventLocation e WHERE e.name LIKE :filterValue";
         $query = $em->createQuery($dql)->setParameter('filterValue', '%' . $request->query->getAlnum('filterValue') . '%');
        }
$pagination = $paginator->paginate(
$query, /* query NOT result */
            $request->query->getInt('page', 1), /*page number*/
            10 /*limit per page*/
            );
 return $this->render('event_location/index.html.twig', [
            'paginationEventLocation' => $pagination,
        ]);
``
</code>```

In the twig i have the knp filter
{{ knp_pagination_filter(paginationEventLocation, {'e.name': 'Name' }) }}

Title: Custom filter for KNP Pagination Filter

Body:
I am using knp pagination filter but i was trying to add a custom filter with LIKE. But nothing return. Maybe someone can help me.
Thank you so much.

``
$dql   = "SELECT e FROM App\Entity\EventLocation e";
            $query = $em->createQuery($dql);
if ($request->query->getAlnum('filterValue')) {
$dql   = "SELECT e FROM App\Entity\EventLocation e WHERE e.name LIKE :filterValue";
         $query = $em->createQuery($dql)->setParameter('filterValue', '%' . $request->query->getAlnum('filterValue') . '%');
        }
$pagination = $paginator->paginate(
$query, /* query NOT result */
            $request->query->getInt('page', 1), /*page number*/
            10 /*limit per page*/
            );
 return $this->render('event_location/index.html.twig', [
            'paginationEventLocation' => $pagination,
        ]);
``

In the twig i have the knp filter
{{ knp_pagination_filter(paginationEventLocation, {'e.name': 'Name' }) }}


来源: stackexchange

问:
My script doesnt work on host, but it works on localhost
I made small script, which uses PerformanceObserver in it

```<code>console.log(1);

const observer = new PerformanceObserver(list => {
    console.log(2);
    list.getEntries().forEach(entry => {
       if (entry.type === "back_forward") {
       const data = document.querySelector(".h1");
       data.textContent = "hello";
       setTimeout(function () {
           window.location.reload();
       }, 2000);
       }
    });
});

console.log(3)

observer.observe({ type: "navigation" });
</code>```

*console logs are for test
When i launched it on localhost, everything worked perfectly, but when i deployed it on host - thats it. Nothing happens especially in chrome. There is no errors. There is no clue about it.

There is the site: https://cq25005.tw1.ru/

I tried a lot of ways to fix this problem, nothing helped

ContentLicense: CC BY-SA 4.0

Body:
I made small script, which uses PerformanceObserver in it

console.log(1);

const observer = new PerformanceObserver(list => {
    console.log(2);
    list.getEntries().forEach(entry => {
       if (entry.type === "back_forward") {
       const data = document.querySelector(".h1");
       data.textContent = "hello";
       setTimeout(function () {
           window.location.reload();
       }, 2000);
       }
    });
});

console.log(3)

observer.observe({ type: "navigation" });

*console logs are for test
When i launched it on localhost, everything worked perfectly, but when i deployed it on host - thats it. Nothing happens especially in chrome. There is no errors. There is no clue about it.

There is the site: https://cq25005.tw1.ru/

I tried a lot of ways to fix this problem, nothing helped


问:
Nuxtjs fails to load some modern.js files in UK
I'm facing a very strange issue with nuxt 2.15.8 during production and specifically users who opens the site from UK. The main issue is that images are not hydrating, so after investigation the only thing I could notice in the console is this error

```<code>GET https://my-site-name.com/_nuxt/a5d3b1c.modern.js net::ERR_ABORTED 404
</code>```

There are like 4 or 5 similar errors to this one. I can't ever replicate the issue locally and It never happens unless the user is opening the site from UK. I can replicate it in production by turning on a VPN in UK and open the site in incognito mode.

Any ideas that might fix the issue? The site is deployed on GoogleCloud and cloudflare.

Body:
I'm facing a very strange issue with nuxt 2.15.8 during production and specifically users who opens the site from UK. The main issue is that images are not hydrating, so after investigation the only thing I could notice in the console is this error

GET https://my-site-name.com/_nuxt/a5d3b1c.modern.js net::ERR_ABORTED 404

There are like 4 or 5 similar errors to this one. I can't ever replicate the issue locally and It never happens unless the user is opening the site from UK. I can replicate it in production by turning on a VPN in UK and open the site in incognito mode.

Any ideas that might fix the issue? The site is deployed on GoogleCloud and cloudflare.


问:
Blazor Wasm in subfolder
I have two blazor wasm applications I would like to host withing the same root folder as follows:

MainSite

     |_ Customers

Each of those are seperate applications.
Is it possible to host the 'customers' wasm site within the same 'root' folder but treat it as completely seperate application? i.e.

http://localhost:8999/ (takes you to -> Root Site)

http://localhost:8999/Customers (takes you to -> /Customers)

I have tried to to the following without any luck:

a) modified <base href="/" /> to <base href="/customers/" /> for subfolder 'customers' application

b) added some url rewrite rules in 'customers/web.config'

```<code><rewrite>
       <rules>
            <rule name="ExampleToDemo">
                <match url="^(.*)customers" />
                <action type="Rewrite" url="^(.*)customers\wwwroot\{R:0}" />
            </rule>
            <rule name="SPA fallback routing 2" stopProcessing="true">
                <match url="^(.*)customers" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                </conditions>
                <action type="Rewrite" url="customers\wwroot\" />
            </rule>
      </rules>
    </rewrite>
</code>```

Root site works as expected:

Sub directory 'Customers' shows this:

Instead of this:

How can I make the sub dir customers site work using the /customers path?

Title: Blazor Wasm in subfolder

Body:
I have two blazor wasm applications I would like to host withing the same root folder as follows:

MainSite

     |_ Customers

Each of those are seperate applications.
Is it possible to host the 'customers' wasm site within the same 'root' folder but treat it as completely seperate application? i.e.

http://localhost:8999/ (takes you to -> Root Site)

http://localhost:8999/Customers (takes you to -> /Customers)

I have tried to to the following without any luck:

a) modified <base href="/" /> to <base href="/customers/" /> for subfolder 'customers' application

b) added some url rewrite rules in 'customers/web.config'

<rewrite>
       <rules>
            <rule name="ExampleToDemo">
                <match url="^(.*)customers" />
                <action type="Rewrite" url="^(.*)customers\wwwroot\{R:0}" />
            </rule>
            <rule name="SPA fallback routing 2" stopProcessing="true">
                <match url="^(.*)customers" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                </conditions>
                <action type="Rewrite" url="customers\wwroot\" />
            </rule>
      </rules>
    </rewrite>

Root site works as expected:

Sub directory 'Customers' shows this:

Instead of this:

How can I make the sub dir customers site work using the /customers path?


问:
String format strange behaviour when rounding to decimal places
I'm trying to round decimal number to 2 decimals and I'm using String(format:"%.2f", number) to achieve that.

Problem is that it is not consistent and sometimes it rounds number wrong.

For example it rounds 2.345 to 2.35 as it should, but it rounds 1.345 to 1.34 which is wrong, it should be 1.35.

Does anyone know why is this happening and how to fix it?


问:
Can't expect named function to have been called after mocking
I'm trying to mock a named import function (createCart), I followed this guide for hints:
https://github.com/facebook/jest/issues/7514.

However, the assert for function call is failing:

```<code>expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 1
Received number of calls: 0
</code>```

What am I missing here? The function should be correctly mocked to my understanding.

Test:

// libs
import { createCart } from 'lib'
import fetchMock from 'jest-fetch-mock'

// handler
import handler from 'pages/api/store/create-cart'

// utils
import { mockRequestResponse } from 'utils'

const cart = { createCart }

const mockSuccessfulResponse = {
  checkoutUrl: 'https://checkout.godsent.gg/cart/c/13e33289e8aebdc38b064db2ada05161',
  id: 'gid://shopify/Cart/13e33289e8aebdc38b064db2ada05161',
}

beforeEach(() => {
  fetchMock.resetMocks()
})

describe('POST api/store/create-cart API endpoint', () => {
  it('should return a successful response', async () => {
     jest.spyOn(cart, 'createCart').mockResolvedValue(mockSuccessfulResponse)

    fetchMock.mockResponseOnce(JSON.stringify(mockSuccessfulResponse))

    const { req, res } = mockRequestResponse('POST')

    await handler(req, res)

    expect(cart.createCart).toHaveBeenCalledTimes(1)
    expect(res.statusCode).toBe(200)
    expect(res._getJSONData()).toEqual(mockSuccessfulResponse)
  })
})```
</div>
</div>
</p>
<p>API handler being tested:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>const handler = async (
  request: NextApiRequest,
  response: NextApiResponse<SuccessfulResponse | ErrorResponse>
) => {
  await NextCors(request, response, corsOptions)

  const logger = getLogger('createCart')

  try {
    const data = await createCart()

    response.status(200).json(data)
  } catch (error) {
    logger.error(error)

    response.status(500).json({ message: 'There was a problem creating the cart' })
  }
}</code>```

Body:
I'm trying to mock a named import function (createCart), I followed this guide for hints:
https://github.com/facebook/jest/issues/7514.

However, the assert for function call is failing:

expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 1
Received number of calls: 0

What am I missing here? The function should be correctly mocked to my understanding.

Test:

// libs
import { createCart } from 'lib'
import fetchMock from 'jest-fetch-mock'

// handler
import handler from 'pages/api/store/create-cart'

// utils
import { mockRequestResponse } from 'utils'

const cart = { createCart }

const mockSuccessfulResponse = {
  checkoutUrl: 'https://checkout.godsent.gg/cart/c/13e33289e8aebdc38b064db2ada05161',
  id: 'gid://shopify/Cart/13e33289e8aebdc38b064db2ada05161',
}

beforeEach(() => {
  fetchMock.resetMocks()
})

describe('POST api/store/create-cart API endpoint', () => {
  it('should return a successful response', async () => {
     jest.spyOn(cart, 'createCart').mockResolvedValue(mockSuccessfulResponse)

    fetchMock.mockResponseOnce(JSON.stringify(mockSuccessfulResponse))

    const { req, res } = mockRequestResponse('POST')

    await handler(req, res)

    expect(cart.createCart).toHaveBeenCalledTimes(1)
    expect(res.statusCode).toBe(200)
    expect(res._getJSONData()).toEqual(mockSuccessfulResponse)
  })
})

API handler being tested:

const handler = async (
  request: NextApiRequest,
  response: NextApiResponse<SuccessfulResponse | ErrorResponse>
) => {
  await NextCors(request, response, corsOptions)

  const logger = getLogger('createCart')

  try {
    const data = await createCart()

    response.status(200).json(data)
  } catch (error) {
    logger.error(error)

    response.status(500).json({ message: 'There was a problem creating the cart' })
  }
}


问:
Why do I get this arbitrary syntax error?
I'm learning GLSL, and I thought it might be a fun project to build a simple raytracer. I can't figure out why I get a weird syntax error on this function:

```<code>vec3 rayAt(in ray r, in float t)
{
    return r.o + t*r.d;
}
</code>```

For context, r.o and r.d are components of this struct:

```<code>struct ray
{
    vec3 o;
    vec3 d;
}
</code>```

Edit: I'm writing this on shadertoy, and the specific error I get is 'vec3' : syntax error

Body:
I'm learning GLSL, and I thought it might be a fun project to build a simple raytracer. I can't figure out why I get a weird syntax error on this function:

vec3 rayAt(in ray r, in float t)
{
    return r.o + t*r.d;
}

For context, r.o and r.d are components of this struct:

struct ray
{
    vec3 o;
    vec3 d;
}

Edit: I'm writing this on shadertoy, and the specific error I get is 'vec3' : syntax error


问:
Get To and From email address from email information and add dynamically to external page link
Can we get entered user's to and cc email and also from email data and any way to attach to URL through GET parameters to send it to external page?


问:
MongoDB Query Collection
I would like to querymy mongodb collection just like this SQl Query:

SELECT m1.stage_id, m2.stage_id
FROM Memories m1, Memories m2
WHERE m1.experience_id = m2.experience_id
AND m1.stage_id < m2.stage_id;
```

I want to have pairs of stage_id's at the end so I can input them in a CSV-File
example of an document

Title: MongoDB Query Collection

Body:
I would like to querymy mongodb collection just like this SQl Query:

SELECT m1.stage_id, m2.stage_id
FROM Memories m1, Memories m2
WHERE m1.experience_id = m2.experience_id
AND m1.stage_id < m2.stage_id;

I want to have pairs of stage_id's at the end so I can input them in a CSV-File
example of an document


问:
Do we always have to run Bellman-Ford N-1 times?
This is more a theoretical question because I can see this question being asked in an exam.
Assuming we have a directed graph G(V,E) with |V| = 10 and we want to know the shortest path from S to all other 9 vertices. Assuming we know that the longest path from S has length 5 do we still have to run Bellman-Ford 9 times or can we run it 5 times and conclude that we have found the shortest path ?

When trying it on an example it worked but it could also just be luck and there might me some edgecase I am missing.


问:
Saxon HE Gradle: Error occurred during initialization of boot layer java.lang.module.FindException: Module Saxon.HE not found

Solution: Thanks to jewelsea's comment here I switched the project to Maven and won't be using Gradle anymore.

I try to include Saxon-HE within a modular Gradle project, based on the autogenerated JavaFX project within intellij. The error message I get when running in Intellij is:

```<code>Error occurred during initialization of boot layer
java.lang.module.FindException: Module Saxon.HE not found, required by org.proj.xslgui
</code>```

Dependencies in build.gradle:

```<code>plugins {
    id 'java'
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.13'
    id 'org.beryx.jlink' version '2.25.0'
}

group 'org.proj'
version '1.0'

repositories {
    mavenCentral()
}

ext {
    junitVersion = '5.9.1'
}

sourceCompatibility = '17'
targetCompatibility = '17'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

application {
    mainModule = 'org.proj.xslgui'
    mainClass = 'org.proj.xslgui.HelloApplication'
}

javafx {
    version = '17.0.2'
    modules = ['javafx.controls', 'javafx.fxml']
}

dependencies {
    implementation("net.sf.saxon:Saxon-HE:11.4")
    testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
}

test {
    useJUnitPlatform()
}

jlink {
    imageZip = project.file("${buildDir}/distributions/app-${javafx.platform.classifier}.zip")
    options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages']
    launcher {
        name = 'app'
    }
}

jlinkZip {
    group = 'distribution'
}
</code>```

The main part of the build.gradle is autogenerated by intellij.

My settings.gradle:

```<code>rootProject.name = "XSLGui"
</code>```

My module-info.java:

```<code>module org.proj.xslgui {
    requires javafx.controls;
    requires javafx.fxml;
    requires java.xml;
    requires Saxon.HE;

    opens org.proj.xslgui to javafx.fxml;
    exports org.proj.xslgui;
}
</code>```

The Saxon.jar shows up in the external libraries. And within the classes everything gets resolved just fine. I have no idea why it can't find the modul, ... intellij itself autogenerated the require Saxon.HE in the module-info.java... I think Saxon just isn't a module at all (can't find a module-info.java), so maybe that's where the problem starts...

I expected that adding the dependency in the build.gradle and adding the require in the module-info.java would suffice for the library to be available in order to run the program. I read the Gradle documentation and googled/stackoverflowed, I didn't find a solution for this problem though.

Body:
Solution: Thanks to jewelsea's comment here I switched the project to Maven and won't be using Gradle anymore.

I try to include Saxon-HE within a modular Gradle project, based on the autogenerated JavaFX project within intellij. The error message I get when running in Intellij is:

Error occurred during initialization of boot layer
java.lang.module.FindException: Module Saxon.HE not found, required by org.proj.xslgui

Dependencies in build.gradle:

plugins {
    id 'java'
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.13'
    id 'org.beryx.jlink' version '2.25.0'
}

group 'org.proj'
version '1.0'

repositories {
    mavenCentral()
}

ext {
    junitVersion = '5.9.1'
}

sourceCompatibility = '17'
targetCompatibility = '17'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

application {
    mainModule = 'org.proj.xslgui'
    mainClass = 'org.proj.xslgui.HelloApplication'
}

javafx {
    version = '17.0.2'
    modules = ['javafx.controls', 'javafx.fxml']
}

dependencies {
    implementation("net.sf.saxon:Saxon-HE:11.4")
    testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
}

test {
    useJUnitPlatform()
}

jlink {
    imageZip = project.file("${buildDir}/distributions/app-${javafx.platform.classifier}.zip")
    options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages']
    launcher {
        name = 'app'
    }
}

jlinkZip {
    group = 'distribution'
}

The main part of the build.gradle is autogenerated by intellij.

My settings.gradle:

rootProject.name = "XSLGui"

My module-info.java:

module org.proj.xslgui {
    requires javafx.controls;
    requires javafx.fxml;
    requires java.xml;
    requires Saxon.HE;

    opens org.proj.xslgui to javafx.fxml;
    exports org.proj.xslgui;
}

The Saxon.jar shows up in the external libraries. And within the classes everything gets resolved just fine. I have no idea why it can't find the modul, ... intellij itself autogenerated the require Saxon.HE in the module-info.java... I think Saxon just isn't a module at all (can't find a module-info.java), so maybe that's where the problem starts...

I expected that adding the dependency in the build.gradle and adding the require in the module-info.java would suffice for the library to be available in order to run the program. I read the Gradle documentation and googled/stackoverflowed, I didn't find a solution for this problem though.


问:
expo won't start my development server, because it thinks the my simulator device is on different network?
I have always been successful running "npm start" and then running my ios simulator expo app, but for some reason it doesn't open any more and just crashes.

Here is the error message:

```<code>It looks like you may be using a LAN URL. Make sure your device is on the same network as the server, and that you have granted Expo Go the Local Network permission in the Settings app, or try using the tunnel connection type.
</code>```

I am running ios simulator on the same device, so of course its on the same network, why am I getting this error, what can I do?

Please I need help as this has never happened before, i am using macos.

Body:
I have always been successful running "npm start" and then running my ios simulator expo app, but for some reason it doesn't open any more and just crashes.

Here is the error message:

It looks like you may be using a LAN URL. Make sure your device is on the same network as the server, and that you have granted Expo Go the Local Network permission in the Settings app, or try using the tunnel connection type.

I am running ios simulator on the same device, so of course its on the same network, why am I getting this error, what can I do?

Please I need help as this has never happened before, i am using macos.


问:
Failed to compile htmlparser2 reactjs
Failed to compile on npm start, Reactjs

/node_modules/htmlparser2/lib/esm/index.js 62:9
Module parse failed: Unexpected token (62:9)
File was processed with these loaders:

./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|   return getFeed(parseDOM(feed, options));
| }

export * as DomUtils from "domutils";
| // Old name for DomHandler
| export { DomHandler as DefaultHandler };

Title: Failed to compile htmlparser2 reactjs


问:
Lottie files - SVG gaussian blur does not work on Safari
Just wondering if anyone has a way of working around this - finally managed to get the SVG animation working and not slowing down all the JS on the page but turns out it doesn't work on Safari.......

On chrome using the renderer of SVG it works fine - but on Safari it does not.

CHROME:

Safari:

The issue I can see is that on Safari you need to use the Canvas renderer, but this does not support Guassin blur from after effects:

Are there any work arounds for this? as this is a blocker at the moment.

Thanks -


问:
How do I reliably handle right-to-left text between AWS s3 and node.js?
I have a text file located on AWS s3 which is written in Arabic. I've been told that the text is set to be displayed right-to-left. When I download that file at the terminal and open it in Emacs, the text is indeed displayed right-to-left and the first line looks like this:

But when I use Node.js to download that file from s3 and try to view the first line, it's not the same:

My code is below. I would have assumed that the toString() method is the culprit but having played around with toLocaleString() and various language arguments I couldn't make them consistent. I see that s3 has ContentLanguage and ContentEncoding fields which are both undefined for this object. What am I doing wrong?

      const ob = await s3.getObject({
        Bucket, Key
      }).promise(),
      text = ob.Body.toString('utf-8'),
      data = text.split('\n').filter(e => e.match(/\S/));

      console.info(JSON.stringify(data.slice(0, 2), null, 5));
```
<p>As a workaround, I do this:</p>
<pre class="lang-js prettyprint-override"><code>      data = text.split('\n').filter(e => e.match(/\S/))
        .map(line => [`ar`, `he`].includes(lng) ?
          line.split("").reverse().join("") : // <-- arabic & hebrew right-to-left rtl
          line)
</code>```

But I'm not clear if that's best.

Body:
I have a text file located on AWS s3 which is written in Arabic. I've been told that the text is set to be displayed right-to-left. When I download that file at the terminal and open it in Emacs, the text is indeed displayed right-to-left and the first line looks like this:

But when I use Node.js to download that file from s3 and try to view the first line, it's not the same:

My code is below. I would have assumed that the toString() method is the culprit but having played around with toLocaleString() and various language arguments I couldn't make them consistent. I see that s3 has ContentLanguage and ContentEncoding fields which are both undefined for this object. What am I doing wrong?

      const ob = await s3.getObject({
        Bucket, Key
      }).promise(),
      text = ob.Body.toString('utf-8'),
      data = text.split('\n').filter(e => e.match(/\S/));

      console.info(JSON.stringify(data.slice(0, 2), null, 5));

As a workaround, I do this:

      data = text.split('\n').filter(e => e.match(/\S/))
        .map(line => [`ar`, `he`].includes(lng) ?
          line.split("").reverse().join("") : // <-- arabic & hebrew right-to-left rtl
          line)

But I'm not clear if that's best.


问:
How to omit setter of PropertyChanged when the framework draws controls [MAUI.NET]
I have an application in MAUI.NET with MVVM architecture.
In ViewModels I am setting PropertyChanged as most of examples through the web.

In my application the user opens lots of views (that are of type ContentView).
Each time the ContentView is assigned to main area of application and drawn on the monitor, the setters of ViewModels are fired (when they have already binded value).

What I need is to limit this behaviour (firing setters in ViewModels) only to the moment when the user himself/herself click on the checkbox, omitting the moments when the framework just draw the checkbox which have binded value set to true.

In this situation call stack says that external code is firing this.

Anyone have any idea how to deal with this?

edit:

viewmodel:

```<code>internal class CheckboxViewModel : BaseViewModel
{
    public bool Value
    {
        get
        {
            ...
        }
        set
        {
            //here I compute value and set status to be changed

            //this is fired when the user click on checkbox = ok
            //but also when checkbox (with binded true value) is drawn on the monitor = problem
        }
    }

    public CheckboxViewModel(XElement item, Registry registry) : base(item, registry)
    {
            ...
    }
}
</code>```

view:

```<code><DataTemplate x:DataType="viewModels:CheckboxViewModel" x:Key="CheckboxDataTemplate">
    <CheckBox IsChecked="{Binding Value}" ... />
</DataTemplate>
</code>```

and my sligthly changed version of INotifyProperty:

```<code>    public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new(propertyName));
    }

    protected virtual void SetPropertyAndNotify<T>(ref T backedProperty, T newValue, [CallerMemberName] string propertyName = null)
    {
        if (object.Equals(backedProperty, newValue))
            return;

        backedProperty = newValue;

        PropertyChanged?.Invoke(this, new(propertyName));
    }
}
</code>```

situation:

I put a ContentView that in BindedContext has (in some hierarchy) the CheckBoxViewModel and it is drawn. But the setter is fired.

Body:
I have an application in MAUI.NET with MVVM architecture.
In ViewModels I am setting PropertyChanged as most of examples through the web.

In my application the user opens lots of views (that are of type ContentView).
Each time the ContentView is assigned to main area of application and drawn on the monitor, the setters of ViewModels are fired (when they have already binded value).

What I need is to limit this behaviour (firing setters in ViewModels) only to the moment when the user himself/herself click on the checkbox, omitting the moments when the framework just draw the checkbox which have binded value set to true.

In this situation call stack says that external code is firing this.

Anyone have any idea how to deal with this?

edit:

viewmodel:

internal class CheckboxViewModel : BaseViewModel
{
    public bool Value
    {
        get
        {
            ...
        }
        set
        {
            //here I compute value and set status to be changed

            //this is fired when the user click on checkbox = ok
            //but also when checkbox (with binded true value) is drawn on the monitor = problem
        }
    }

    public CheckboxViewModel(XElement item, Registry registry) : base(item, registry)
    {
            ...
    }
}

view:

<DataTemplate x:DataType="viewModels:CheckboxViewModel" x:Key="CheckboxDataTemplate">
    <CheckBox IsChecked="{Binding Value}" ... />
</DataTemplate>

and my sligthly changed version of INotifyProperty:

    public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new(propertyName));
    }

    protected virtual void SetPropertyAndNotify<T>(ref T backedProperty, T newValue, [CallerMemberName] string propertyName = null)
    {
        if (object.Equals(backedProperty, newValue))
            return;

        backedProperty = newValue;

        PropertyChanged?.Invoke(this, new(propertyName));
    }
}

situation:

I put a ContentView that in BindedContext has (in some hierarchy) the CheckBoxViewModel and it is drawn. But the setter is fired.


问:
Syntax Errors showing up in a file in the 'ag-charts-community' library that I haven't edited
Working on a project using the 'ag-charts-community' and 'ag-charts-angular' libraries, and upon compiling what I've written, I get these errors:

```<code>ERROR in node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,52): error TS1005: ',' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,77): error TS1005: ',' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,80): error TS1005: '=>' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,91): error TS1109: Expression expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,109): error TS1109: Expression expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,117): error TS1005: ';' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,118): error TS1128: Declaration or statement expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,132): error TS1011: An element access expression should take an argument.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,134): error TS1011: An element access expression should take an argument.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(26,58): error TS1005: ',' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(26,73): error TS1005: ',' expected.
</code>```

Here's the file in question, errors take place in last two export declare function statements:

```<code>import { SizedPoint, Point } from '../scene/point';
export interface MeasuredLabel {
    readonly text: string;
    readonly width: number;
    readonly height: number;
}
export interface PlacedLabel<PLD = PointLabelDatum> extends MeasuredLabel, Readonly<Point> {
    readonly index: number;
    readonly datum: PLD;
}
export interface PointLabelDatum {
    readonly point: Readonly<SizedPoint>;
    readonly label: MeasuredLabel;
}
interface Bounds extends Readonly<Point> {
    readonly width: number;
    readonly height: number;
}
export declare function isPointLabelDatum(x: any): x is PointLabelDatum;
/**
 * @param data Points and labels for one or more series. The order of series determines label placement precedence.
 * @param bounds Bounds to fit the labels into. If a label can't be fully contained, it doesn't fit.
 * @returns Placed labels for the given series (in the given order).
 */
export declare function placeLabels(data: readonly (readonly PointLabelDatum[])[], bounds?: Bounds, padding?: number): PlacedLabel[][];
export declare function axisLabelsOverlap(data: readonly PointLabelDatum[], padding?: number): boolean;
export {};

</code>```

Here are the dependencies listed in my package.json file:

```<code>"dependencies": {
    "@angular/animations": "^7.2.15",
    "@angular/cdk": "^7.3.7",
    "@angular/cli": "^7.3.10",
    "@angular/common": "^7.0.3",
    "@angular/compiler": "^7.0.3",
    "@angular/core": "^7.2.16",
    "@angular/forms": "^7.0.3",
    "@angular/http": "^7.0.3",
    "@angular/material": "^7.3.7",
    "@angular/platform-browser": "^7.0.3",
    "@angular/platform-browser-dynamic": "^7.0.3",
    "@angular/router": "^7.0.3",
    "@zxing/browser": "^0.0.10",
    "@zxing/library": "^0.18.6",
    "@zxing/ngx-scanner": "3.3.0",
    "ag-grid-angular": "^20.0.0",
    "ag-grid-community": "^20.0.0",
    "angular-highcharts": "7.0.2",
    "bootstrap-icons": "^1.6.1",
    "core-js": "^2.4.1",
    "file-save": "^0.2.0",
    "font-awesome": "^4.7.0",
    "highcharts": "^6.2.0",
    "it-mlaf-sass": "^5.0.0",
    "jquery": "^3.4.1",
    "lodash": "^4.17.11",
    "moment": "^2.22.2",
    "ng2-signalr": "^8.0.2",
    "ngx-bootstrap": "^3.1.1",
    "primeicons": "^1.0.0",
    "primeng": "^7.1.0",
    "rxjs": "^6.3.3",
    "rxjs-compat": "^6.0.0-rc.0",
    "signalr": "^2.4.1",
    "uuid": "^7.0.3",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.13.8",
    "@angular/compiler-cli": "^7.0.3",
    "@angular/language-service": "^7.0.3",
    "@types/file-saver": "^2.0.1",
    "@types/highcharts": "^5.0.34",
    "@types/jasmine": "^2.8.11",
    "@types/jasminewd2": "^2.0.6",
    "@types/lodash": "^4.14.118",
    "@types/node": "~8.9.4",
    "codelyzer": "^4.0.1",
    "cypress": "^8.5.0",
    "cypress-file-upload": "^5.0.8",
    "cypress-ntlm-auth": "3.2.2",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-ie-launcher": "^1.0.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-junit-reporter": "^1.2.0",
    "karma-parallel": "^0.3.1",
    "node-sass": "^4.14.1",
    "protractor": "~5.1.2",
    "sonar-scanner": "^3.1.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1",
    "tslint-config-intc-angular": "^1.0.0",
    "tslint-sonarts": "^1.9.0",
    "typescript": "~3.1.6",
    "xlsx": "^0.16.8"
  }
</code>```

Here are the dependencies listed in ag-charts-community package.json file:

```<code>"devDependencies": {
    "@babel/types": "7.12.7",
    "@types/jest": "^25.2.1",
    "@types/jest-image-snapshot": "^4.3.1",
    "@types/node": "^16.0.0",
    "@types/pixelmatch": "^5.2.4",
    "@types/pngjs": "^6.0.1",
    "@types/ws": "8.5.3",
    "canvas": "^2.9.0",
    "eslint": "^6.8.0",
    "eslint-plugin-compat": "^3.5.1",
    "eslint-plugin-ie11": "^1.0.0",
    "glob": "8.0.3",
    "husky": "^8.0.1",
    "jest": "^25.4.0",
    "jest-canvas-mock": "2.3.1",
    "jest-image-snapshot": "^4.5.1",
    "jest-runner": "^25.4.0",
    "jest-serial-runner": "^1.2.0",
    "lint-staged": "^13.0.3",
    "pixelmatch": "^5.2.1",
    "prettier": "^2.7.1",
    "raf": "3.4.1",
    "rimraf": "3.0.2",
    "ts-jest": "^25.4.0",
    "typescript": "~3.7.7",
    "ws": "8.9.0"
  },
</code>```

I haven't touched either of those lines, let alone anything in the library.

I've tried removing the node_modules folder and reinstalling it via npm install. I have a hunch that its a versioning issue, but I am not 100% sure as I am fairly new to typescript/angular in general.

I noticed that the typescript version for my project and the typescript version for this library do not line up, as the ag-charts-community typescript version is 3.7.7, while mine is 3.1.6. Could this be what's causing the issue or is it likely something else?

Body:
Working on a project using the 'ag-charts-community' and 'ag-charts-angular' libraries, and upon compiling what I've written, I get these errors:

ERROR in node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,52): error TS1005: ',' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,77): error TS1005: ',' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,80): error TS1005: '=>' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,91): error TS1109: Expression expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,109): error TS1109: Expression expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,117): error TS1005: ';' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,118): error TS1128: Declaration or statement expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,132): error TS1011: An element access expression should take an argument.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(25,134): error TS1011: An element access expression should take an argument.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(26,58): error TS1005: ',' expected.
node_modules/ag-charts-community/dist/cjs/es5/util/labelPlacement.d.ts(26,73): error TS1005: ',' expected.

Here's the file in question, errors take place in last two export declare function statements:

import { SizedPoint, Point } from '../scene/point';
export interface MeasuredLabel {
    readonly text: string;
    readonly width: number;
    readonly height: number;
}
export interface PlacedLabel<PLD = PointLabelDatum> extends MeasuredLabel, Readonly<Point> {
    readonly index: number;
    readonly datum: PLD;
}
export interface PointLabelDatum {
    readonly point: Readonly<SizedPoint>;
    readonly label: MeasuredLabel;
}
interface Bounds extends Readonly<Point> {
    readonly width: number;
    readonly height: number;
}
export declare function isPointLabelDatum(x: any): x is PointLabelDatum;
/**
 * @param data Points and labels for one or more series. The order of series determines label placement precedence.
 * @param bounds Bounds to fit the labels into. If a label can't be fully contained, it doesn't fit.
 * @returns Placed labels for the given series (in the given order).
 */
export declare function placeLabels(data: readonly (readonly PointLabelDatum[])[], bounds?: Bounds, padding?: number): PlacedLabel[][];
export declare function axisLabelsOverlap(data: readonly PointLabelDatum[], padding?: number): boolean;
export {};

Here are the dependencies listed in my package.json file:

"dependencies": {
    "@angular/animations": "^7.2.15",
    "@angular/cdk": "^7.3.7",
    "@angular/cli": "^7.3.10",
    "@angular/common": "^7.0.3",
    "@angular/compiler": "^7.0.3",
    "@angular/core": "^7.2.16",
    "@angular/forms": "^7.0.3",
    "@angular/http": "^7.0.3",
    "@angular/material": "^7.3.7",
    "@angular/platform-browser": "^7.0.3",
    "@angular/platform-browser-dynamic": "^7.0.3",
    "@angular/router": "^7.0.3",
    "@zxing/browser": "^0.0.10",
    "@zxing/library": "^0.18.6",
    "@zxing/ngx-scanner": "3.3.0",
    "ag-grid-angular": "^20.0.0",
    "ag-grid-community": "^20.0.0",
    "angular-highcharts": "7.0.2",
    "bootstrap-icons": "^1.6.1",
    "core-js": "^2.4.1",
    "file-save": "^0.2.0",
    "font-awesome": "^4.7.0",
    "highcharts": "^6.2.0",
    "it-mlaf-sass": "^5.0.0",
    "jquery": "^3.4.1",
    "lodash": "^4.17.11",
    "moment": "^2.22.2",
    "ng2-signalr": "^8.0.2",
    "ngx-bootstrap": "^3.1.1",
    "primeicons": "^1.0.0",
    "primeng": "^7.1.0",
    "rxjs": "^6.3.3",
    "rxjs-compat": "^6.0.0-rc.0",
    "signalr": "^2.4.1",
    "uuid": "^7.0.3",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.13.8",
    "@angular/compiler-cli": "^7.0.3",
    "@angular/language-service": "^7.0.3",
    "@types/file-saver": "^2.0.1",
    "@types/highcharts": "^5.0.34",
    "@types/jasmine": "^2.8.11",
    "@types/jasminewd2": "^2.0.6",
    "@types/lodash": "^4.14.118",
    "@types/node": "~8.9.4",
    "codelyzer": "^4.0.1",
    "cypress": "^8.5.0",
    "cypress-file-upload": "^5.0.8",
    "cypress-ntlm-auth": "3.2.2",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-ie-launcher": "^1.0.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-junit-reporter": "^1.2.0",
    "karma-parallel": "^0.3.1",
    "node-sass": "^4.14.1",
    "protractor": "~5.1.2",
    "sonar-scanner": "^3.1.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1",
    "tslint-config-intc-angular": "^1.0.0",
    "tslint-sonarts": "^1.9.0",
    "typescript": "~3.1.6",
    "xlsx": "^0.16.8"
  }

Here are the dependencies listed in ag-charts-community package.json file:

"devDependencies": {
    "@babel/types": "7.12.7",
    "@types/jest": "^25.2.1",
    "@types/jest-image-snapshot": "^4.3.1",
    "@types/node": "^16.0.0",
    "@types/pixelmatch": "^5.2.4",
    "@types/pngjs": "^6.0.1",
    "@types/ws": "8.5.3",
    "canvas": "^2.9.0",
    "eslint": "^6.8.0",
    "eslint-plugin-compat": "^3.5.1",
    "eslint-plugin-ie11": "^1.0.0",
    "glob": "8.0.3",
    "husky": "^8.0.1",
    "jest": "^25.4.0",
    "jest-canvas-mock": "2.3.1",
    "jest-image-snapshot": "^4.5.1",
    "jest-runner": "^25.4.0",
    "jest-serial-runner": "^1.2.0",
    "lint-staged": "^13.0.3",
    "pixelmatch": "^5.2.1",
    "prettier": "^2.7.1",
    "raf": "3.4.1",
    "rimraf": "3.0.2",
    "ts-jest": "^25.4.0",
    "typescript": "~3.7.7",
    "ws": "8.9.0"
  },

I haven't touched either of those lines, let alone anything in the library.

I've tried removing the node_modules folder and reinstalling it via npm install. I have a hunch that its a versioning issue, but I am not 100% sure as I am fairly new to typescript/angular in general.

I noticed that the typescript version for my project and the typescript version for this library do not line up, as the ag-charts-community typescript version is 3.7.7, while mine is 3.1.6. Could this be what's causing the issue or is it likely something else?


问:
find minium of increasing subseqeunces in permutation
i want to find one minimum of increasing subsequences List<int[] in a permutation 1-n. So i just needn't a number but the concrete subsequences.

Currently I search the longest increasing subsequence, delete these elements and search again, until no element left. But this isn't optimal.

Example:

1,4,3,2,5 -> 3 -> 1,2,5 4 3

1,4,5,2,3 -> 2 -> 1,4,5 2,3


问:
How to find out if a document is near similar from different documents in database using hashing algorithm?
Note: I have been trying to do a NLP project but stuck in this.
I have trying to find out fingerprint similarity of documents

The problem is I could not understand how to know if  documents are near similar by calculating the hamming distance from hash value of the documents and what conditions should applied after calculating the hamming distance to find their similarity between documents.

I have searched in the internet in validated sources still I have not got any good explanation on how to do it. If anybody could help, that would be good.


问:
Setting previously not pickleable attributes of a class during unpickling
I have classes that contain unpickleable attributes, e.g. COM interfaces. When I pickle the classes I can remove those attributes to make the whole instance of this class pickleable.
But when I unpickle the dumped data again, of course I want to re-establish those previously removed attributes. The easiest for me would be to provide the new values, e.g. the COM interfaces, as additional parameters to __setstate__() but of course this is not possible.

Is there another nice solution to this without setting all those attributes one by another from externally? Maybe something using __getnewargs__(), which I have not really understood yet?

Here is a minimal example:

```<code>import win32com.client as COM
import pickle

class Test:
    def __init__(self, app):
        self.app = app

    def __getstate__(self):
        attr = self.__dict__.copy()
        # Remove the unpicklable entries.
        attr['app'] = None
        return attr

    def __setstate__(self, attr):
        self.__dict__.update(attr)
        # FIXME: Re-establish COM interfaces here! Would be nice to provide
        # app as parameter an do self.app = app here.

# This must be done outside the class since it is only that easy in this
# minimal example.
app = COM.Dispatch('designer.Application')

test = Test(app)
with open('Test.pickle', 'wb') as fid:
    pickle.dump(test, fid)
with open('Test.pickle', 'rb') as fid:
    test_new = pickle.load(fid)

# Of course now I could do
# test_new.app = app
# But this is cumbersome with a lot of such attributes to be set...

print(test.app, test_new.app)
</code>```

Body:
I have classes that contain unpickleable attributes, e.g. COM interfaces. When I pickle the classes I can remove those attributes to make the whole instance of this class pickleable.
But when I unpickle the dumped data again, of course I want to re-establish those previously removed attributes. The easiest for me would be to provide the new values, e.g. the COM interfaces, as additional parameters to __setstate__() but of course this is not possible.

Is there another nice solution to this without setting all those attributes one by another from externally? Maybe something using __getnewargs__(), which I have not really understood yet?

Here is a minimal example:

import win32com.client as COM
import pickle

class Test:
    def __init__(self, app):
        self.app = app

    def __getstate__(self):
        attr = self.__dict__.copy()
        # Remove the unpicklable entries.
        attr['app'] = None
        return attr

    def __setstate__(self, attr):
        self.__dict__.update(attr)
        # FIXME: Re-establish COM interfaces here! Would be nice to provide
        # app as parameter an do self.app = app here.

# This must be done outside the class since it is only that easy in this
# minimal example.
app = COM.Dispatch('designer.Application')

test = Test(app)
with open('Test.pickle', 'wb') as fid:
    pickle.dump(test, fid)
with open('Test.pickle', 'rb') as fid:
    test_new = pickle.load(fid)

# Of course now I could do
# test_new.app = app
# But this is cumbersome with a lot of such attributes to be set...

print(test.app, test_new.app)


问:
Customize style of dropdown poup in Android WebView
I Would like to Customize the ui of dropdown popup inside webview.

Image

Can anyone here helpme to solve this ?


问:
Why is the whatsapp bot awnsering in the place of my zendesk bot?
We activated the messages feature on our Zendesk account and created a bot to one of the brands, the problem is that in the web widget the one that answers the messages isnt the bot created in zendesk but our whatsapp chatbot that is integrated to the account but it should not be in the web widget.

Any insights are aprecciated.


问:
Instagram 401 unauthorized
Im using the graphql api endpoint to call the endpoint to retrieve a posts information using the function below.

```<code>async function getInstagramData(url: string) {
  const postHash = '';
  const postAPI = `https://www.instagram.com/graphql/query/?query_hash=${postHash}&variables=${encodeURIComponent(
    `{"shortcode":"${getShortcode(url)}"}`
  )}`;

  console.log(postAPI);

  try {
    const respone = await axios.get(postAPI);
    const json = await respone.data;
    if (!json.data) return null;
    return json.data['shortcode_media'];
  } catch (error) {
    console.log(error);
    return null;
  }
}
</code>```

This works fine locally but doesn't work on the server as I get a 401 unauthorized. After looking into the response I found

```<code>data: {
    message: 'Please wait a few minutes before you try again.',
    require_login: true,
    status: 'fail'
}
</code>```

My question would be how I should log into the API.
From my understanding, I have two solutions (not sure if any of them are possible)

Call the Login API Endpoint store the cookies that are returned and use them when calling the endpoint above.

Is it possible to use a facebook APP ID in my get request to call the request via my application.

Title: Instagram 401 unauthorized

Body:
Im using the graphql api endpoint to call the endpoint to retrieve a posts information using the function below.

async function getInstagramData(url: string) {
  const postHash = '';
  const postAPI = `https://www.instagram.com/graphql/query/?query_hash=${postHash}&variables=${encodeURIComponent(
    `{"shortcode":"${getShortcode(url)}"}`
  )}`;

  console.log(postAPI);

  try {
    const respone = await axios.get(postAPI);
    const json = await respone.data;
    if (!json.data) return null;
    return json.data['shortcode_media'];
  } catch (error) {
    console.log(error);
    return null;
  }
}

This works fine locally but doesn't work on the server as I get a 401 unauthorized. After looking into the response I found

data: {
    message: 'Please wait a few minutes before you try again.',
    require_login: true,
    status: 'fail'
}

My question would be how I should log into the API.
From my understanding, I have two solutions (not sure if any of them are possible)

Call the Login API Endpoint store the cookies that are returned and use them when calling the endpoint above.

Is it possible to use a facebook APP ID in my get request to call the request via my application.


问:
Problem with pandas .corr() and seaborn heatmap
I have been trying to understand pd.corr() function and making it work with a heatmap.

I have a dataset built with the following columns :

a country column that stores country names (str)

an Industry column that stores industry names (str)

a profit column which stores profit values (int)

I turned the dataframe into a table. I tried to build a heatmap in order to check if there is a correlation between the Banking and Food industry according to profit values.

Here is the code I tried:

table = df.pivot_table(index="Country", columns="Industry", values="Profits (Billions)").reset_index()

sns.heatmap(table["Banking"].corr(table["Food, Drink & Tobacco"]))
```

It results in the following error :

ValueError: Must pass 2-d input. shape=()

Body:
I have been trying to understand pd.corr() function and making it work with a heatmap.

I have a dataset built with the following columns :

a country column that stores country names (str)

an Industry column that stores industry names (str)

a profit column which stores profit values (int)

I turned the dataframe into a table. I tried to build a heatmap in order to check if there is a correlation between the Banking and Food industry according to profit values.

Here is the code I tried:

table = df.pivot_table(index="Country", columns="Industry", values="Profits (Billions)").reset_index()

sns.heatmap(table["Banking"].corr(table["Food, Drink & Tobacco"]))

It results in the following error :

ValueError: Must pass 2-d input. shape=()


问:
Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [5], [batch]: [6]
enter image description here> image sample

Hello! I am trying to train a model. I had dataset of 3000 images(500~1000bite / 8bit / size: 200x50) and tried to learn dataset using package "CaptchCracker".But I it doesnt work.. The interesting thing is that it doesn't work when dataset has 3000 images, but it works when dataset has 300~400 images.
And it work only batch size: 1 (with 3000 images)

But I want to learn more than 3,000 images, batch size>1

I tried in (Python3.7.-numpy1.19.2-tensorflow2.3.0) and (Python3.7.-numpy1.19.5-tensorflow2.5.0)

please Help me. please..

-This is the image training code I tried.-

```<code>import glob
import CaptchaCracker as cc

train_img_path_list = glob.glob("data/*.png")

img_width = 200
img_height = 50

CM = cc.CreateModel(train_img_path_list, img_width, img_height)
model = CM.train_model(epochs=100)
model.save_weights("weights.h5")
</code>```

-I get following erros:-

```<code>Epoch 1/100
85/91 [===========================>..] - ETA: 2s - loss: 25.1152Traceback (most recent call last):
  File "C:\Users\rlack\OneDrive\wallpaper\ver_1\train.py", line 10, in <module>
    model = CM.train_model(epochs=100)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\CaptchaCracker\core.py", line 110, in train_model
    epochs=epochs
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\keras\engine\training.py", line 108, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1098, in fit
    tmp_logs = train_function(iterator)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\def_function.py", line 780, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\def_function.py", line 807, in _call
    return self._stateless_fn(*args, **kwds)  # pylint: disable=not-callable
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\function.py", line 2829, in __call__
    return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\function.py", line 1848, in _filtered_call
    cancellation_manager=cancellation_manager)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\function.py", line 1924, in _call_flat
    ctx, args, cancellation_manager=cancellation_manager))
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\function.py", line 550, in call
    ctx=ctx)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\execute.py", line 60, in quick_execute
    inputs, attrs, num_outputs)
tensorflow.python.framework.errors_impl.InvalidArgumentError:  Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [5], [batch]: [6]
     [[node IteratorGetNext (defined at \anaconda3\envs\cracker\lib\site-packages\CaptchaCracker\core.py:110) ]] [Op:__inference_train_function_12337]

Function call stack:
train_function

</code>```

-And this is core code of "CaptchaCracker"

```<code>import os
import glob
import numpy as np

from pathlib import Path
from collections import Counter

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

class CTCLayer(layers.Layer):
    def __init__(self, name=None):
        super().__init__(name=name)
        self.loss_fn = keras.backend.ctc_batch_cost

    def call(self, y_true, y_pred):
        # Compute the training-time loss value and add it
        # to the layer using `self.add_loss()`.
        batch_len = tf.cast(tf.shape(y_true)[0], dtype="int64")
        input_length = tf.cast(tf.shape(y_pred)[1], dtype="int64")
        label_length = tf.cast(tf.shape(y_true)[1], dtype="int64")

        input_length = input_length * tf.ones(shape=(batch_len, 1), dtype="int64")
        label_length = label_length * tf.ones(shape=(batch_len, 1), dtype="int64")

        loss = self.loss_fn(y_true, y_pred, input_length, label_length)
        self.add_loss(loss)

        # At test time, just return the computed predictions
        return y_pred

class CreateModel:

    def __init__(self, train_img_path, img_width=200, img_height=50):
        # Image Size
        self.img_width = img_width
        self.img_height = img_height
        # Learning Image File Path List
        self.images = sorted(train_img_path)
        # Learning Image File Label List
        self.labels = [img.split(os.path.sep)[-1].split(".png")[0] for img in self.images]
        # Label SET
        self.characters = set(char for label in self.labels for char in label)
        # Label maximum length
        self.max_length = max([len(label) for label in self.labels])

        # Mapping characters to integers
        self.char_to_num = layers.experimental.preprocessing.StringLookup(
            vocabulary=sorted(self.characters), num_oov_indices=0, mask_token=None
        )
        # Mapping integers back to original characters
        self.num_to_char = layers.experimental.preprocessing.StringLookup(
            vocabulary=self.char_to_num.get_vocabulary(), mask_token=None, invert=True
        )

    def train_model(self, epochs=100, earlystopping=False):
        # Define batch size for learning and validation
        batch_size = 16
        # Number of downsampling factors (Conv: 2, Pooling: 2)
        downsample_factor = 4

        # Splitting data into training and validation sets
        x_train, x_valid, y_train, y_valid = self.split_data(np.array(self.images), np.array(self.labels))

        train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
        train_dataset = (
            train_dataset.map(
                self.encode_single_sample, num_parallel_calls=tf.data.experimental.AUTOTUNE
            )
            .batch(batch_size)
            .prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
        )

        validation_dataset = tf.data.Dataset.from_tensor_slices((x_valid, y_valid))
        validation_dataset = (
            validation_dataset.map(
                self.encode_single_sample, num_parallel_calls=tf.data.experimental.AUTOTUNE
            )
            .batch(batch_size)
            .prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
        )

        # Get the model
        model = self.build_model()

        if earlystopping == True:

            early_stopping_patience = 10
            # Add early stopping
            early_stopping = keras.callbacks.EarlyStopping(
                monitor="val_loss", patience=early_stopping_patience, restore_best_weights=True
            )

            # Train the model
            history = model.fit(
                train_dataset,
                validation_data=validation_dataset,
                epochs=epochs,
                callbacks=[early_stopping],
            )

        else:
            # Train the model
            history = model.fit(
                train_dataset,
                validation_data=validation_dataset,
                epochs=epochs
            )

        return model

    def encode_single_sample(self, img_path, label):
        # 1. Read image
        img = tf.io.read_file(img_path)
        # 2. Decode and convert to grayscale
        img = tf.io.decode_png(img, channels=1)
        # 3. Convert to float32 in [0, 1] range
        img = tf.image.convert_image_dtype(img, tf.float32)
        # 4. Resize to the desired size
        img = tf.image.resize(img, [self.img_height, self.img_width])
        # 5. Transpose the image because we want the time
        # dimension to correspond to the width of the image.
        img = tf.transpose(img, perm=[1, 0, 2])
        # 6. Map the characters in label to numbers
        label = self.char_to_num(tf.strings.unicode_split(label, input_encoding="UTF-8"))
        # 7. Return a dict as our model is expecting two inputs
        return {"image": img, "label": label}

    def build_model(self):
        # Inputs to the model
        input_img = layers.Input(
            shape=(self.img_width, self.img_height, 1), name="image", dtype="float32"
        )
        labels = layers.Input(name="label", shape=(None,), dtype="float32")

        # First conv block
        x = layers.Conv2D(
            32,
            (3, 3),
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
            name="Conv1",
        )(input_img)
        x = layers.MaxPooling2D((2, 2), name="pool1")(x)

        # Second conv block
        x = layers.Conv2D(
            64,
            (3, 3),
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
            name="Conv2",
        )(x)
        x = layers.MaxPooling2D((2, 2), name="pool2")(x)

        # We have used two max pool with pool size and strides 2.
        # Hence, downsampled feature maps are 4x smaller. The number of
        # filters in the last layer is 64. Reshape accordingly before
        # passing the output to the RNN part of the model
        new_shape = ((self.img_width // 4), (self.img_height // 4) * 64)
        x = layers.Reshape(target_shape=new_shape, name="reshape")(x)
        x = layers.Dense(64, activation="relu", name="dense1")(x)
        x = layers.Dropout(0.2)(x)

        # RNNs
        x = layers.Bidirectional(layers.LSTM(128, return_sequences=True, dropout=0.25))(x)
        x = layers.Bidirectional(layers.LSTM(64, return_sequences=True, dropout=0.25))(x)

        # Output layer
        x = layers.Dense(len(self.characters) + 1, activation="softmax", name="dense2")(x)

        # Add CTC layer for calculating CTC loss at each step
        output = CTCLayer(name="ctc_loss")(labels, x)

        # Define the model
        model = keras.models.Model(
            inputs=[input_img, labels], outputs=output, name="ocr_model_v1"
        )
        # Optimizer
        opt = keras.optimizers.Adam()
        # Compile the model and return
        model.compile(optimizer=opt)
        return model

    def split_data(self, images, labels, train_size=0.9, shuffle=True):
        # 1. Get the total size of the dataset
        size = len(images)
        # 2. Make an indices array and shuffle it, if required
        indices = np.arange(size)
        if shuffle:
            np.random.shuffle(indices)
        # 3. Get the size of training samples
        train_samples = int(size * train_size)
        # 4. Split data into training and validation sets
        x_train, y_train = images[indices[:train_samples]], labels[indices[:train_samples]]
        x_valid, y_valid = images[indices[train_samples:]], labels[indices[train_samples:]]
        return x_train, x_valid, y_train, y_valid

class ApplyModel:

    def __init__(self,
                 weights_path,
                 img_width=200,
                 img_height=50,
                 max_length=6,
                 characters={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}):

        self.img_width = img_width
        self.img_height = img_height
        self.max_length = max_length
        self.characters = characters

        # Mapping characters to integers
        self.char_to_num = layers.experimental.preprocessing.StringLookup(
            vocabulary=sorted(self.characters), num_oov_indices=0, mask_token=None
        )
        # Mapping integers back to original characters
        self.num_to_char = layers.experimental.preprocessing.StringLookup(
            vocabulary=self.char_to_num.get_vocabulary(), mask_token=None, invert=True
        )
        # Model
        self.model = self.build_model()
        self.model.load_weights(weights_path)
        self.prediction_model = keras.models.Model(
            self.model.get_layer(name="image").input, self.model.get_layer(name="dense2").output
        )

    def predict(self, target_img_path):
        target_img = self.encode_single_sample(target_img_path)['image']
        target_img = tf.reshape(target_img, shape=[1,self.img_width,self.img_height,1])
        pred_val = self.prediction_model.predict(target_img)
        pred = self.decode_batch_predictions(pred_val)[0]
        return pred

    def encode_single_sample(self, img_path):
        # 1. Read image
        img = tf.io.read_file(img_path)
        # 2. Decode and convert to grayscale
        img = tf.io.decode_png(img, channels=1)
        # 3. Convert to float32 in [0, 1] range
        img = tf.image.convert_image_dtype(img, tf.float32)
        # 4. Resize to the desired size
        img = tf.image.resize(img, [self.img_height, self.img_width])
        # 5. Transpose the image because we want the time
        # dimension to correspond to the width of the image.
        img = tf.transpose(img, perm=[1, 0, 2])
        # 6. Map the characters in label to numbers
        # 7. Return a dict as our model is expecting two inputs
        return {"image": img}

    def build_model(self):
        # Inputs to the model
        input_img = layers.Input(
            shape=(self.img_width, self.img_height, 1), name="image", dtype="float32"
        )
        labels = layers.Input(name="label", shape=(None,), dtype="float32")

        # First conv block
        x = layers.Conv2D(
            32,
            (3, 3),
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
            name="Conv1",
        )(input_img)
        x = layers.MaxPooling2D((2, 2), name="pool1")(x)

        # Second conv block
        x = layers.Conv2D(
            64,
            (3, 3),
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
            name="Conv2",
        )(x)
        x = layers.MaxPooling2D((2, 2), name="pool2")(x)

        # We have used two max pool with pool size and strides 2.
        # Hence, downsampled feature maps are 4x smaller. The number of
        # filters in the last layer is 64. Reshape accordingly before
        # passing the output to the RNN part of the model
        new_shape = ((self.img_width // 4), (self.img_height // 4) * 64)
        x = layers.Reshape(target_shape=new_shape, name="reshape")(x)
        x = layers.Dense(64, activation="relu", name="dense1")(x)
        x = layers.Dropout(0.2)(x)

        # RNNs
        x = layers.Bidirectional(layers.LSTM(128, return_sequences=True, dropout=0.25))(x)
        x = layers.Bidirectional(layers.LSTM(64, return_sequences=True, dropout=0.25))(x)

        # Output layer
        x = layers.Dense(len(self.characters) + 1, activation="softmax", name="dense2")(x)

        # Add CTC layer for calculating CTC loss at each step
        output = CTCLayer(name="ctc_loss")(labels, x)

        # Define the model
        model = keras.models.Model(
            inputs=[input_img, labels], outputs=output, name="ocr_model_v1"
        )
        # Optimizer
        opt = keras.optimizers.Adam()
        # Compile the model and return
        model.compile(optimizer=opt)
        return model

    def split_data(self, images, labels, train_size=0.9, shuffle=True):
        # 1. Get the total size of the dataset
        size = len(images)
        # 2. Make an indices array and shuffle it, if required
        indices = np.arange(size)
        if shuffle:
            np.random.shuffle(indices)
        # 3. Get the size of training samples
        train_samples = int(size * train_size)
        # 4. Split data into training and validation sets
        x_train, y_train = images[indices[:train_samples]], labels[indices[:train_samples]]
        x_valid, y_valid = images[indices[train_samples:]], labels[indices[train_samples:]]
        return x_train, x_valid, y_train, y_valid

    # A utility function to decode the output of the network
    def decode_batch_predictions(self, pred):
        input_len = np.ones(pred.shape[0]) * pred.shape[1]
        # Use greedy search. For complex tasks, you can use beam search
        results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][
            :, :self.max_length
        ]
        # Iterate over the results and get back the text
        output_text = []
        for res in results:
            res = tf.strings.reduce_join(self.num_to_char(res+1)).numpy().decode("utf-8")
            output_text.append(res)
        return output_text
</code>```

What i tried
-Change image size of dataset
-Change version of python,numpy,tensorflow...
-Change computer with a good gpu.

I need help. thank you for reading.

Body:
enter image description here> image sample

Hello! I am trying to train a model. I had dataset of 3000 images(500~1000bite / 8bit / size: 200x50) and tried to learn dataset using package "CaptchCracker".But I it doesnt work.. The interesting thing is that it doesn't work when dataset has 3000 images, but it works when dataset has 300~400 images.
And it work only batch size: 1 (with 3000 images)

But I want to learn more than 3,000 images, batch size>1

I tried in (Python3.7.-numpy1.19.2-tensorflow2.3.0) and (Python3.7.-numpy1.19.5-tensorflow2.5.0)

please Help me. please..

-This is the image training code I tried.-

import glob
import CaptchaCracker as cc

train_img_path_list = glob.glob("data/*.png")

img_width = 200
img_height = 50

CM = cc.CreateModel(train_img_path_list, img_width, img_height)
model = CM.train_model(epochs=100)
model.save_weights("weights.h5")

-I get following erros:-

Epoch 1/100
85/91 [===========================>..] - ETA: 2s - loss: 25.1152Traceback (most recent call last):
  File "C:\Users\rlack\OneDrive\wallpaper\ver_1\train.py", line 10, in <module>
    model = CM.train_model(epochs=100)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\CaptchaCracker\core.py", line 110, in train_model
    epochs=epochs
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\keras\engine\training.py", line 108, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1098, in fit
    tmp_logs = train_function(iterator)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\def_function.py", line 780, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\def_function.py", line 807, in _call
    return self._stateless_fn(*args, **kwds)  # pylint: disable=not-callable
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\function.py", line 2829, in __call__
    return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\function.py", line 1848, in _filtered_call
    cancellation_manager=cancellation_manager)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\function.py", line 1924, in _call_flat
    ctx, args, cancellation_manager=cancellation_manager))
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\function.py", line 550, in call
    ctx=ctx)
  File "C:\Users\rlack\anaconda3\envs\cracker\lib\site-packages\tensorflow\python\eager\execute.py", line 60, in quick_execute
    inputs, attrs, num_outputs)
tensorflow.python.framework.errors_impl.InvalidArgumentError:  Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [5], [batch]: [6]
     [[node IteratorGetNext (defined at \anaconda3\envs\cracker\lib\site-packages\CaptchaCracker\core.py:110) ]] [Op:__inference_train_function_12337]

Function call stack:
train_function

-And this is core code of "CaptchaCracker"

import os
import glob
import numpy as np

from pathlib import Path
from collections import Counter

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

class CTCLayer(layers.Layer):
    def __init__(self, name=None):
        super().__init__(name=name)
        self.loss_fn = keras.backend.ctc_batch_cost

    def call(self, y_true, y_pred):
        # Compute the training-time loss value and add it
        # to the layer using `self.add_loss()`.
        batch_len = tf.cast(tf.shape(y_true)[0], dtype="int64")
        input_length = tf.cast(tf.shape(y_pred)[1], dtype="int64")
        label_length = tf.cast(tf.shape(y_true)[1], dtype="int64")

        input_length = input_length * tf.ones(shape=(batch_len, 1), dtype="int64")
        label_length = label_length * tf.ones(shape=(batch_len, 1), dtype="int64")

        loss = self.loss_fn(y_true, y_pred, input_length, label_length)
        self.add_loss(loss)

        # At test time, just return the computed predictions
        return y_pred

class CreateModel:

    def __init__(self, train_img_path, img_width=200, img_height=50):
        # Image Size
        self.img_width = img_width
        self.img_height = img_height
        # Learning Image File Path List
        self.images = sorted(train_img_path)
        # Learning Image File Label List
        self.labels = [img.split(os.path.sep)[-1].split(".png")[0] for img in self.images]
        # Label SET
        self.characters = set(char for label in self.labels for char in label)
        # Label maximum length
        self.max_length = max([len(label) for label in self.labels])

        # Mapping characters to integers
        self.char_to_num = layers.experimental.preprocessing.StringLookup(
            vocabulary=sorted(self.characters), num_oov_indices=0, mask_token=None
        )
        # Mapping integers back to original characters
        self.num_to_char = layers.experimental.preprocessing.StringLookup(
            vocabulary=self.char_to_num.get_vocabulary(), mask_token=None, invert=True
        )

    def train_model(self, epochs=100, earlystopping=False):
        # Define batch size for learning and validation
        batch_size = 16
        # Number of downsampling factors (Conv: 2, Pooling: 2)
        downsample_factor = 4

        # Splitting data into training and validation sets
        x_train, x_valid, y_train, y_valid = self.split_data(np.array(self.images), np.array(self.labels))

        train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
        train_dataset = (
            train_dataset.map(
                self.encode_single_sample, num_parallel_calls=tf.data.experimental.AUTOTUNE
            )
            .batch(batch_size)
            .prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
        )

        validation_dataset = tf.data.Dataset.from_tensor_slices((x_valid, y_valid))
        validation_dataset = (
            validation_dataset.map(
                self.encode_single_sample, num_parallel_calls=tf.data.experimental.AUTOTUNE
            )
            .batch(batch_size)
            .prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
        )

        # Get the model
        model = self.build_model()

        if earlystopping == True:

            early_stopping_patience = 10
            # Add early stopping
            early_stopping = keras.callbacks.EarlyStopping(
                monitor="val_loss", patience=early_stopping_patience, restore_best_weights=True
            )

            # Train the model
            history = model.fit(
                train_dataset,
                validation_data=validation_dataset,
                epochs=epochs,
                callbacks=[early_stopping],
            )

        else:
            # Train the model
            history = model.fit(
                train_dataset,
                validation_data=validation_dataset,
                epochs=epochs
            )

        return model

    def encode_single_sample(self, img_path, label):
        # 1. Read image
        img = tf.io.read_file(img_path)
        # 2. Decode and convert to grayscale
        img = tf.io.decode_png(img, channels=1)
        # 3. Convert to float32 in [0, 1] range
        img = tf.image.convert_image_dtype(img, tf.float32)
        # 4. Resize to the desired size
        img = tf.image.resize(img, [self.img_height, self.img_width])
        # 5. Transpose the image because we want the time
        # dimension to correspond to the width of the image.
        img = tf.transpose(img, perm=[1, 0, 2])
        # 6. Map the characters in label to numbers
        label = self.char_to_num(tf.strings.unicode_split(label, input_encoding="UTF-8"))
        # 7. Return a dict as our model is expecting two inputs
        return {"image": img, "label": label}

    def build_model(self):
        # Inputs to the model
        input_img = layers.Input(
            shape=(self.img_width, self.img_height, 1), name="image", dtype="float32"
        )
        labels = layers.Input(name="label", shape=(None,), dtype="float32")

        # First conv block
        x = layers.Conv2D(
            32,
            (3, 3),
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
            name="Conv1",
        )(input_img)
        x = layers.MaxPooling2D((2, 2), name="pool1")(x)

        # Second conv block
        x = layers.Conv2D(
            64,
            (3, 3),
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
            name="Conv2",
        )(x)
        x = layers.MaxPooling2D((2, 2), name="pool2")(x)

        # We have used two max pool with pool size and strides 2.
        # Hence, downsampled feature maps are 4x smaller. The number of
        # filters in the last layer is 64. Reshape accordingly before
        # passing the output to the RNN part of the model
        new_shape = ((self.img_width // 4), (self.img_height // 4) * 64)
        x = layers.Reshape(target_shape=new_shape, name="reshape")(x)
        x = layers.Dense(64, activation="relu", name="dense1")(x)
        x = layers.Dropout(0.2)(x)

        # RNNs
        x = layers.Bidirectional(layers.LSTM(128, return_sequences=True, dropout=0.25))(x)
        x = layers.Bidirectional(layers.LSTM(64, return_sequences=True, dropout=0.25))(x)

        # Output layer
        x = layers.Dense(len(self.characters) + 1, activation="softmax", name="dense2")(x)

        # Add CTC layer for calculating CTC loss at each step
        output = CTCLayer(name="ctc_loss")(labels, x)

        # Define the model
        model = keras.models.Model(
            inputs=[input_img, labels], outputs=output, name="ocr_model_v1"
        )
        # Optimizer
        opt = keras.optimizers.Adam()
        # Compile the model and return
        model.compile(optimizer=opt)
        return model

    def split_data(self, images, labels, train_size=0.9, shuffle=True):
        # 1. Get the total size of the dataset
        size = len(images)
        # 2. Make an indices array and shuffle it, if required
        indices = np.arange(size)
        if shuffle:
            np.random.shuffle(indices)
        # 3. Get the size of training samples
        train_samples = int(size * train_size)
        # 4. Split data into training and validation sets
        x_train, y_train = images[indices[:train_samples]], labels[indices[:train_samples]]
        x_valid, y_valid = images[indices[train_samples:]], labels[indices[train_samples:]]
        return x_train, x_valid, y_train, y_valid

class ApplyModel:

    def __init__(self,
                 weights_path,
                 img_width=200,
                 img_height=50,
                 max_length=6,
                 characters={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}):

        self.img_width = img_width
        self.img_height = img_height
        self.max_length = max_length
        self.characters = characters

        # Mapping characters to integers
        self.char_to_num = layers.experimental.preprocessing.StringLookup(
            vocabulary=sorted(self.characters), num_oov_indices=0, mask_token=None
        )
        # Mapping integers back to original characters
        self.num_to_char = layers.experimental.preprocessing.StringLookup(
            vocabulary=self.char_to_num.get_vocabulary(), mask_token=None, invert=True
        )
        # Model
        self.model = self.build_model()
        self.model.load_weights(weights_path)
        self.prediction_model = keras.models.Model(
            self.model.get_layer(name="image").input, self.model.get_layer(name="dense2").output
        )

    def predict(self, target_img_path):
        target_img = self.encode_single_sample(target_img_path)['image']
        target_img = tf.reshape(target_img, shape=[1,self.img_width,self.img_height,1])
        pred_val = self.prediction_model.predict(target_img)
        pred = self.decode_batch_predictions(pred_val)[0]
        return pred

    def encode_single_sample(self, img_path):
        # 1. Read image
        img = tf.io.read_file(img_path)
        # 2. Decode and convert to grayscale
        img = tf.io.decode_png(img, channels=1)
        # 3. Convert to float32 in [0, 1] range
        img = tf.image.convert_image_dtype(img, tf.float32)
        # 4. Resize to the desired size
        img = tf.image.resize(img, [self.img_height, self.img_width])
        # 5. Transpose the image because we want the time
        # dimension to correspond to the width of the image.
        img = tf.transpose(img, perm=[1, 0, 2])
        # 6. Map the characters in label to numbers
        # 7. Return a dict as our model is expecting two inputs
        return {"image": img}

    def build_model(self):
        # Inputs to the model
        input_img = layers.Input(
            shape=(self.img_width, self.img_height, 1), name="image", dtype="float32"
        )
        labels = layers.Input(name="label", shape=(None,), dtype="float32")

        # First conv block
        x = layers.Conv2D(
            32,
            (3, 3),
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
            name="Conv1",
        )(input_img)
        x = layers.MaxPooling2D((2, 2), name="pool1")(x)

        # Second conv block
        x = layers.Conv2D(
            64,
            (3, 3),
            activation="relu",
            kernel_initializer="he_normal",
            padding="same",
            name="Conv2",
        )(x)
        x = layers.MaxPooling2D((2, 2), name="pool2")(x)

        # We have used two max pool with pool size and strides 2.
        # Hence, downsampled feature maps are 4x smaller. The number of
        # filters in the last layer is 64. Reshape accordingly before
        # passing the output to the RNN part of the model
        new_shape = ((self.img_width // 4), (self.img_height // 4) * 64)
        x = layers.Reshape(target_shape=new_shape, name="reshape")(x)
        x = layers.Dense(64, activation="relu", name="dense1")(x)
        x = layers.Dropout(0.2)(x)

        # RNNs
        x = layers.Bidirectional(layers.LSTM(128, return_sequences=True, dropout=0.25))(x)
        x = layers.Bidirectional(layers.LSTM(64, return_sequences=True, dropout=0.25))(x)

        # Output layer
        x = layers.Dense(len(self.characters) + 1, activation="softmax", name="dense2")(x)

        # Add CTC layer for calculating CTC loss at each step
        output = CTCLayer(name="ctc_loss")(labels, x)

        # Define the model
        model = keras.models.Model(
            inputs=[input_img, labels], outputs=output, name="ocr_model_v1"
        )
        # Optimizer
        opt = keras.optimizers.Adam()
        # Compile the model and return
        model.compile(optimizer=opt)
        return model

    def split_data(self, images, labels, train_size=0.9, shuffle=True):
        # 1. Get the total size of the dataset
        size = len(images)
        # 2. Make an indices array and shuffle it, if required
        indices = np.arange(size)
        if shuffle:
            np.random.shuffle(indices)
        # 3. Get the size of training samples
        train_samples = int(size * train_size)
        # 4. Split data into training and validation sets
        x_train, y_train = images[indices[:train_samples]], labels[indices[:train_samples]]
        x_valid, y_valid = images[indices[train_samples:]], labels[indices[train_samples:]]
        return x_train, x_valid, y_train, y_valid

    # A utility function to decode the output of the network
    def decode_batch_predictions(self, pred):
        input_len = np.ones(pred.shape[0]) * pred.shape[1]
        # Use greedy search. For complex tasks, you can use beam search
        results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][
            :, :self.max_length
        ]
        # Iterate over the results and get back the text
        output_text = []
        for res in results:
            res = tf.strings.reduce_join(self.num_to_char(res+1)).numpy().decode("utf-8")
            output_text.append(res)
        return output_text

What i tried
-Change image size of dataset
-Change version of python,numpy,tensorflow...
-Change computer with a good gpu.

I need help. thank you for reading.


问:
GES ghe-repl-setup replica node cannot be reached over SSH and is not marked offline
I'm setting up a new replica for a GES primary that has never been replicated.  Followed all instructions with no problems until I run ghe-repl-setup.  This almost completes successfully, but fails right at the end on 'validating configuration' stating (on the replica node itself) that the replica node cannot be reached over ssh.

I have tested ssh connectivity from the primary to the replica on port 122 directly, and vice versa; all works as it should.  Partway through the ghe-repl-setup it actually connects to the primary over ssh and pulls keys over, so it can connect.  I have trawled every GES HA document I can find, there's no mention of this error.  Anyone else seen it?

This is the exact setup output (domain names and ip addresses redacted):

admin@github-domain-replica:~$ ghe-repl-setup github.domain

Error: Can't configure replication with the GitHub Enterprise Server hostname. Please configure with the primary's IP address.

admin@github-domain-replica:~$ ghe-repl-setup xx.xx.xx.xx

Verifying ssh connectivity with xx.xx.xx.xx ...

Connection check succeeded.

Updating Elasticsearch configuration ...

Elasticsearch isn't listening on tcp/9200.

Copying license and settings from primary appliance ...

Syncing Actions state files and certificates (if applicable) from primary appliance ...

--> Importing SSH host keys...

--> The SSH host keys on this appliance have been replaced to match the primary.

--> Please run 'ssh-keygen -R xx.xx.xx.xx; ssh-keygen -R "[xx.xx.xx.xx]:122"' on your client to prevent future ssh warnings.

Copying custom CA certificates from primary appliance ...

Validating configuration

Cluster node github-domain-replica (xx.xx.xx.xx) cannot be reached over SSH and is not marked offline

admin@github-domain-replica:~$

I expected the configuration validation to succeed, and finish, so that I could then start replication.


问:
Upgrading react-redux for react 18 breaks when using createRoot
We updated all packages in our legacy project to the latest versions:

react/react-dom: 18.2.0

react-redux: 7.2.0 => 8.0.5

redux: 4.0.5 => 4.2.0

redux-thunk: 2.3.0 => 2.4.2

By themselves, everything works. When we try to use the createRoot from 'react-dom/client', redux stops working.

No errors or warnings are shown in dev mode and tests render empty bodies.

We have a mix of class components using connect, mapToProps... and functional with useSelector.

All components using Redux stop working as they should. But only when using new createRoot. Using the legacy way, they work as normal.

Tables don't render what they should be rendering, or render old values. Tests break showing empty bodies...


问:
I'm trying to create a remix project but npx create-remix@latest doesn't work for me
I have this problem when I run the npx create-remix@latest command, I don't understand this problem because I only run the command to create a remix project

Bug image


问:
Gitlab Pipeline: lftp runs into a timeout
I received a notification a few days ago from my gitlab runner about a failed pipeline.
The Pipeline was working normally and nothing got changed, which makes everything a bit harder to investigate.
The specific command which causes the timeout of 1 hour is the following:

```<code>lftp -e "set ftp:ssl-allow no; mirror -R dist/ ./; quit;" -u $USER_TEST,$PASSWORD_TEST $HOST_TEST
</code>```

This was working fine. I tried to troubleshoot this problem. There are a plenty of reasons out there why the timeout happens. However none of it was solving my problem.

A short brief of what the git pipeline does:

building an angular app (the dist folder's size is about 750kB)

deploying it on a server using ftp credentials

I manually went through the pipeline steps, hoping to replicate the bug, but it was working fine.

.gitlab-ci.yml:

```<code>image: node:14.15.3-alpine
cache:
  paths:
    - node_modules/

stages:
  - build
  - deploy

#DEV Stage
build_stage_dev:
  stage: build
  only:
    refs:
      - develop
  cache:
    paths:
      - dist/
  script:
    - npm install --legacy-peer-deps
    - npm install -g @angular/cli@11.0.5
    - ng build --build-optimizer

deploy_stage_dev:
  stage: deploy
  environment: develop
  only:
    refs:
      - develop
  script:
    - apk update && apk add openssh-client && apk add sshpass
    - export SSHPASS=$PASSWORD_DEV
    #command to remove all files first
    #- sshpass -e ssh -o stricthostkeychecking=no $USER_DEV@$HOST_DEV rm -r /var/www/app/*
    - sshpass -e scp -o stricthostkeychecking=no -r dist/* $USER_DEV@$HOST_DEV:/var/www/app

#TEST Stage
build_stage_test:
  stage: build
  only:
    refs:
      - test
  cache:
    paths:
      - dist/
  script:
    - npm install --legacy-peer-deps
    - npm install -g @angular/cli@11.0.5
    - ng build --build-optimizer

deploy_stage_test:
  stage: deploy
  environment: test
  only:
    refs:
      - test
  script:
    - apk update && apk add lftp
    - lftp -e "set ftp:ssl-allow no; mirror -R dist/ ./; quit;" -u $USER_TEST,$PASSWORD_TEST $HOST_TEST

</code>```

The DEV Stage (deploying with the ssh) is working fine. Only the test stage throws an error after 1 hour.
This is the error I receive on Gitlab: ERROR: Job failed: execution took longer than 1h0m0s seconds

Maybe any of you have experienced the same? or did "lftp" got an update and I am running into an enndless job?
Also I checked whether files are getting updated at all, the answer is no. I thought it could be an issue with "quit". But appearently nothing is getting transferred at all.

Body:
I received a notification a few days ago from my gitlab runner about a failed pipeline.
The Pipeline was working normally and nothing got changed, which makes everything a bit harder to investigate.
The specific command which causes the timeout of 1 hour is the following:

lftp -e "set ftp:ssl-allow no; mirror -R dist/ ./; quit;" -u $USER_TEST,$PASSWORD_TEST $HOST_TEST

This was working fine. I tried to troubleshoot this problem. There are a plenty of reasons out there why the timeout happens. However none of it was solving my problem.

A short brief of what the git pipeline does:

building an angular app (the dist folder's size is about 750kB)

deploying it on a server using ftp credentials

I manually went through the pipeline steps, hoping to replicate the bug, but it was working fine.

.gitlab-ci.yml:

image: node:14.15.3-alpine
cache:
  paths:
    - node_modules/

stages:
  - build
  - deploy

#DEV Stage
build_stage_dev:
  stage: build
  only:
    refs:
      - develop
  cache:
    paths:
      - dist/
  script:
    - npm install --legacy-peer-deps
    - npm install -g @angular/cli@11.0.5
    - ng build --build-optimizer

deploy_stage_dev:
  stage: deploy
  environment: develop
  only:
    refs:
      - develop
  script:
    - apk update && apk add openssh-client && apk add sshpass
    - export SSHPASS=$PASSWORD_DEV
    #command to remove all files first
    #- sshpass -e ssh -o stricthostkeychecking=no $USER_DEV@$HOST_DEV rm -r /var/www/app/*
    - sshpass -e scp -o stricthostkeychecking=no -r dist/* $USER_DEV@$HOST_DEV:/var/www/app

#TEST Stage
build_stage_test:
  stage: build
  only:
    refs:
      - test
  cache:
    paths:
      - dist/
  script:
    - npm install --legacy-peer-deps
    - npm install -g @angular/cli@11.0.5
    - ng build --build-optimizer

deploy_stage_test:
  stage: deploy
  environment: test
  only:
    refs:
      - test
  script:
    - apk update && apk add lftp
    - lftp -e "set ftp:ssl-allow no; mirror -R dist/ ./; quit;" -u $USER_TEST,$PASSWORD_TEST $HOST_TEST

The DEV Stage (deploying with the ssh) is working fine. Only the test stage throws an error after 1 hour.
This is the error I receive on Gitlab: ERROR: Job failed: execution took longer than 1h0m0s seconds

Maybe any of you have experienced the same? or did "lftp" got an update and I am running into an enndless job?
Also I checked whether files are getting updated at all, the answer is no. I thought it could be an issue with "quit". But appearently nothing is getting transferred at all.


问:
NetGroupGetUsers returns error when group have members from other domain
I am using NetGroupGetUsers to get the members of Active Directory groups.
I have two domains and some groups have user members from both domains. When I try to list the members of this groups with mixed users, NetGroupGetUsers returns the error code 2147 (NERR_CfgParamNotFound).

Ex.:

"DOMAIN1" has "Group1" and "user1"

"DOMAIN2" has "user2"

"user1" and "user2" are both members of "Group1"

when I try to use NetGroupGetUsers to get "Group1" members it returns NERR_CfgParamNotFound

if I remove "user2" from "Group1", NetGroupGetUsers returns Success.

This case I described is not supported or there is a way to access this data using MFC Network Management?

Exemple of how I am using NetGroupGetUsers:

```<code>HRESULT MySampleFunction(CString strGroupName)
{
  TCHAR tcGroup[CREDUI_MAX_USERNAME_LENGTH + 1] = { 0 };
  TCHAR tcDomain[CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1] = { 0 };
  DWORD dwError = ::CredUIParseUserName(strGroupName, tcGroup, SizeOfArray(tcGroup), tcDomain, SizeOfArray(tcDomain));

  if (dwError != NO_ERROR)
    return MAKE_HRESULT(1, FACILITY_WIN32, dwError);

  GROUP_USERS_INFO_0* pGroupUsersInfo = NULL;
  DWORD dwEntriesRead = 0;
  DWORD dwTotalEntries = 0;

  NET_API_STATUS apiStatus = NetGroupGetUsers(tcDomain, tcGroup, 0, (LPBYTE*)&pGroupUsersInfo, MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, NULL);

  if (apiStatus != NERR_Success)
    return MAKE_HRESULT(1, FACILITY_WIN32, apiStatus);

  if (pGroupUsersInfo != NULL)
    NetApiBufferFree(pGroupUsersInfo);

  return S_OK
}
</code>```

Body:
I am using NetGroupGetUsers to get the members of Active Directory groups.
I have two domains and some groups have user members from both domains. When I try to list the members of this groups with mixed users, NetGroupGetUsers returns the error code 2147 (NERR_CfgParamNotFound).

Ex.:

"DOMAIN1" has "Group1" and "user1"

"DOMAIN2" has "user2"

"user1" and "user2" are both members of "Group1"

when I try to use NetGroupGetUsers to get "Group1" members it returns NERR_CfgParamNotFound

if I remove "user2" from "Group1", NetGroupGetUsers returns Success.

This case I described is not supported or there is a way to access this data using MFC Network Management?

Exemple of how I am using NetGroupGetUsers:

HRESULT MySampleFunction(CString strGroupName)
{
  TCHAR tcGroup[CREDUI_MAX_USERNAME_LENGTH + 1] = { 0 };
  TCHAR tcDomain[CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1] = { 0 };
  DWORD dwError = ::CredUIParseUserName(strGroupName, tcGroup, SizeOfArray(tcGroup), tcDomain, SizeOfArray(tcDomain));

  if (dwError != NO_ERROR)
    return MAKE_HRESULT(1, FACILITY_WIN32, dwError);

  GROUP_USERS_INFO_0* pGroupUsersInfo = NULL;
  DWORD dwEntriesRead = 0;
  DWORD dwTotalEntries = 0;

  NET_API_STATUS apiStatus = NetGroupGetUsers(tcDomain, tcGroup, 0, (LPBYTE*)&pGroupUsersInfo, MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, NULL);

  if (apiStatus != NERR_Success)
    return MAKE_HRESULT(1, FACILITY_WIN32, apiStatus);

  if (pGroupUsersInfo != NULL)
    NetApiBufferFree(pGroupUsersInfo);

  return S_OK
}


问:
Delphi IDE data explorer
Connection using FireDAC from within the IDE data explorer.

I'm trying to create a MSSQL connection using FireDAC from within the IDE data explorer, but when testing the connection, I'm always getting "Timeout Expired" error.
If create an application using FireDAC components (TFDConnection and TFDPhysMSSQLDriverLink1) with exact same parameters as within IDE data explorer connection, it just works fine.
What am I missing?

Title: Delphi IDE data explorer


问:
Why does MediaWiki DrawioEditor extension drop "Call to a member function getRepo() on bool" error?
I installed DrawioEditor extension for MediaWiki, but as soon as I insert {{#drawio:ChartName}} and save, I got the error message in the title with a fairly long backtrace. Can someone help me out here?

I am running:

MediaWiki   1.35.6
PHP 7.4.30 (fpm-fcgi)
MariaDB 10.3.32-MariaDB
DrawioEditor    1.1 (ec19d0f)20:07, 2023 January 5

Thank you in advance!

Attila

Based on another suggestion here (DrawioEditor extension does not seem to work in MediaWiki 1.33), I made sure NativeSvgHandler is properly installed, and the following options are active:

$wgDrawioEditorImageInteractive = true;

$wgFileExtensions[] = 'svg';

$wgEnableUploads = true;