问:
Python: type-hinting CTypes "pointer to X" types in a way that MyPy accepts
I have a large Python binding over a C library, with complex memory management. To help with that, I have drawn up the following aliases for strings (here, you a minimal reproducible example of my definitions and the subsequent problem).

from typing import Type, TypeAlias
from ctypes import POINTER, pointer, c_char, c_char_p

#normal python string
p_useable_p_str = str

#the result of a my_str.decode("utf-8")
c_useable_p_str = bytes

#used for string literals returned by the C, which should not be freed
p_useable_c_str = c_char_p

#used for allocated strings returned by the C, which need to be freed later
c_useable_c_str = POINTER(c_char)  #the problematic line

def example(hello: c_useable_c_str):  # source of the MyPy error
    pass
```
<p>My code runs fine (memory freed properly, consistent inheritance of the above if necessary, etc) when following the above definitions+usage conventions). <code>POINTER(c_char)</code> has the intended behavior in the rest of the code.</p>
<p>However, analyzing the above with MyPy, I get:</p>
```playground.py:10: error: Variable "playground.c_useable_c_str" is not valid as a type
playground.py:10: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)
```
<p>I get this error for anything that uses the <code>c_useable_c_str</code> alias. I, of course, read the section in the documentation linked above, and tried using Type and TypeAlias in a bunch of different ways - to no avail.</p>
<p>The only syntax that seems to make MyPy happy is</p>
<pre class="lang-py prettyprint-override"><code>c_useable_c_str = pointer[c_char]
</code>```

However, when actually running the code with this definition of the type alias, I get the following error (not seen by MyPy, so I suspect a bug on MyPy's end, or a lack of typing in the standard):

```<code>Traceback (most recent call last):
  File "/home/fulguritude/ProfessionalWork/LEDR/Orchestra-AvesTerra/Python_binding/playground2.py", line 92, in <module>
    c_useable_c_str = pointer[c_char]
TypeError: 'builtin_function_or_method' object is not subscriptable
</code>```

Any ideas as to how I'm supposed to make things consistent ?

TLDR: what's the valid way to type hint, and alias, a "pointer to X" with MyPy and CTypes ?

答:
I think you can use something like:</p>
```<code>if TYPE_CHECKING: # valid for mypy
    c_useable_c_str = pointer[c_char]  # the problematic line
else: # valid at run time
    c_useable_c_str = pointer
</code>```

Body:
I have a large Python binding over a C library, with complex memory management. To help with that, I have drawn up the following aliases for strings (here, you a minimal reproducible example of my definitions and the subsequent problem).

from typing import Type, TypeAlias
from ctypes import POINTER, pointer, c_char, c_char_p

#normal python string
p_useable_p_str = str

#the result of a my_str.decode("utf-8")
c_useable_p_str = bytes

#used for string literals returned by the C, which should not be freed
p_useable_c_str = c_char_p

#used for allocated strings returned by the C, which need to be freed later
c_useable_c_str = POINTER(c_char)  #the problematic line

def example(hello: c_useable_c_str):  # source of the MyPy error
    pass

My code runs fine (memory freed properly, consistent inheritance of the above if necessary, etc) when following the above definitions+usage conventions). POINTER(c_char) has the intended behavior in the rest of the code.

However, analyzing the above with MyPy, I get:

playground.py:10: error: Variable "playground.c_useable_c_str" is not valid as a type
playground.py:10: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)

I get this error for anything that uses the c_useable_c_str alias. I, of course, read the section in the documentation linked above, and tried using Type and TypeAlias in a bunch of different ways - to no avail.

The only syntax that seems to make MyPy happy is

c_useable_c_str = pointer[c_char]

However, when actually running the code with this definition of the type alias, I get the following error (not seen by MyPy, so I suspect a bug on MyPy's end, or a lack of typing in the standard):

Traceback (most recent call last):
  File "/home/fulguritude/ProfessionalWork/LEDR/Orchestra-AvesTerra/Python_binding/playground2.py", line 92, in <module>
    c_useable_c_str = pointer[c_char]
TypeError: 'builtin_function_or_method' object is not subscriptable

Any ideas as to how I'm supposed to make things consistent ?

TLDR: what's the valid way to type hint, and alias, a "pointer to X" with MyPy and CTypes ?

Body:
I think you can use something like:

if TYPE_CHECKING: # valid for mypy
    c_useable_c_str = pointer[c_char]  # the problematic line
else: # valid at run time
    c_useable_c_str = pointer


来源: stackexchange

问:
Koa & Passport Missing credentials
I have a Koa server that uses Passport to authenticate users against an Array,
and a React client. After successful login, the following requests are not authenticated as the cookie is undefined. The authenticate function's error parameter has:

```<code>{ message: 'Missing credentials' }
</code>```

After browsing the site, I fixed the usual errors, calling the returned function of authenticate, adding {credentials: 'include'} to fetch etc, but still I have the same problem.

Middleware list:
router.use(cookie.default());

app.use :

koa-body, koa-session-store (also tried with koa-session), passport.initialize(), passport.session(), router.routes(), koa-static

local strategy

```<code>passport.use(new Strategy((username,password,callback)=>{
    var u =  users.find(u=>u.username == username);
    return (u  && password == 'password')?  callback(null, u ):callback('user not found', false);
}));
</code>```

/login authenticate

```<code>.post('/login', (ctx)=>{
    console.log(ctx.request.body);
    return passport.authenticate('local',(err,user,info,status)=>{
        if(user) {
            ctx.login(user);
            ctx.body = {success: true}; // works correctly
            ctx.redirect('/login-success');
        } else {
            ctx.redirect('/login-failure');
        }
    })(ctx);
});
</code>```

/login-success

```<code>router.get('/login-success',async(ctx)=> {
    return passport.authenticate('local',(err,user,info,status)=>{
        console.log(err); // "Missing credentials"
    })(ctx);
    await ctx.response;
    ctx.body = {success: true};
}).
</code>```

Client call

```<code>let body = JSON.stringify({username: this.state.username, password: this.state.password});
let result = await fetch('http://localhost:4200/login',{method:'POST',credentials: 'include',body, headers:{'Content-Type':'application/json'}});
</code>```

答:
The fix is actually simple, but the reason is hard to find.

async middleware must either call await next() or return next() at the end.
Otherwise a 404 error is caused.

Adding await next() to the async /login-success callback, fixed the issue.

Documentation: https://github.com/koajs/koa/blob/master/docs/troubleshooting.md#my-middleware-is-not-called

ContentLicense: CC BY-SA 4.0

Title: Koa & Passport Missing credentials

Body:
I have a Koa server that uses Passport to authenticate users against an Array,
and a React client. After successful login, the following requests are not authenticated as the cookie is undefined. The authenticate function's error parameter has:

{ message: 'Missing credentials' }

After browsing the site, I fixed the usual errors, calling the returned function of authenticate, adding {credentials: 'include'} to fetch etc, but still I have the same problem.

Middleware list:
router.use(cookie.default());

app.use :

koa-body, koa-session-store (also tried with koa-session), passport.initialize(), passport.session(), router.routes(), koa-static

local strategy

passport.use(new Strategy((username,password,callback)=>{
    var u =  users.find(u=>u.username == username);
    return (u  && password == 'password')?  callback(null, u ):callback('user not found', false);
}));

/login authenticate

.post('/login', (ctx)=>{
    console.log(ctx.request.body);
    return passport.authenticate('local',(err,user,info,status)=>{
        if(user) {
            ctx.login(user);
            ctx.body = {success: true}; // works correctly
            ctx.redirect('/login-success');
        } else {
            ctx.redirect('/login-failure');
        }
    })(ctx);
});

/login-success

router.get('/login-success',async(ctx)=> {
    return passport.authenticate('local',(err,user,info,status)=>{
        console.log(err); // "Missing credentials"
    })(ctx);
    await ctx.response;
    ctx.body = {success: true};
}).

Client call

let body = JSON.stringify({username: this.state.username, password: this.state.password});
let result = await fetch('http://localhost:4200/login',{method:'POST',credentials: 'include',body, headers:{'Content-Type':'application/json'}});


问:
Ping Docker Container from another machine in the network
I have created a docker container and tried pinging www.google.com within the bash of the container and it works. Also I tried pinging the container from the host - it works perfectly fine.

But when I try to ping the container from a external system in the network, it gives me a request timed out exception.

I am planning to install a tomcat webserver on a container and allow other containers to access the application deployed in the server. Would appreciate some help!

答:
I installed docker desktop in windows 10.  I faced similar challenge to ping the container from windows 10. Since the docker host cannot reach the linux containers(Known limitations, use cases, and workarounds), here is a way to reach out the container ip.  We can ping via vEthernet WSL ip to Docker Gateway to Container ip.

Solution:

type "ipconfig /all" in host command prompt.

find the ip of "Ethernet adapter vEthernet (WSL)"

vEthernet (WSL) ip

Containers running:

Ping thru vEthernet (WSL) ip

Similar to the above, other containers are also pinging from windows 10.

Hope this helps for windows users.

ContentLicense: CC BY-SA 3.0


问:
How do I use cordova firebase.dynamiclinks plugin in Ionic 4?
I want to use Cordova Firebase Dynamiclinks plugin : https://github.com/chemerisuk/cordova-plugin-firebase-dynamiclinks#installation in my Ionic 4 App.

There is an Ionic-native-plugin usage for this too : npm install @ionic-native/firebase-dynamic-links and usage :

```<code>import { FirebaseDynamicLinks } from '@ionic-native/firebase-dynamic-links/ngx';

constructor(private firebaseDynamicLinks: FirebaseDynamicLinks) { }

...
this.firebaseDynamicLinks.onDynamicLink()
  .subscribe((res: any) => console.log(res), (error:any) => console.log(error));
</code>```

Issue is : I want to use createDynamicLink(parameters) method available in Cordova Firebase Dynamiclinks plugin but Ionic-native-plugin says

Property 'createDynamicLink' does not exist on type 'FirebaseDynamicLinks'.

Therefore, I need to use Cordova Firebase Dynamiclinks directly and I tried doing using it like

```<code>import { cordova } from '@ionic-native/core';
...
cordova.plugins.firebase.dynamiclinks.createDynamicLink({
    link: "https://google.com"
}).then(function(url) {
    console.log("Dynamic link was created:", url);
});
</code>```

But got error

Property 'plugins' does not exist on type '(pluginObj: any, methodName: string, config: CordovaOptions, args: IArguments | any[]) => any'.

Also tried removing import

```<code>cordova.plugins.firebase.dynamiclinks.createDynamicLink({
    link: "https://google.com"
}).then(function(url) {
    console.log("Dynamic link was created:", url);
});
</code>```

And got this

Property 'firebase' does not exist on type 'CordovaPlugins'.

What is the correct usage of cordova plugins?

Update

Ionic-native-plugin now contains all the methods available in Cordova Firebase Dynamiclinks plugin.

答:
I have developed an ionic 5 app that uses Firebase Dynamic Links and it works great but it took some effort.  I watched videos to understand how Firebase Dynamic Links work but there is certainly much that is not shown.

To answer the original question you can always manually create a dynamic link which is what I do in our solution.  We created a dynamic link that would help users onboard (register an account).  Our dynamic link has custom onboardingId which originates from the backend process and the link is presented to the user via SMS text message.

This is in app.component.ts constructor
Here is some code that happens when the user clicks the dynamic link:

```<code>// Handle the logic here after opening the app (app is already installed) with the Dynamic link
this.firebaseDynamicLinks.onDynamicLink().subscribe((res: any) =>  {
  console.log('app was opened with dynamic link');
  console.log(res);
  /*   This only fires on subsequent calls and not on app start 20220208 STR
  console.log(JSON.stringify(res)); //"{"deepLink":"https://localhost/onboard?onboardingId=8ed634b0-53b7-4a0f-b67e-12c06019982a","clickTimestamp":1643908387670,"minimumAppVersion":0}"
  var dynamicLink = JSON.parse(JSON.stringify(res));
  var deepLink = dynamicLink.deepLink;
  console.log(deepLink);
  if (deepLink.indexOf("onboard")>=0){
    this.isOnboarding = true;
  }
  alert("deepLink ="+ deepLink);
  */
}, (error:any) => {
  console.log(error)
});
</code>```

I originally thought that Firebase handles all of the magic if the user doesn't have the app installed.   I was wrong!  You MUST also handle the code to pickup the dynamic link after the app is installed.

The code below will read the dynamic link from the clipboard and survives the app install process.    Placed in app.component.ts ngOnInit().

```<code>this.platform.ready().then(() => {

  this.firebaseDynamicLinks.getDynamicLink().then((data) => {
    //added 20220208 STR try to help open the deep link if app is just installed
    if (data != null) {
      console.log(JSON.stringify(data));
      //alert("initializeApp():"+JSON.stringify(data));
      var dynamicLink = JSON.parse(JSON.stringify(data));
      var deepLink = dynamicLink.deepLink;
      console.log("initializeApp():"+deepLink);
      if (deepLink != "") {
        if (deepLink.indexOf("onboard")>=0){
          this.isOnboarding = true;
          this.deepLinkToOnboard(deepLink);
        }
      }
    }
  });}
</code>```

So to handle dynamic links after you have the Firebase plugin installed, you must have two sections of code; one for handling if the app is already installed and another for handling the dynamic link if the app is not installed.

Body:
I want to use Cordova Firebase Dynamiclinks plugin : https://github.com/chemerisuk/cordova-plugin-firebase-dynamiclinks#installation in my Ionic 4 App.

There is an Ionic-native-plugin usage for this too : npm install @ionic-native/firebase-dynamic-links and usage :

import { FirebaseDynamicLinks } from '@ionic-native/firebase-dynamic-links/ngx';

constructor(private firebaseDynamicLinks: FirebaseDynamicLinks) { }

...
this.firebaseDynamicLinks.onDynamicLink()
  .subscribe((res: any) => console.log(res), (error:any) => console.log(error));

Issue is : I want to use createDynamicLink(parameters) method available in Cordova Firebase Dynamiclinks plugin but Ionic-native-plugin says

Property 'createDynamicLink' does not exist on type 'FirebaseDynamicLinks'.

Therefore, I need to use Cordova Firebase Dynamiclinks directly and I tried doing using it like

import { cordova } from '@ionic-native/core';
...
cordova.plugins.firebase.dynamiclinks.createDynamicLink({
    link: "https://google.com"
}).then(function(url) {
    console.log("Dynamic link was created:", url);
});

But got error

Property 'plugins' does not exist on type '(pluginObj: any, methodName: string, config: CordovaOptions, args: IArguments | any[]) => any'.

Also tried removing import

cordova.plugins.firebase.dynamiclinks.createDynamicLink({
    link: "https://google.com"
}).then(function(url) {
    console.log("Dynamic link was created:", url);
});

And got this

Property 'firebase' does not exist on type 'CordovaPlugins'.

What is the correct usage of cordova plugins?

Update

Ionic-native-plugin now contains all the methods available in Cordova Firebase Dynamiclinks plugin.

Body:
I have developed an ionic 5 app that uses Firebase Dynamic Links and it works great but it took some effort.  I watched videos to understand how Firebase Dynamic Links work but there is certainly much that is not shown.

To answer the original question you can always manually create a dynamic link which is what I do in our solution.  We created a dynamic link that would help users onboard (register an account).  Our dynamic link has custom onboardingId which originates from the backend process and the link is presented to the user via SMS text message.

This is in app.component.ts constructor
Here is some code that happens when the user clicks the dynamic link:

// Handle the logic here after opening the app (app is already installed) with the Dynamic link
this.firebaseDynamicLinks.onDynamicLink().subscribe((res: any) =>  {
  console.log('app was opened with dynamic link');
  console.log(res);
  /*   This only fires on subsequent calls and not on app start 20220208 STR
  console.log(JSON.stringify(res)); //"{"deepLink":"https://localhost/onboard?onboardingId=8ed634b0-53b7-4a0f-b67e-12c06019982a","clickTimestamp":1643908387670,"minimumAppVersion":0}"
  var dynamicLink = JSON.parse(JSON.stringify(res));
  var deepLink = dynamicLink.deepLink;
  console.log(deepLink);
  if (deepLink.indexOf("onboard")>=0){
    this.isOnboarding = true;
  }
  alert("deepLink ="+ deepLink);
  */
}, (error:any) => {
  console.log(error)
});

I originally thought that Firebase handles all of the magic if the user doesn't have the app installed.   I was wrong!  You MUST also handle the code to pickup the dynamic link after the app is installed.

The code below will read the dynamic link from the clipboard and survives the app install process.    Placed in app.component.ts ngOnInit().

this.platform.ready().then(() => {

  this.firebaseDynamicLinks.getDynamicLink().then((data) => {
    //added 20220208 STR try to help open the deep link if app is just installed
    if (data != null) {
      console.log(JSON.stringify(data));
      //alert("initializeApp():"+JSON.stringify(data));
      var dynamicLink = JSON.parse(JSON.stringify(data));
      var deepLink = dynamicLink.deepLink;
      console.log("initializeApp():"+deepLink);
      if (deepLink != "") {
        if (deepLink.indexOf("onboard")>=0){
          this.isOnboarding = true;
          this.deepLinkToOnboard(deepLink);
        }
      }
    }
  });}

So to handle dynamic links after you have the Firebase plugin installed, you must have two sections of code; one for handling if the app is already installed and another for handling the dynamic link if the app is not installed.


问:
How can I get Eclipselink working in a Spring Boot application
copied my boot log to a gist because it's too long for SE.

here's what I suspect is the important part of the message.

```<code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:641)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1157)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:280)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
... 145 more
</code>```

also here's my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://maven.apache.org/POM/4.0.0"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.xenoterracide</groupId>
<artifactId>rpf</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.8.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>
    <!--
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.7.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.3-1102-jdbc41</version>
    </dependency>
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

<properties>
    <!-- use UTF-8 for everything -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <start-class>com.xenoterracide.rpf.Application</start-class>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <artifactId>eclipselink-staticweave-maven-plugin</artifactId>
            <groupId>au.com.alderaan</groupId>
            <version>1.0.4</version>
            <executions>
                <execution>
                    <goals>
                        <goal>weave</goal>
                    </goals>
                    <phase>process-classes</phase>
                    <configuration>
                        <logLevel>ALL</logLevel>
                    </configuration>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>eclipselink</artifactId>
                    <version>2.5.2</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-releases</id>
        <url>http://repo.spring.io/libs-release</url>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>http://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

</project>
</code>```

I'm using IDEA with it's built in "make" to compile and start the app.

I tried adding this class, but it didn't appear to help

```<code>class EntityManagerFactoryProducer {

@Produces
@ApplicationScoped
public EntityManagerFactory createEntityManagerFactory() {
  return Persistence.createEntityManagerFactory("my-presistence-unit");
}

public void close(@Disposes EntityManagerFactory entityManagerFactory) {
  entityManagerFactory.close();
}

@Produces
@RequestScoped
public EntityManager createEntityManager(EntityManagerFactory entityManagerFactory) {
  return entityManagerFactory.createEntityManager();
}

public void close(@Disposes EntityManager entityManager) {
  entityManager.close();
}
}
</code>```

答:
I ran into a similar issue where I received the same No bean named 'entityManagerFactory' is defined exception.  My fix was to define the bean in my configuration class.</p>
```<code>@Configuration
public class JpaConfiguration extends JpaBaseConfiguration {
...
    @Bean
    public EntityManagerFactory entityManagerFactory() {
        return Persistence.createEntityManagerFactory("my-persistence-unit");
    }
}
</code>```

Body:
copied my boot log to a gist because it's too long for SE.

here's what I suspect is the important part of the message.

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:641)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1157)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:280)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
... 145 more

also here's my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://maven.apache.org/POM/4.0.0"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.xenoterracide</groupId>
<artifactId>rpf</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.8.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.7.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.3-1102-jdbc41</version>
    </dependency>
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

<properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <start-class>com.xenoterracide.rpf.Application</start-class>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <artifactId>eclipselink-staticweave-maven-plugin</artifactId>
            <groupId>au.com.alderaan</groupId>
            <version>1.0.4</version>
            <executions>
                <execution>
                    <goals>
                        <goal>weave</goal>
                    </goals>
                    <phase>process-classes</phase>
                    <configuration>
                        <logLevel>ALL</logLevel>
                    </configuration>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>eclipselink</artifactId>
                    <version>2.5.2</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-releases</id>
        <url>http://repo.spring.io/libs-release</url>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>http://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

</project>

I'm using IDEA with it's built in "make" to compile and start the app.

I tried adding this class, but it didn't appear to help

class EntityManagerFactoryProducer {

@Produces
@ApplicationScoped
public EntityManagerFactory createEntityManagerFactory() {
  return Persistence.createEntityManagerFactory("my-presistence-unit");
}

public void close(@Disposes EntityManagerFactory entityManagerFactory) {
  entityManagerFactory.close();
}

@Produces
@RequestScoped
public EntityManager createEntityManager(EntityManagerFactory entityManagerFactory) {
  return entityManagerFactory.createEntityManager();
}

public void close(@Disposes EntityManager entityManager) {
  entityManager.close();
}
}

Body:
I ran into a similar issue where I received the same No bean named 'entityManagerFactory' is defined exception.  My fix was to define the bean in my configuration class.

@Configuration
public class JpaConfiguration extends JpaBaseConfiguration {
...
    @Bean
    public EntityManagerFactory entityManagerFactory() {
        return Persistence.createEntityManagerFactory("my-persistence-unit");
    }
}


问:
Delete visible filtered Rows, Run-time error 1004:Cannot use that command on overlapping selections
I need to delete visible filtered Rows.

I got this  Run-time error 1004: Cannot use that command on overlapping selections.

My data has header on first row.

In advance , greatfull for your help.

```<code>Sub Macro2()

    Dim rng As Range: Set rng = ActiveSheet.Range("A1:Q6880")
    rng.AutoFilter Field:=8, Criteria1:="0"
    rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete

End Sub
</code>```

答:
Delete Filtered Rows

Option Explicit

Sub Macro2()

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    If ws.AutoFilterMode Then ws.AutoFilterMode = False

    Dim rng As Range: Set rng = ws.Range("A1:Q6880")
    ' If your range is contiguous (no empty rows or columns):
    'Dim rng As Range: Set rng = ws.Range("A1").CurrentRegion

    Dim fcrg As Range: Set fcrg = rng.Columns(8) ' Filter Column Range
    ' Filter Column Data Range (no headers)
    Dim fcdrg As Range: Set fcdrg = fcrg.Resize(fcrg.Rows.Count - 1).Offset(1)

    fcrg.AutoFilter Field:=1, Criteria1:="0"

    Dim vfcdrg As Range ' Visible Filter Column Data Range
    On Error Resume Next
        Set vfcdrg = fcdrg.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    ws.AutoFilterMode = False
    If vfcdrg Is Nothing Then Exit Sub ' no filtered values

    vfcdrg.EntireRow.Delete

End Sub
```

Body:
I need to delete visible filtered Rows.

I got this  Run-time error 1004: Cannot use that command on overlapping selections.

My data has header on first row.

In advance , greatfull for your help.

Sub Macro2()

    Dim rng As Range: Set rng = ActiveSheet.Range("A1:Q6880")
    rng.AutoFilter Field:=8, Criteria1:="0"
    rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete

End Sub


问:
How to check if an object is an Express instance?
I'm using typescript to check if an app returned by Express() is an Express instance.

I'm doing this:

```<code>import Express from "express"

const app = Express()

console.log(app instanceof Express)
</code>```

But it is always returning false

答:
There is no instanceof way to check it.

So finally I did:

if ( !app.hasOwnProperty("listen") || typeof app.listen !== "function" ) {
  // So it's not an Express instance
}
```

Rest is to trust in god.

Body:
I'm using typescript to check if an app returned by Express() is an Express instance.

I'm doing this:

import Express from "express"

const app = Express()

console.log(app instanceof Express)

But it is always returning false

Body:
There is no instanceof way to check it.

So finally I did:

if ( !app.hasOwnProperty("listen") || typeof app.listen !== "function" ) {
  // So it's not an Express instance
}

Rest is to trust in god.


问:
How can i set a tag for viewpager fragments?
I,m using slidingTabLayout with 4 tabs and a viewpager and 4 fragment class for every tab.

i need to reload one of my fragments (first tab) in my project when user click some button, and for this i need to have a tag for that fragment

my question is : how can i set a tag for one of viewpagers fragment???

My MainActivity tab and viewpager codes:

```<code>public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"نوع","قیمت","برند","همه"};
int Numboftabs = 4;

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "درج آگهی رایگان", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.colorWhite);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);
    pager.setCurrentItem(3);

} and ....
</code>```

Thank you a lot

答:
In case anyone's using FragmentStateAdapter, the tag is a bit different.
This is the code from FragmentStateAdapter:

```<code>mFragmentManager.beginTransaction()
    .add(fragment, "f" + holder.getItemId())
    .setMaxLifecycle(fragment, STARTED)
    .commitNow();
</code>```

As you can see it's a combination of static string "f" and getItemId().
After overriding fun getItemId(position: Int): Long in your adapter, finding a specific fragment should be quite simple to do. For example, override fun

```<code>getItemId(position: Int): Long {
    return if(position == 0) {
            "my_first_fragment"
    }else "my_second_fragment"
}
</code>```

The tag for our first fragment would be "fmy_first_fragment" and found with childFragmentManager.findFragmentByTag("fmy_first_fragment") as? MyFirstFragment

Careful whenever you look for fragment, you have to use the same FragmentManager as was used to create it. So I recommend creating your adapter with FragmentManager and LifeCycle as a constructor.

Body:
I,m using slidingTabLayout with 4 tabs and a viewpager and 4 fragment class for every tab.

i need to reload one of my fragments (first tab) in my project when user click some button, and for this i need to have a tag for that fragment

my question is : how can i set a tag for one of viewpagers fragment???

My MainActivity tab and viewpager codes:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"نوع","قیمت","برند","همه"};
int Numboftabs = 4;

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "درج آگهی رایگان", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.colorWhite);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);
    pager.setCurrentItem(3);

} and ....

Thank you a lot

Body:
In case anyone's using FragmentStateAdapter, the tag is a bit different.
This is the code from FragmentStateAdapter:

mFragmentManager.beginTransaction()
    .add(fragment, "f" + holder.getItemId())
    .setMaxLifecycle(fragment, STARTED)
    .commitNow();

As you can see it's a combination of static string "f" and getItemId().
After overriding fun getItemId(position: Int): Long in your adapter, finding a specific fragment should be quite simple to do. For example, override fun

getItemId(position: Int): Long {
    return if(position == 0) {
            "my_first_fragment"
    }else "my_second_fragment"
}

The tag for our first fragment would be "fmy_first_fragment" and found with childFragmentManager.findFragmentByTag("fmy_first_fragment") as? MyFirstFragment

Careful whenever you look for fragment, you have to use the same FragmentManager as was used to create it. So I recommend creating your adapter with FragmentManager and LifeCycle as a constructor.


问:
Heroku Shopify Application Error 'npm ERR! ERESOLVE unable to resolve dependency tree'
Greetings I have a problem with Heroku because it's don't want to install legacy packages for my Shopify app, my Shopify app is on Github and I just set up everything that my application needs, but when I deploy the main branch on Heroku I get this error in Heroku console below, can someone help me fix this?

```<code>-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/nodejs
-----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       USE_NPM_INSTALL=true
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=false

-----> Installing binaries
       engines.node (package.json):  unspecified
       engines.npm (package.json):   unspecified (use default)

       Resolving node version 16.x...
       Downloading and installing node 16.14.0...
       Using default npm version: 8.3.1

-----> Restoring cache
       Caching has been disabled because NODE_MODULES_CACHE=false

-----> Installing dependencies
       Installing node modules (package.json + package-lock)
       npm ERR! code ERESOLVE
       npm ERR! ERESOLVE unable to resolve dependency tree
       npm ERR!
       npm ERR! While resolving: shopify-app-node@1.0.0
       npm ERR! Found: react@16.14.0
       npm ERR! node_modules/react
       npm ERR!   react@"^16.10.1" from the root project
       npm ERR!
       npm ERR! Could not resolve dependency:
       npm ERR! peer react@"^17.0.2 || ^18.0.0-0" from next@12.0.10
       npm ERR! node_modules/next
       npm ERR!   next@"^12.0.2" from the root project
       npm ERR!
       npm ERR! Fix the upstream dependency conflict, or retry
       npm ERR! this command with --force, or --legacy-peer-deps
       npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
       npm ERR!
       npm ERR! See /tmp/npmcache.CTfHl/eresolve-report.txt for a full report.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.CTfHl/_logs/2022-02-10T12_18_50_156Z-debug-0.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - Node version not specified in package.json
         https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed
</code>```

My package.json

```<code>{
  "name": "shopify-app-node",
  "version": "1.0.0",
  "description": "Shopify's node app for CLI tool",
  "scripts": {
    "test": "jest",
    "dev": "cross-env NODE_ENV=development nodemon ./server/index.js --watch ./server/index.js",
    "build": "NEXT_TELEMETRY_DISABLED=1 next build",
    "start": "cross-env NODE_ENV=production node ./server/index.js"
  },
  "engines": {
    "node": "16.14.0",
    "npm": "8.4.1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Shopify/shopify-app-node.git"
  },
  "author": "Shopify Inc.",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/shopify/shopify-app-node/issues"
  },
  "dependencies": {
    "@babel/core": "7.12.10",
    "@babel/polyfill": "^7.6.0",
    "@babel/preset-env": "^7.12.11",
    "@babel/register": "^7.12.10",
    "@shopify/app-bridge-react": "^2.0.2",
    "@shopify/app-bridge-utils": "^2.0.2",
    "@shopify/koa-shopify-auth": "^4.1.2",
    "@shopify/polaris": "^6.2.0",
    "apollo-boost": "^0.4.9",
    "axios": "^0.25.0",
    "cross-env": "^7.0.3",
    "dotenv": "^8.2.0",
    "graphql": "^14.5.8",
    "isomorphic-fetch": "^3.0.0",
    "koa": "^2.13.1",
    "koa-bodyparser": "^4.3.0",
    "koa-compress": "^5.1.0",
    "koa-cors": "0.0.16",
    "koa-logger": "^3.2.1",
    "koa-router": "^10.0.0",
    "koa-session": "^6.1.0",
    "mysql2": "^2.3.3",
    "next": "^12.0.2",
    "next-env": "^1.1.0",
    "node-fetch": "^2.6.7",
    "react": "^16.10.1",
    "react-apollo": "^3.1.3",
    "react-dom": "^16.10.1",
    "sequelize": "^6.13.0",
    "slugify": "^1.6.5",
    "validator": "^13.7.0",
    "webpack": "^4.44.1"
  },
  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.12.10",
    "@babel/preset-stage-3": "^7.0.0",
    "babel-jest": "26.6.3",
    "babel-register": "^6.26.0",
    "enzyme": "3.11.0",
    "enzyme-adapter-react-16": "1.15.6",
    "husky": "^4.3.6",
    "jest": "26.6.3",
    "lint-staged": "^10.5.4",
    "nodemon": "^2.0.7",
    "prettier": "2.2.1",
    "react-addons-test-utils": "15.6.2",
    "react-test-renderer": "16.14.0"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,css,json,md}": [
      "prettier --write"
    ]
  }
}
</code>```

答:
I install these old packages with npm install --force

I run npm outdated

I see what packages are in red

I do upgrade from the current version to the wanted version with npm install --save packagename@wanted_version

Remove any empty files that you may have in your project

Uploaded to git

Deploy to Heroku

Body:
Greetings I have a problem with Heroku because it's don't want to install legacy packages for my Shopify app, my Shopify app is on Github and I just set up everything that my application needs, but when I deploy the main branch on Heroku I get this error in Heroku console below, can someone help me fix this?

-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/nodejs
-----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       USE_NPM_INSTALL=true
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=false

-----> Installing binaries
       engines.node (package.json):  unspecified
       engines.npm (package.json):   unspecified (use default)

       Resolving node version 16.x...
       Downloading and installing node 16.14.0...
       Using default npm version: 8.3.1

-----> Restoring cache
       Caching has been disabled because NODE_MODULES_CACHE=false

-----> Installing dependencies
       Installing node modules (package.json + package-lock)
       npm ERR! code ERESOLVE
       npm ERR! ERESOLVE unable to resolve dependency tree
       npm ERR!
       npm ERR! While resolving: shopify-app-node@1.0.0
       npm ERR! Found: react@16.14.0
       npm ERR! node_modules/react
       npm ERR!   react@"^16.10.1" from the root project
       npm ERR!
       npm ERR! Could not resolve dependency:
       npm ERR! peer react@"^17.0.2 || ^18.0.0-0" from next@12.0.10
       npm ERR! node_modules/next
       npm ERR!   next@"^12.0.2" from the root project
       npm ERR!
       npm ERR! Fix the upstream dependency conflict, or retry
       npm ERR! this command with --force, or --legacy-peer-deps
       npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
       npm ERR!
       npm ERR! See /tmp/npmcache.CTfHl/eresolve-report.txt for a full report.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.CTfHl/_logs/2022-02-10T12_18_50_156Z-debug-0.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - Node version not specified in package.json
         https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed

My package.json

{
  "name": "shopify-app-node",
  "version": "1.0.0",
  "description": "Shopify's node app for CLI tool",
  "scripts": {
    "test": "jest",
    "dev": "cross-env NODE_ENV=development nodemon ./server/index.js --watch ./server/index.js",
    "build": "NEXT_TELEMETRY_DISABLED=1 next build",
    "start": "cross-env NODE_ENV=production node ./server/index.js"
  },
  "engines": {
    "node": "16.14.0",
    "npm": "8.4.1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Shopify/shopify-app-node.git"
  },
  "author": "Shopify Inc.",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/shopify/shopify-app-node/issues"
  },
  "dependencies": {
    "@babel/core": "7.12.10",
    "@babel/polyfill": "^7.6.0",
    "@babel/preset-env": "^7.12.11",
    "@babel/register": "^7.12.10",
    "@shopify/app-bridge-react": "^2.0.2",
    "@shopify/app-bridge-utils": "^2.0.2",
    "@shopify/koa-shopify-auth": "^4.1.2",
    "@shopify/polaris": "^6.2.0",
    "apollo-boost": "^0.4.9",
    "axios": "^0.25.0",
    "cross-env": "^7.0.3",
    "dotenv": "^8.2.0",
    "graphql": "^14.5.8",
    "isomorphic-fetch": "^3.0.0",
    "koa": "^2.13.1",
    "koa-bodyparser": "^4.3.0",
    "koa-compress": "^5.1.0",
    "koa-cors": "0.0.16",
    "koa-logger": "^3.2.1",
    "koa-router": "^10.0.0",
    "koa-session": "^6.1.0",
    "mysql2": "^2.3.3",
    "next": "^12.0.2",
    "next-env": "^1.1.0",
    "node-fetch": "^2.6.7",
    "react": "^16.10.1",
    "react-apollo": "^3.1.3",
    "react-dom": "^16.10.1",
    "sequelize": "^6.13.0",
    "slugify": "^1.6.5",
    "validator": "^13.7.0",
    "webpack": "^4.44.1"
  },
  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.12.10",
    "@babel/preset-stage-3": "^7.0.0",
    "babel-jest": "26.6.3",
    "babel-register": "^6.26.0",
    "enzyme": "3.11.0",
    "enzyme-adapter-react-16": "1.15.6",
    "husky": "^4.3.6",
    "jest": "26.6.3",
    "lint-staged": "^10.5.4",
    "nodemon": "^2.0.7",
    "prettier": "2.2.1",
    "react-addons-test-utils": "15.6.2",
    "react-test-renderer": "16.14.0"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,css,json,md}": [
      "prettier --write"
    ]
  }
}


问:
HubSpot API - Search contact by phone
I understand that HubSpot api provides an endpoint to search contact by name or email?

Is there a way to search a contact by phone number with the API?

答:
Below Python code works on my side.
This page looks very useful.

Cheers!

```<code>import hubspot
from pprint import pprint
from hubspot.crm.deals import PublicObjectSearchRequest, ApiException

api_key = "your api key"

test_search_url = f'https://api.hubapi.com/crm/v3/objects/contact/search?hapikey='+api_key
headers = {"Content-Type": "application/json"}

payload = {
        "filterGroups": [
            {
                "filters": [
                    {
                        "propertyName": "phone",
                        "operator": "EQ",
                        "value": "1234567"
                    }
                ]
            }
        ],
        "properties": [
            "firstname", "lastname", "email", "hs_object_id"
        ]
    }

res = requests.post(test_search_url, headers=headers, data=json.dumps(payload))

res.json()

####Output####
# {'total': 1,
#  'results': [{'id': '13701',
#    'properties': {'createdate': '2022-02-10T07:27:18.733Z',
#     'email': 'adi@XXX.com',
#     'firstname': 'XXX K.',
#     'hs_object_id': '13701',
#     'lastmodifieddate': '2022-02-10T07:28:01.033Z',
#     'lastname': None},
#    'createdAt': '2022-02-10T07:27:18.733Z',
#    'updatedAt': '2022-02-10T07:28:01.033Z',
#    'archived': False}]
# }
</code>```

Title: HubSpot API - Search contact by phone

Body:
Below Python code works on my side.
This page looks very useful.

Cheers!

import hubspot
from pprint import pprint
from hubspot.crm.deals import PublicObjectSearchRequest, ApiException

api_key = "your api key"

test_search_url = f'https://api.hubapi.com/crm/v3/objects/contact/search?hapikey='+api_key
headers = {"Content-Type": "application/json"}

payload = {
        "filterGroups": [
            {
                "filters": [
                    {
                        "propertyName": "phone",
                        "operator": "EQ",
                        "value": "1234567"
                    }
                ]
            }
        ],
        "properties": [
            "firstname", "lastname", "email", "hs_object_id"
        ]
    }

res = requests.post(test_search_url, headers=headers, data=json.dumps(payload))

res.json()

####Output####
# {'total': 1,
#  'results': [{'id': '13701',
#    'properties': {'createdate': '2022-02-10T07:27:18.733Z',
#     'email': 'adi@XXX.com',
#     'firstname': 'XXX K.',
#     'hs_object_id': '13701',
#     'lastmodifieddate': '2022-02-10T07:28:01.033Z',
#     'lastname': None},
#    'createdAt': '2022-02-10T07:27:18.733Z',
#    'updatedAt': '2022-02-10T07:28:01.033Z',
#    'archived': False}]
# }


问:
Intent to launch fingerprint enrollment screen
How to launch finger print enrollment settings screen(Add fingerprint screen) from my app?

After enrolling finger print, is there any way to navigate back to my application? (with startActivityForResult)

答:
Suggested answer lack of an important point: if the user need to enroll a  BIOMETRIC_STRONG type of biometry an Extra need to be added to the intent in order to correctly open BiometricEnrollActivity.

If I try to enroll a STRONG biometry with a WEAK biometry already enrolled the startActvity command fails to open the activity.

So the complete snippet used to bring the user to enroll a BIOMETRIC_STRONG is:

```<code>val intent: Intent = when {
  Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
     Intent(Settings.ACTION_BIOMETRIC_ENROLL).putExtra(EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED, BiometricManager.Authenticators.BIOMETRIC_STRONG)
  }
   Build.VERSION.SDK_INT >= Build.VERSION_CODES.P -> {
     Intent(Settings.ACTION_FINGERPRINT_ENROLL)
   }
   else -> {
     Intent(Settings.ACTION_SECURITY_SETTINGS)
   }
}

if(intent.resolveActivity(context!!.packageManager) != null){
   startActivity(intent)
  }else{
   startActivity(Intent(Settings.ACTION_SETTINGS))
}
</code>```

Body:
Suggested answer lack of an important point: if the user need to enroll a  BIOMETRIC_STRONG type of biometry an Extra need to be added to the intent in order to correctly open BiometricEnrollActivity.

If I try to enroll a STRONG biometry with a WEAK biometry already enrolled the startActvity command fails to open the activity.

So the complete snippet used to bring the user to enroll a BIOMETRIC_STRONG is:

val intent: Intent = when {
  Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
     Intent(Settings.ACTION_BIOMETRIC_ENROLL).putExtra(EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED, BiometricManager.Authenticators.BIOMETRIC_STRONG)
  }
   Build.VERSION.SDK_INT >= Build.VERSION_CODES.P -> {
     Intent(Settings.ACTION_FINGERPRINT_ENROLL)
   }
   else -> {
     Intent(Settings.ACTION_SECURITY_SETTINGS)
   }
}

if(intent.resolveActivity(context!!.packageManager) != null){
   startActivity(intent)
  }else{
   startActivity(Intent(Settings.ACTION_SETTINGS))
}


问:
Laravel 8.4 – Remove Public from URL
I am working on creating a website that converts text into speech. I am using the script from codecanyon which is Developed with PHP 7.4.x and Laravel 8.4.x . The issue I am facing is that I don't want to show /public URL as a permalink to access the website. Now, if I type mywebsite.com/pubic then the website is accessible otherwise if I write mywebsite.com then it only shows the files. I followed some of the previous queries posted on StackOverflow but got no results.
The topic I followed is Laravel 5 – Remove Public from URL
I tried even by renaming server.php , copying .htaccess and rewriting it. But those all resulted in a screen showing up errors or even blank.

My .htaccess file is;

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</code>```

答:
To remove the /public from the URL you are not going to use the .htaccess file.

What you are going to do instead is set the /public folder as the serving directory for your Server.

If you use Apache, just go to your /etc/apache2/sites-available/000-default.conf file and change the DocumentRoot from {your base folder}/ (usually /var/www) to {your base folder}/public

Title: Laravel 8.4 – Remove Public from URL

Body:
I am working on creating a website that converts text into speech. I am using the script from codecanyon which is Developed with PHP 7.4.x and Laravel 8.4.x . The issue I am facing is that I don't want to show /public URL as a permalink to access the website. Now, if I type mywebsite.com/pubic then the website is accessible otherwise if I write mywebsite.com then it only shows the files. I followed some of the previous queries posted on StackOverflow but got no results.
The topic I followed is Laravel 5 – Remove Public from URL
I tried even by renaming server.php , copying .htaccess and rewriting it. But those all resulted in a screen showing up errors or even blank.

My .htaccess file is;

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]


问:
parallelizing code with python pathos multiprocessing in docker
I am parallizing code across 30 CPUs and confirmed that outside a container this works fine using the python library 'pathos'.

```<code>pool = ProcessPool(nodes=30)
results = pool.map(func_that_needs_to_run_in_parallel, range(30))
pool.close()
pool.join()

results_df = pd.concat(results)
</code>```

However, it doesn't work while running the code as part of a Flask app in a Docker container. I have three containers:

flask app,

redis which I use to offload all the heavy processing to a worker process,

the worker process.

The code for the worker process can be summarised as:

```<code>#some code that needs to be run on only one cpu
#the above 'ProcessPool' code snippet for one particularly resource-intensive task
#some code that needs to be run on only one cpu
</code>```

When I run the app, the parallelization part of the code in the worker container never uses more than 4 cpus. I confirmed this in docker stats and htop. There are no cpu usage limits on the containers in the docker-compose yaml file.

htop shows that the code runs on only 4 cpus at any one time but it actually randomly switches which cpus its using during the task, thus the worker container can access all 48 cpus.

Summary: Running the app with this multiprocessing code is helpful but there is a ceiling on CPU usage.

答:
Early docker literature (2016) suggested one container per CPU, which is clearly not the case. The idea is to configure this at run time, in the same way you assign memory,

```<code>docker run -it --cpus="30" debian /bin/bash
</code>```

The  docker container resource allocation I found useful, here

If pathos is the issue why not switch to themultiprocessor.Pool() library via  apply, map_async, or imap methods?

Body:
I am parallizing code across 30 CPUs and confirmed that outside a container this works fine using the python library 'pathos'.

pool = ProcessPool(nodes=30)
results = pool.map(func_that_needs_to_run_in_parallel, range(30))
pool.close()
pool.join()

results_df = pd.concat(results)

However, it doesn't work while running the code as part of a Flask app in a Docker container. I have three containers:

flask app,

redis which I use to offload all the heavy processing to a worker process,

the worker process.

The code for the worker process can be summarised as:

#some code that needs to be run on only one cpu
#the above 'ProcessPool' code snippet for one particularly resource-intensive task
#some code that needs to be run on only one cpu

When I run the app, the parallelization part of the code in the worker container never uses more than 4 cpus. I confirmed this in docker stats and htop. There are no cpu usage limits on the containers in the docker-compose yaml file.

htop shows that the code runs on only 4 cpus at any one time but it actually randomly switches which cpus its using during the task, thus the worker container can access all 48 cpus.

Summary: Running the app with this multiprocessing code is helpful but there is a ceiling on CPU usage.

Body:
Early docker literature (2016) suggested one container per CPU, which is clearly not the case. The idea is to configure this at run time, in the same way you assign memory,

docker run -it --cpus="30" debian /bin/bash

The  docker container resource allocation I found useful, here

If pathos is the issue why not switch to themultiprocessor.Pool() library via  apply, map_async, or imap methods?


问:
scikit-learn error: The least populated class in y has only 1 member
I'm trying to split my dataset into a training and a test set by using the train_test_split function from scikit-learn, but I'm getting this error:

```<code>In [1]: y.iloc[:,0].value_counts()
Out[1]:
M2    38
M1    35
M4    29
M5    15
M0    15
M3    15

In [2]: xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=1/3, random_state=85, stratify=y)
Out[2]:
Traceback (most recent call last):
  File "run_ok.py", line 48, in <module>
    xtrain,xtest,ytrain,ytest = train_test_split(X,y,test_size=1/3,random_state=85,stratify=y)
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1700, in train_test_split
    train, test = next(cv.split(X=arrays[0], y=stratify))
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 953, in split
    for train, test in self._iter_indices(X, y, groups):
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1259, in _iter_indices
    raise ValueError("The least populated class in y has only 1"
ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2.
</code>```

However, all classes have at least 15 samples. Why am I getting this error?

X is a pandas DataFrame which represents the data points, y is a pandas DataFrame with one column that contains the target variable.

I cannot post the original data because it's proprietary, but it is fairly reproducible by creating a random pandas DataFrame (X) with 1k rows x 500 columns, and a random pandas DataFrame (y) with the same number of rows (1k) of X, and, for each row the target variable (a categorical label).
The y pandas DataFrame should have different categorical labels (e.g. 'class1', 'class2'...) and each labels should have at least 15 occurrences.

答:
```<code>from sklearn.model_selection import train_test_split

all_keys = df['Key'].unique().tolist()

t_df = pd.DataFrame()
c_df = pd.DataFrame()

for key in all_keys:
    print(key)
    if df.loc[df['Key']==key].shape[0] < 2 :
        t_df = t_df.append(df.loc[df['Key']==key])
    else:
        df_t, df_c = train_test_split(df.loc[df['Key']==key],test_size=0.2,stratify=df.loc[df['Key']==key]['Key'])
        t_df = t_df.append(df_t)
        c_df = c_df.append(df_c)
</code>```

Body:
I'm trying to split my dataset into a training and a test set by using the train_test_split function from scikit-learn, but I'm getting this error:

In [1]: y.iloc[:,0].value_counts()
Out[1]:
M2    38
M1    35
M4    29
M5    15
M0    15
M3    15

In [2]: xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=1/3, random_state=85, stratify=y)
Out[2]:
Traceback (most recent call last):
  File "run_ok.py", line 48, in <module>
    xtrain,xtest,ytrain,ytest = train_test_split(X,y,test_size=1/3,random_state=85,stratify=y)
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1700, in train_test_split
    train, test = next(cv.split(X=arrays[0], y=stratify))
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 953, in split
    for train, test in self._iter_indices(X, y, groups):
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1259, in _iter_indices
    raise ValueError("The least populated class in y has only 1"
ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2.

However, all classes have at least 15 samples. Why am I getting this error?

X is a pandas DataFrame which represents the data points, y is a pandas DataFrame with one column that contains the target variable.

I cannot post the original data because it's proprietary, but it is fairly reproducible by creating a random pandas DataFrame (X) with 1k rows x 500 columns, and a random pandas DataFrame (y) with the same number of rows (1k) of X, and, for each row the target variable (a categorical label).
The y pandas DataFrame should have different categorical labels (e.g. 'class1', 'class2'...) and each labels should have at least 15 occurrences.


问:
What is the best practice to make an object in JS like this: T('isArray')([]) == T.run('isArray')([]) == T().run('isArray')?
What is the best practice to make an object in JavaScript like this, knowing T is the main object:

```<code>  T('isArray')([])
  T.run('isArray')([])
  T().run('isArray')([])

  T('isArray', [])
  T.run('isArray', [])
  T().run('isArray', [])
</code>```

They all must use the same function.

答:
Since the main object can be called it must be a function. The function should decide what to return based on the arguments:</p>

```<code>var T = (function() {

    var functions = { // define functions that can be run like isArray
        isArray: function(a) {
            return Array.isArray(a);
        },

        log: function(a, b) {
            console.log(a + b);
        }
    };

    var noop = function() {}; // function doing nothing (no operation)

    var T = function(f) {
        if(arguments.length >= 2) { // function + args provided
            return (functions[f] || noop) // call it
                    .apply(this, [].slice.call(arguments, 1));
        } else if(arguments.length === 1) { // only function provided
            return function() { // return function that can be called with args
                return (functions[f] || noop)
                        .apply(this, arguments);
            }
        } else { // nothing provided, return T itself (so that e.g. T.run === T().run)
            return T;
        }
    }

    T.run = function() { // run function
        return T.apply(this, arguments);
    };

    T.getState = function() { // another function
        console.log("Not implemented");
    };

    return T; // actually return T so that it gets stored in 'var T'
})();

// tests

console.log(
    T('isArray')([]),
    T.run('isArray')([]),
    T().run('isArray')([]),

    T('isArray', []),
    T.run('isArray', []),
    T().run('isArray', [])
);

T('log')(1, 2);
T.getState();
</code>```

Body:
What is the best practice to make an object in JavaScript like this, knowing T is the main object:

  T('isArray')([])
  T.run('isArray')([])
  T().run('isArray')([])

  T('isArray', [])
  T.run('isArray', [])
  T().run('isArray', [])

They all must use the same function.

Body:
Since the main object can be called it must be a function. The function should decide what to return based on the arguments:

var T = (function() {

    var functions = { // define functions that can be run like isArray
        isArray: function(a) {
            return Array.isArray(a);
        },

        log: function(a, b) {
            console.log(a + b);
        }
    };

    var noop = function() {}; // function doing nothing (no operation)

    var T = function(f) {
        if(arguments.length >= 2) { // function + args provided
            return (functions[f] || noop) // call it
                    .apply(this, [].slice.call(arguments, 1));
        } else if(arguments.length === 1) { // only function provided
            return function() { // return function that can be called with args
                return (functions[f] || noop)
                        .apply(this, arguments);
            }
        } else { // nothing provided, return T itself (so that e.g. T.run === T().run)
            return T;
        }
    }

    T.run = function() { // run function
        return T.apply(this, arguments);
    };

    T.getState = function() { // another function
        console.log("Not implemented");
    };

    return T; // actually return T so that it gets stored in 'var T'
})();

// tests

console.log(
    T('isArray')([]),
    T.run('isArray')([]),
    T().run('isArray')([]),

    T('isArray', []),
    T.run('isArray', []),
    T().run('isArray', [])
);

T('log')(1, 2);
T.getState();


问:
Android FragmentStatePagerAdapter, how to tag a fragment to find it later
When using the FragmentStatePageAdapter I get the fragments like this:

```<code>    @Override
    public Fragment getItem(int position) {
        return new SuperCoolFragment();
    }
</code>```

However, later on my code I need to find this fragment to set a property. In some other parts of the app where I use fragments I basically tag them and look for them using findFragmentByTag(TAG) but with now I don't know how to do it.

How do can I find the fragments using the FragmentStatePageAdapter?

答:
While using FragmentStateAdapter setting up custom tag and looking for it is pretty simple. This is how FragmentStateAdapter tags its fragments:

```<code>mFragmentManager.beginTransaction()
    .add(fragment, "f" + holder.getItemId())
    .setMaxLifecycle(fragment, STARTED)
    .commitNow();
</code>```

As you can see it's a combination of static string "f" and getItemId().
After overriding fun getItemId(position: Int): Long in your adapter, finding a specific fragment should be straightforward to do. For example

```<code>override fun getItemId(position: Int): Long {
    return if(position == 0) {
            200001
    }else 200002
}
</code>```

The tag for our first fragment would be "fmy_first_fragment" and found with childFragmentManager.findFragmentByTag("fmy_first_fragment") as? MyFirstFragment

Careful whenever you look for fragment, you have to use the same FragmentManager as was used to create it. So I recommend creating your adapter with FragmentManager and LifeCycle as a constructor.

Body:
When using the FragmentStatePageAdapter I get the fragments like this:

    @Override
    public Fragment getItem(int position) {
        return new SuperCoolFragment();
    }

However, later on my code I need to find this fragment to set a property. In some other parts of the app where I use fragments I basically tag them and look for them using findFragmentByTag(TAG) but with now I don't know how to do it.

How do can I find the fragments using the FragmentStatePageAdapter?

Body:
While using FragmentStateAdapter setting up custom tag and looking for it is pretty simple. This is how FragmentStateAdapter tags its fragments:

mFragmentManager.beginTransaction()
    .add(fragment, "f" + holder.getItemId())
    .setMaxLifecycle(fragment, STARTED)
    .commitNow();

As you can see it's a combination of static string "f" and getItemId().
After overriding fun getItemId(position: Int): Long in your adapter, finding a specific fragment should be straightforward to do. For example

override fun getItemId(position: Int): Long {
    return if(position == 0) {
            200001
    }else 200002
}

The tag for our first fragment would be "fmy_first_fragment" and found with childFragmentManager.findFragmentByTag("fmy_first_fragment") as? MyFirstFragment

Careful whenever you look for fragment, you have to use the same FragmentManager as was used to create it. So I recommend creating your adapter with FragmentManager and LifeCycle as a constructor.


问:
Can't intialize a char array with a string variable, only with explicit assignment using "something like this"
My code is

```<code>void function(string line) {
   char str[line.length()] = line;
   const char s[2] = " ";
   char *token;

  token = strtok(str,s);
  while (token != NULL) {
      printf( " %s\n",token);
      token = strtok(NULL,s);
  }
}

int main() {
  function("Slovakia 5 #948384");
  return 0;
}
</code>```

Which does not compile unless I assign str explicitly like this:

char str[line.length()] = "Slovakia 5 #948384";

However, that defeats the purpose of having a variable string passed as a parameter to the function. How can I fix this?

答:
The simple answer is a shrug and "that's the way it is".

char arrays are rather primitive; they hold a sequence of char values, and there are a bunch of functions in the standard library that treat them like strings. But they're not like C++ std::string. They're just arrays.

```<code>int x[4] = { 1, 2, 3, 4 };
int y[4] = x; // illegal, arrays aren't automatically copied
</code>```

Same thing for an array of char:

```<code>char x1[4] = { 'a' , 'b', 'c', '\0' };
char y1[4] = x1; // illegal, arrays aren't automatically copied
</code>```

The typical copy operation on an array of char assumes that the sequence of characters is terminated by a nul character, and strcpy looks for that:

```<code>char y1[4];
strcpy(y1, x1); // okay; copies the contents of x1 into y1
</code>```

And there's a special rule for arrays that are initialized by a string literal:

```<code>char y2[4] = "abc"; // okay, copies string literal into y2, including nul terminator
</code>```

The red herring in the question is the combination of a variable length array with an attempted initialization from another array. Variable length arrays are not part of C++, so char str[line.length()] isn't legal. C allows runtime determination of array sizes, and some compilers allow this as an extension in C++.

Body:
My code is

void function(string line) {
   char str[line.length()] = line;
   const char s[2] = " ";
   char *token;

  token = strtok(str,s);
  while (token != NULL) {
      printf( " %s\n",token);
      token = strtok(NULL,s);
  }
}

int main() {
  function("Slovakia 5 #948384");
  return 0;
}

Which does not compile unless I assign str explicitly like this:

char str[line.length()] = "Slovakia 5 #948384";

However, that defeats the purpose of having a variable string passed as a parameter to the function. How can I fix this?

Body:
The simple answer is a shrug and "that's the way it is".

char arrays are rather primitive; they hold a sequence of char values, and there are a bunch of functions in the standard library that treat them like strings. But they're not like C++ std::string. They're just arrays.

int x[4] = { 1, 2, 3, 4 };
int y[4] = x; // illegal, arrays aren't automatically copied

Same thing for an array of char:

char x1[4] = { 'a' , 'b', 'c', '\0' };
char y1[4] = x1; // illegal, arrays aren't automatically copied

The typical copy operation on an array of char assumes that the sequence of characters is terminated by a nul character, and strcpy looks for that:

char y1[4];
strcpy(y1, x1); // okay; copies the contents of x1 into y1

And there's a special rule for arrays that are initialized by a string literal:

char y2[4] = "abc"; // okay, copies string literal into y2, including nul terminator

The red herring in the question is the combination of a variable length array with an attempted initialization from another array. Variable length arrays are not part of C++, so char str[line.length()] isn't legal. C allows runtime determination of array sizes, and some compilers allow this as an extension in C++.


问:
how to finish reverting a commit, and how to revert a lot of commits
This has to be simple, but I can't find it in git-scm.

I've been making a lot of small commits to a public project, and all of my work is bad. I want to remove everything that I've done. Some I've just committed locally, some I've pushed to 'origin master'.

The first commit (a week ago) is bdbad86... with the most recent being e82401b...

I want to just make all these go away. I've tried to revert one.

```<code>git status
# On branch master
# You are currently reverting commit e82401b.
#   (all conflicts fixed: run "git revert --continue")
#   (use "git revert --abort" to cancel the revert operation)
</code>```

I can't figure out how to finish this reverting.

I don't want to have to do each commit separately, I want to blow them all away.

答:
This question is already answered correctly, but I just want to address the first point of op's question -- I can't figure out how to finish this reverting. if you too were stuck in revert state like me and got here searching for an answer.

it can be straightforward as git revert --continue. but only if you're reverting some changes inside a file. if you get stuck in revert state, that's most likely because you're trying to revert a commit that created a file and that file is modified in any of the subsequent commit.

take an example:

```<code>1c40cd3 added fileB
4e06828 added fileA
faf29dd (origin/main, origin/HEAD, main) Merged in feature5 (pull request #13)
6e735e3 (origin/feature5, feature5) updated file.txt
fb51fca added file.txt
744ba74 Initial commit
</code>```

now, if you're trying to revert fb51fca (added file.txt), it will show you something like:

```<code>$ git revert fb51fca
CONFLICT (modify/delete): file.txt deleted in parent of fb51fca (added file.txt) and modified in HEAD.  Version HEAD of file.txt left in tree.
error: could not revert fb51fca... added file.txt
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git revert --continue".
hint: You can instead skip this commit with "git revert --skip".
hint: To abort and get back to the state before "git revert",
hint: run "git revert --abort".

$ git status
On branch feature6
You are currently reverting commit fb51fca.
  (fix conflicts and run "git revert --continue")
  (use "git revert --skip" to skip this patch)
  (use "git revert --abort" to cancel the revert operation)

Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add/rm <file>..." as appropriate to mark resolution)
        deleted by them: file.txt
</code>```

you can clearly see file.txt deleted in fb51fca (added file.txt) and modified in HEAD.  Version HEAD of file.txt left in tree.. now, you can do git add -A and git commit ... BUT

what revert does is goes back in history (in the specified commit), removes the changes that were done in that commit. and makes a new commit. but the issue is, you created a file, now revert is deleting it. in the end, there is no file left to stage and as you know, git doesn't allow empty directories or empty commits.

but there's a workaround for empty commits. as ryan suggested, you can do git commit -m "empty commit to escape revert" --allow-empty. git revert probably doesn't use this --allow-empty flag and that's probably the reason it can't do a commit gets stuck in revert state.

either way, if you get stuck in the revert state, you're probably doing something wrong. trying to revert something that doesn't make sense.

Body:
This has to be simple, but I can't find it in git-scm.

I've been making a lot of small commits to a public project, and all of my work is bad. I want to remove everything that I've done. Some I've just committed locally, some I've pushed to 'origin master'.

The first commit (a week ago) is bdbad86... with the most recent being e82401b...

I want to just make all these go away. I've tried to revert one.

git status
# On branch master
# You are currently reverting commit e82401b.
#   (all conflicts fixed: run "git revert --continue")
#   (use "git revert --abort" to cancel the revert operation)

I can't figure out how to finish this reverting.

I don't want to have to do each commit separately, I want to blow them all away.

Body:
This question is already answered correctly, but I just want to address the first point of op's question -- I can't figure out how to finish this reverting. if you too were stuck in revert state like me and got here searching for an answer.

it can be straightforward as git revert --continue. but only if you're reverting some changes inside a file. if you get stuck in revert state, that's most likely because you're trying to revert a commit that created a file and that file is modified in any of the subsequent commit.

take an example:

1c40cd3 added fileB
4e06828 added fileA
faf29dd (origin/main, origin/HEAD, main) Merged in feature5 (pull request #13)
6e735e3 (origin/feature5, feature5) updated file.txt
fb51fca added file.txt
744ba74 Initial commit

now, if you're trying to revert fb51fca (added file.txt), it will show you something like:

$ git revert fb51fca
CONFLICT (modify/delete): file.txt deleted in parent of fb51fca (added file.txt) and modified in HEAD.  Version HEAD of file.txt left in tree.
error: could not revert fb51fca... added file.txt
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git revert --continue".
hint: You can instead skip this commit with "git revert --skip".
hint: To abort and get back to the state before "git revert",
hint: run "git revert --abort".

$ git status
On branch feature6
You are currently reverting commit fb51fca.
  (fix conflicts and run "git revert --continue")
  (use "git revert --skip" to skip this patch)
  (use "git revert --abort" to cancel the revert operation)

Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add/rm <file>..." as appropriate to mark resolution)
        deleted by them: file.txt

you can clearly see file.txt deleted in fb51fca (added file.txt) and modified in HEAD.  Version HEAD of file.txt left in tree.. now, you can do git add -A and git commit ... BUT

what revert does is goes back in history (in the specified commit), removes the changes that were done in that commit. and makes a new commit. but the issue is, you created a file, now revert is deleting it. in the end, there is no file left to stage and as you know, git doesn't allow empty directories or empty commits.

but there's a workaround for empty commits. as ryan suggested, you can do git commit -m "empty commit to escape revert" --allow-empty. git revert probably doesn't use this --allow-empty flag and that's probably the reason it can't do a commit gets stuck in revert state.

either way, if you get stuck in the revert state, you're probably doing something wrong. trying to revert something that doesn't make sense.


问:
WARN: Unable to load JNA library (OS: Mac OS X 12.2) warning when running flutter app on release mode. (M1 Mac)
I  built a simple tic-tac-toe app on Flutter. It works in debug mode without any problem, but when I run it in release mode it gives me an error:

```<code>WARN: Unable to load JNA library (OS: Mac OS X 12.2)
java.lang.UnsatisfiedLinkError: /Users/rza/Library/Caches/JNA/temp/jna10193542212619812140.tmp: dlopen(/Users/rza/Library/Caches/JNA/temp/jna10193542212619812140.tmp, 0x0001): tried: '/Users/rza/Library/Caches/JNA/temp/jna10193542212619812140.tmp' (fat file, but missing compatible architecture (have 'i386,x86_64', need 'arm64e')), '/usr/lib/jna10193542212619812140.tmp' (no such file)
</code>```

I'm running the app in release mode in a virtual Android machine.

I am assuming it is about CPU architecture. How can I fix this?

答:
Just had this error as well. This happens with flutter 2.10.1 on a mac with M1.

I got rid of it by doing a

```<code>$ flutter clean
</code>```

in my project directory.

Body:
I  built a simple tic-tac-toe app on Flutter. It works in debug mode without any problem, but when I run it in release mode it gives me an error:

WARN: Unable to load JNA library (OS: Mac OS X 12.2)
java.lang.UnsatisfiedLinkError: /Users/rza/Library/Caches/JNA/temp/jna10193542212619812140.tmp: dlopen(/Users/rza/Library/Caches/JNA/temp/jna10193542212619812140.tmp, 0x0001): tried: '/Users/rza/Library/Caches/JNA/temp/jna10193542212619812140.tmp' (fat file, but missing compatible architecture (have 'i386,x86_64', need 'arm64e')), '/usr/lib/jna10193542212619812140.tmp' (no such file)

I'm running the app in release mode in a virtual Android machine.

I am assuming it is about CPU architecture. How can I fix this?

Body:
Just had this error as well. This happens with flutter 2.10.1 on a mac with M1.

I got rid of it by doing a

$ flutter clean

in my project directory.


问:
im getting the `get youtuble app` dialog even if i have the leastest youtube app installed on my physical divice
im very new to youtube api when i test the app on my mobile phone a get youtube app  dialog is showing even that i have the leastest vertion of the youtube app installed on my divice . i dont know where the error could be or what i did wrong .

```<code>
import android.os.Build
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import com.google.android.youtube.player.YouTubeBaseActivity
import com.google.android.youtube.player.YouTubeInitializationResult
import com.google.android.youtube.player.YouTubePlayer
import com.google.android.youtube.player.YouTubePlayerView
const val KEY_VID_ID  = "dQw4w9WgXcQ"
const val KEY_LIST_ID  = "PLkNqPjK6mmFYDGUceKt73TmoM7srNpDlm"
class youtubePlayer : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener {
   @RequiresApi(Build.VERSION_CODES.M)
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       val layout = layoutInflater.inflate(R.layout.activity_youtube_player,
           null,
           false) as ConstraintLayout
       setContentView(layout)
       val ytbView = YouTubePlayerView(this)
       ytbView.layoutParams = ConstraintLayout.LayoutParams(
           ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
       layout.addView(ytbView)
       ytbView.initialize(getString(R.string.KEY_API_ID ), this)
   }

   override fun onInitializationSuccess(
       provider: YouTubePlayer.Provider?,
       youtubePlayer: YouTubePlayer?,
       wasRestored: Boolean,
   ) {
       if(!wasRestored){
           youtubePlayer?.cueVideo(KEY_VID_ID)
       }
   }

   override fun onInitializationFailure(
       provider: YouTubePlayer.Provider?,
       errorType: YouTubeInitializationResult?,
   ) {
       if(errorType!!.isUserRecoverableError()){
           errorType.getErrorDialog(this , 0).show()
       }else{
           Toast.makeText(this, "an error accured ${errorType}", Toast.LENGTH_LONG).show()
       }
   }
}
'''
</code>```

答:
if you are using android 11 and  apov you should add this  code t o thye manefest</p>
```<code>       <intent>
           <action android:name="com.google.android.youtube.api.service.START" />
       </intent>
   </queries>```
</code>```

Body:
im very new to youtube api when i test the app on my mobile phone a get youtube app  dialog is showing even that i have the leastest vertion of the youtube app installed on my divice . i dont know where the error could be or what i did wrong .

import android.os.Build
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import com.google.android.youtube.player.YouTubeBaseActivity
import com.google.android.youtube.player.YouTubeInitializationResult
import com.google.android.youtube.player.YouTubePlayer
import com.google.android.youtube.player.YouTubePlayerView
const val KEY_VID_ID  = "dQw4w9WgXcQ"
const val KEY_LIST_ID  = "PLkNqPjK6mmFYDGUceKt73TmoM7srNpDlm"
class youtubePlayer : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener {
   @RequiresApi(Build.VERSION_CODES.M)
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       val layout = layoutInflater.inflate(R.layout.activity_youtube_player,
           null,
           false) as ConstraintLayout
       setContentView(layout)
       val ytbView = YouTubePlayerView(this)
       ytbView.layoutParams = ConstraintLayout.LayoutParams(
           ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
       layout.addView(ytbView)
       ytbView.initialize(getString(R.string.KEY_API_ID ), this)
   }

   override fun onInitializationSuccess(
       provider: YouTubePlayer.Provider?,
       youtubePlayer: YouTubePlayer?,
       wasRestored: Boolean,
   ) {
       if(!wasRestored){
           youtubePlayer?.cueVideo(KEY_VID_ID)
       }
   }

   override fun onInitializationFailure(
       provider: YouTubePlayer.Provider?,
       errorType: YouTubeInitializationResult?,
   ) {
       if(errorType!!.isUserRecoverableError()){
           errorType.getErrorDialog(this , 0).show()
       }else{
           Toast.makeText(this, "an error accured ${errorType}", Toast.LENGTH_LONG).show()
       }
   }
}
'''

Body:
if you are using android 11 and  apov you should add this  code t o thye manefest

       <intent>
           <action android:name="com.google.android.youtube.api.service.START" />
       </intent>
   </queries>```


问:
Wordpress 5.9 and wp_lazy_loading_enabled filter issue on images
since WP 5.5, I had to add this function to my theme to prevent rendering issues in an image slider due to automatic lazy loading in WP:

    add_filter( 'wp_lazy_loading_enabled', '__return_false' );
```

This was working quite well since it was removing the automatic parameter "loading=lazy" on images elements.

Yesterday, after upgrading to WP 5.9, I'm facing the same issue again with my slider and I see that the "loading=lazy" parameter is back on all images!

How can I fix that? Thanks

答:
You can try one of these two solutions:

```<code>$attr['loading'] = false;
return wp_get_attachment_image( $attachment_id, $size, $icon, $attr );
</code>```

Or:

```<code>add_filter( 'wp_get_attachment_image_attributes', function( $attr, $attachment, $size ) {
    if ( $attachment->post_mime_type === 'image/svg+xml' ) {
        unset( $attr['loading'] );
    }
    return $attr;
} );
</code>```

Answer is from here: https://developer.wordpress.org/reference/functions/wp_lazy_loading_enabled/#comment-4226

Body:
since WP 5.5, I had to add this function to my theme to prevent rendering issues in an image slider due to automatic lazy loading in WP:

    add_filter( 'wp_lazy_loading_enabled', '__return_false' );

This was working quite well since it was removing the automatic parameter "loading=lazy" on images elements.

Yesterday, after upgrading to WP 5.9, I'm facing the same issue again with my slider and I see that the "loading=lazy" parameter is back on all images!

How can I fix that? Thanks

Body:
You can try one of these two solutions:

$attr['loading'] = false;
return wp_get_attachment_image( $attachment_id, $size, $icon, $attr );

Or:

add_filter( 'wp_get_attachment_image_attributes', function( $attr, $attachment, $size ) {
    if ( $attachment->post_mime_type === 'image/svg+xml' ) {
        unset( $attr['loading'] );
    }
    return $attr;
} );

Answer is from here: https://developer.wordpress.org/reference/functions/wp_lazy_loading_enabled/#comment-4226


问:
How ro access docker volume files from the code on docker container
i have creted a docker volume with such command

```<code>docker run -ti --rm -v TestVolume1:/testvolume1 ubuntu
</code>```

then i created a file there, called TestFile.txt and added text to it

Also i have a simple "Hello world" .net core app with Dockerfile

```<code>FROM mcr.microsoft.com/dotnet/aspnet:6.0
COPY bin/Release/net6.0/publish/ ShareFileTestInstance1/
WORKDIR /ShareFileTestInstance1
ENTRYPOINT ["dotnet", "ShareFileTestInstance1.dll"]
</code>```

I published it using

```<code>dotnet publish -c Release
</code>```

then ran

```<code>docker build -t counter-image -f Dockerfile .
</code>```

And finally executed

```<code>docker run -it --rm --name=counter-container counter-image -v TestVolume1:/testvolume1 ubuntu
</code>```

to run my app with a docker volume

So what i want to achive to access a file which is in a volume("TestFile.txt" in my case) from a code in the container.

for example

```<code>Console.WriteLine(File.Exists("WHAT FILE PATH HAS TO BE HERE") ? "File exists." : "File does not exist.");
</code>```

Is it also possible to combine all this stuff in a Dockerfile? I want to add one more container next and connect to the volume to save data there.

答:
The parameters for docker run can be either for docker or for the program running in the docker container. Parameters for docker go before the image name and parameters for the program in the container go after the image name.

The volume mapping is a parameter for docker, so it should go before the image name. So instead of

```<code>docker run -it --rm --name=counter-container counter-image -v TestVolume1:/testvolume1 ubuntu
</code>```

you should do

```<code>docker run -it --rm --name=counter-container -v TestVolume1:/testvolume1 counter-image
</code>```

When you do that, your file should be accessible for your program at /testvolume1/TestFile.txt.

It's not possible to do the mapping in the Dockerfile as you ask. Mappings may vary from docker host to docker host, so they need to be specified at run-time.

Body:
i have creted a docker volume with such command

docker run -ti --rm -v TestVolume1:/testvolume1 ubuntu

then i created a file there, called TestFile.txt and added text to it

Also i have a simple "Hello world" .net core app with Dockerfile

FROM mcr.microsoft.com/dotnet/aspnet:6.0
COPY bin/Release/net6.0/publish/ ShareFileTestInstance1/
WORKDIR /ShareFileTestInstance1
ENTRYPOINT ["dotnet", "ShareFileTestInstance1.dll"]

I published it using

dotnet publish -c Release

then ran

docker build -t counter-image -f Dockerfile .

And finally executed

docker run -it --rm --name=counter-container counter-image -v TestVolume1:/testvolume1 ubuntu

to run my app with a docker volume

So what i want to achive to access a file which is in a volume("TestFile.txt" in my case) from a code in the container.

for example

Console.WriteLine(File.Exists("WHAT FILE PATH HAS TO BE HERE") ? "File exists." : "File does not exist.");

Is it also possible to combine all this stuff in a Dockerfile? I want to add one more container next and connect to the volume to save data there.

Body:
The parameters for docker run can be either for docker or for the program running in the docker container. Parameters for docker go before the image name and parameters for the program in the container go after the image name.

The volume mapping is a parameter for docker, so it should go before the image name. So instead of

docker run -it --rm --name=counter-container counter-image -v TestVolume1:/testvolume1 ubuntu

you should do

docker run -it --rm --name=counter-container -v TestVolume1:/testvolume1 counter-image

When you do that, your file should be accessible for your program at /testvolume1/TestFile.txt.

It's not possible to do the mapping in the Dockerfile as you ask. Mappings may vary from docker host to docker host, so they need to be specified at run-time.