问:
Traefik 2 letsencrypt. Add new domain in a smart way
What could be the best way to issue missing letsencrypt certificates automatically?

I have a Traefik 2.9 proxy that works for multiple docker containers for multiple domain names.
Acme http challenge is set up for all my domains.

I want to add a new domain to work with letsencrypt:

s3.mydomain.com

How to solve this in a smart way?

What i do now is:

```<code>rm acme.json
docker compose -f docker/docker-compose-prod.yml -p traefik up --build --force-recreate -d --remove-orphans
chmod 777 acme.json
</code>```

I think this is not smart.

Do I rly need to delete acme.json?
Do I rly need to restart traefik?

I would expect traefik would hendle everything automatically somehow.

Is there a more smart/clever way?

My traefik config:

```<code>entryPoints:
  web:
    address: ":80"
  websecure:
    address: ":443"
providers:
  docker:
    endpoint: "unix:///var/run/docker.sock"
    exposedByDefault: false
    watch: true
certificatesResolvers:
  myresolver:
    acme:
      email: myemail@gmail.com
      storage: acme.json
      caServer: "https://acme-v02.api.letsencrypt.org/directory"
      httpChallenge:
        entryPoint: web
</code>```

Traefik labels for one of my containers. (it is similar for all other containers)

```<code>    labels:
      - traefik.enable=true
      - traefik.docker.network=traefik_proxy
      - traefik.http.routers.api-community.entrypoints=web
      - traefik.http.routers.api-community.rule=Host(`${API_PUBLIC_URL}`, `${ADMIN_PUBLIC_URL}`)
      - traefik.http.routers.api-community.middlewares=api-community-https-redirect
      - traefik.http.routers.api-community-secure.entrypoints=websecure
      - traefik.http.routers.api-community-secure.rule=Host(`${API_PUBLIC_URL}`, `${ADMIN_PUBLIC_URL}`)
      - traefik.http.routers.api-community-secure.tls=true
      - traefik.http.routers.api-community-secure.tls.certresolver=myresolver
      - traefik.http.routers.api-community-secure.service=php-nginx-community
      - traefik.http.middlewares.api-community-https-redirect.redirectscheme.scheme=https
</code>```

Body:
What could be the best way to issue missing letsencrypt certificates automatically?

I have a Traefik 2.9 proxy that works for multiple docker containers for multiple domain names.
Acme http challenge is set up for all my domains.

I want to add a new domain to work with letsencrypt:

s3.mydomain.com

How to solve this in a smart way?

What i do now is:

rm acme.json
docker compose -f docker/docker-compose-prod.yml -p traefik up --build --force-recreate -d --remove-orphans
chmod 777 acme.json

I think this is not smart.

Do I rly need to delete acme.json?
Do I rly need to restart traefik?

I would expect traefik would hendle everything automatically somehow.

Is there a more smart/clever way?

My traefik config:

entryPoints:
  web:
    address: ":80"
  websecure:
    address: ":443"
providers:
  docker:
    endpoint: "unix:///var/run/docker.sock"
    exposedByDefault: false
    watch: true
certificatesResolvers:
  myresolver:
    acme:
      email: myemail@gmail.com
      storage: acme.json
      caServer: "https://acme-v02.api.letsencrypt.org/directory"
      httpChallenge:
        entryPoint: web

Traefik labels for one of my containers. (it is similar for all other containers)

    labels:
      - traefik.enable=true
      - traefik.docker.network=traefik_proxy
      - traefik.http.routers.api-community.entrypoints=web
      - traefik.http.routers.api-community.rule=Host(`${API_PUBLIC_URL}`, `${ADMIN_PUBLIC_URL}`)
      - traefik.http.routers.api-community.middlewares=api-community-https-redirect
      - traefik.http.routers.api-community-secure.entrypoints=websecure
      - traefik.http.routers.api-community-secure.rule=Host(`${API_PUBLIC_URL}`, `${ADMIN_PUBLIC_URL}`)
      - traefik.http.routers.api-community-secure.tls=true
      - traefik.http.routers.api-community-secure.tls.certresolver=myresolver
      - traefik.http.routers.api-community-secure.service=php-nginx-community
      - traefik.http.middlewares.api-community-https-redirect.redirectscheme.scheme=https


来源: stackexchange

问:
Getting java.net.unknownHostException: when trying to access a service with help of feign and the service is having https protocol
As i am new java developer i am facing the problem and the problem is like this i have a servise which is running on https:\localhost:8080\endpoints

now i am using eureka and making this servise eureka clint and storing this servise with a name suppose xyz now the end point looks like https:\xyz\endpoints\ now i am using feign clint from a servise running on port 9090 and if call the end point i.e.https:\xyz\endpoints\ from a servise running in port 9090 i am getting java.net.UnknownHostException:xyz but if i pass like https:\localhost:8080\endpoints\ i am getting the servise what should i do but http methods can be accessed i.e. http:\localhost:8080\endpoints\  but not https i.e.https:\localhost:8080\endpoints\

this how i am declaring feign

@FeignClient(name = "xyz" ,path="/api/3.0/users/", configuration = FeignConfig.class)
@LoadBalancerClient(name = "xyz",configuration=LoadBalancerConfiguration.class)

this is my configuration for feign to access a end point running onhttps
@Configuration
public class FeignConfig {

    @Value("${my.keystore.path}")
    private String keystorePath;
    @Value("${server.ssl.key-store-type}")
    private String keystoreType;
    @Value("${trust.store.password}")
    private String keystorePassword;

        @Bean
    public Client feignClient() {
        Client trustSSLSockets = new Client.Default(getSSLSocketFactory(), new     NoopHostnameVerifier());
        return trustSSLSockets;
    }
private SSLSocketFactory getSSLSocketFactory() {

        SSLContext sslContext = null;
        try {
            sslContext = SSLContextBuilder.create().setKeyStoreType(keystoreType).loadTrustMaterial(
                    ResourceUtils.getFile("classpath:AppsDeveloperBlog.p12"), keystorePassword.toCharArray()).build();
        } catch (Exception e) {
        }
        return sslContext.getSocketFactory();
    }
}
```

ContentLicense: CC BY-SA 4.0


问:
Device or resource busy when deleting a mounted file
I'm trying to delete a file from a Kubernetes pod but I'm getting this error Device or resource busy and I have a volume mount for this file</p>


问:
Register Angular providers dynamically during runtime
Is there a way to register module/component providers in a dynamic way? I know about the useFactory option but this is only about a specific provider.
What I want to achieve is to register some providers during runtime, via a service instance.

Take the following code for example, where the BarService instance has a property that contains multiple providers, this service is provided in module level and then a contained component provides all these services in order to be accessible in the DI.

```<code>@Injectable()
export class BarService {
  public readonly manyProviders: Provider[] = [Service1, Service2, Service3];
}

@NgModule({
  providers: [BarService],
  ...
})

@Component({
   selector: 'foo-component',
   templateUrl: './foo.component.html',
   providers: [...barServiceInstance.manyProviders]
})
export class FooComponent {
  public constructor(private service1: Service1) {
   ...
  }
}
</code>```

I've tried to use the useFactory approach, but the services are not resolved (which makes sense I guess...):

```<code>export function barServiceProviderFactory(barServiceInstance: BarService) {
  return barServiceInstance.manyProviders;
}

@NgModule({
  providers: [BarService, {provide: 'barServiceProviders', useFactory: barServiceProviderFactory, deps: [BarService] }],
  ...
})

@Component({
   selector: 'foo-component',
   templateUrl: './foo.component.html'
})
export class FooComponent {
  public constructor(@Inject('barServiceProviders') private services: any[]) {
   // services array contains the types and not the instantiated/resolved services.
  }
}
</code>```

Body:
Is there a way to register module/component providers in a dynamic way? I know about the useFactory option but this is only about a specific provider.
What I want to achieve is to register some providers during runtime, via a service instance.

Take the following code for example, where the BarService instance has a property that contains multiple providers, this service is provided in module level and then a contained component provides all these services in order to be accessible in the DI.

@Injectable()
export class BarService {
  public readonly manyProviders: Provider[] = [Service1, Service2, Service3];
}

@NgModule({
  providers: [BarService],
  ...
})

@Component({
   selector: 'foo-component',
   templateUrl: './foo.component.html',
   providers: [...barServiceInstance.manyProviders]
})
export class FooComponent {
  public constructor(private service1: Service1) {
   ...
  }
}

I've tried to use the useFactory approach, but the services are not resolved (which makes sense I guess...):

export function barServiceProviderFactory(barServiceInstance: BarService) {
  return barServiceInstance.manyProviders;
}

@NgModule({
  providers: [BarService, {provide: 'barServiceProviders', useFactory: barServiceProviderFactory, deps: [BarService] }],
  ...
})

@Component({
   selector: 'foo-component',
   templateUrl: './foo.component.html'
})
export class FooComponent {
  public constructor(@Inject('barServiceProviders') private services: any[]) {
   // services array contains the types and not the instantiated/resolved services.
  }
}


问:
Is it possible to specify a "not equals" condition whilst defining Load Balancer rules for path based routing?
I'm trying to add path based routing in an AWS Load Balancer.

In the above screenshot, the rule specifies "my_path" as the matching rule. Is there anyway to specify routing based on a path not matching a particular pattern, instead of matching?


问:
Automatically closing browser in kiosk mode after a timeout of some minutes or user inactivity
Operating System: Linux TLXOS
Available Browsers: Chromium and Microsoft Edge

I am trying to set up a terminal where my my colleagues can log in and browse in our intranet. The goal is to get a browser that opens in kiosk mode and closes itself if the user has not made any entries for a while.

Currently the browser successfully starts in kiosk and incognito mode and it opens our startpage. So far so good, but what I am missing is something like a timeout that just closes the browser after a certain amount of time, because this terminal shall be placed in a public area.

Actually I have to ways to edit the Command Line Args:

directly on the Intel Nuc in the browser properties

remotly in the TMS Management Software of TLXOS (opens the browser after it gets closed)

Besides Chromium I also tried Microsoft Edge, because I thought I had found a well solution (that was just for Edge), but in the end the output is the same, I still miss a timeout that closes the browser. These are my current Command Arguments/Switches:

(Chromium)
usr/bin/chromium --incognito --kiosk https://stackoverflow.com --user-response-timeout=1

(Microsoft Edge)
usr/bin/microsoft-edge --kiosk https://stackoverflow.com --edge-kiosk-type=fullscreen --kiosk-idle-timeout-minutes=1


问:
Change rem reference from html base font size to the div container font size
I'm injecting UI using the shadow dom approach into web pages as a chrome extension. The library I'm using to add styles inside the shadow dom uses rem instead of px and because of this, it's taking font-size reference from the HTML base font size. Some sites have different base font sizes so the shadow dom UI looks smaller or bigger on various sites.

Is there a way to tell shadow dom to use the base font size of 16px instead of taking reference from the HTML font size?


问:
SQFLite Stream for StreamProvider flutter
I am using SQFLite for storing data and have difficulties to set up the "listener" for changes. E.g: I have a User model, which is saved in SQFLite. If I delete the row in the DB for this user, I want my app to know about this.

In another project I have used Firebase and it was quite simply to setup StreamProvider as Firebase has everything needed for it. I tried to go through Firebase source code to recreate the same logic for SQFLite, but it's not that easy.

So the question is - how do I create a Stream for my User model so that if the entry is deleted I am notified about it? ( for start, but at the end would be nice to be informed about any changes )


问:
Use packages from old R-Version in new R-Version with renv
I'm using renv i.e. for package management in R-projects. I cannot load packages from external sources. After a new R-Version was installed, I want to continue using the same packages in the new version as used in the old R-version.

Since renv creates a new directory to store packages for the new R-version (e.g. .../renv/library/R-4.2/), which contains only "base" packages installed with the new R-version, I want to "clone" the packages stored in the renv environment of the old R-version (e.g. .../renv/library/R-4.1/).

What is the best practice to simply use the same packages in the new R-version compared to the old R-version (without installing packages). Using renv::restore(), renv tries to newly install packages for the new R-version (and I don't want this). Can I simply "copy" the content of .../renv/library/R-4.1/ to .../renv/library/R-4.2/? Does renv provide options to simply keep using packages from "old R-versions" (here R-4.1) in "new R-versions" (here R-4.2)?


问:
SQLIntegrityConstraintViolationException -> Column "name" can not be null INTRESTING
So, i create Entity in my DB from CommandLineRunner, everything okay.
Then i create some controller one of them give me next Exception, when i going to update my Entity ->

```<code>***java.sql.SQLIntegrityConstraintViolationException: Column 'name' cannot be null***
</code>```

Controller

```<code>@PostMapping ("/update")
    public String update (Instructor instructor) {
        instructorService.updateInstructor(instructor);
        return "redirect:/instructors/index";
    }
</code>```

Entity

```<code>@Entity
@Table (name = "Instructor")
public class Instructor {

    @Id
        @GeneratedValue (strategy = GenerationType.IDENTITY)
        @Column (name = "instructor_id", nullable = false)
        private Long instructorId;

        @Basic
        @Column (name = "name", nullable = false, length = 45)
        private String firstName;

        @Basic
        @Column (name = "lastName", nullable = false, length = 45)
        private String lastName;

        @Basic
        @Column (name = "summary", nullable = false, length = 45)
        private String instructorSummary;

        @OneToMany (mappedBy = "instructor", fetch = FetchType.LAZY)
        private Set <Course> courses = new HashSet<>();

        @OneToOne (cascade = CascadeType.REMOVE)
        @JoinColumn (name = "user_id", referencedColumnName = "user_id", nullable = false)
        private User user;
</code>```

When i delete (nullable=false) everything work by Entity does not appear in DB

Instructor Service

```<code>Instructor updateInstructor (Instructor instructor);
</code>```

InstructorImpl

```<code>@Override
    public Instructor updateInstructor(Instructor instructor) {
        return instructorDao.save(instructor);
    }
</code>```

DaoClass only extend JpaRepository

Update: here are the logs

Hibernate: update instructor set name=?, summary=?, last_name=?,
user_id=? where instructor_id=? 2023-01-13T14:41:40.545+02:00 WARN
4176 --- [nio-8071-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper :
SQL Error: 1048, SQLState: 23000 2023-01-13T14:41:40.545+02:00 ERROR
4176 --- [nio-8071-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper :
Column 'name' cannot be null 2023-01-13T14:41:40.551+02:00 ERROR 4176
--- [nio-8071-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed:
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint [null]] with root cause

Body:
So, i create Entity in my DB from CommandLineRunner, everything okay.
Then i create some controller one of them give me next Exception, when i going to update my Entity ->

***java.sql.SQLIntegrityConstraintViolationException: Column 'name' cannot be null***

Controller

@PostMapping ("/update")
    public String update (Instructor instructor) {
        instructorService.updateInstructor(instructor);
        return "redirect:/instructors/index";
    }

Entity

@Entity
@Table (name = "Instructor")
public class Instructor {

    @Id
        @GeneratedValue (strategy = GenerationType.IDENTITY)
        @Column (name = "instructor_id", nullable = false)
        private Long instructorId;

        @Basic
        @Column (name = "name", nullable = false, length = 45)
        private String firstName;

        @Basic
        @Column (name = "lastName", nullable = false, length = 45)
        private String lastName;

        @Basic
        @Column (name = "summary", nullable = false, length = 45)
        private String instructorSummary;

        @OneToMany (mappedBy = "instructor", fetch = FetchType.LAZY)
        private Set <Course> courses = new HashSet<>();

        @OneToOne (cascade = CascadeType.REMOVE)
        @JoinColumn (name = "user_id", referencedColumnName = "user_id", nullable = false)
        private User user;

When i delete (nullable=false) everything work by Entity does not appear in DB

Instructor Service

Instructor updateInstructor (Instructor instructor);

InstructorImpl

@Override
    public Instructor updateInstructor(Instructor instructor) {
        return instructorDao.save(instructor);
    }

DaoClass only extend JpaRepository

Update: here are the logs

Hibernate: update instructor set name=?, summary=?, last_name=?,
user_id=? where instructor_id=? 2023-01-13T14:41:40.545+02:00 WARN
4176 --- [nio-8071-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper :
SQL Error: 1048, SQLState: 23000 2023-01-13T14:41:40.545+02:00 ERROR
4176 --- [nio-8071-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper :
Column 'name' cannot be null 2023-01-13T14:41:40.551+02:00 ERROR 4176
--- [nio-8071-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed:
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint [null]] with root cause


问:
How can let my filter let the reactive request to pass and not block them
In my architecture, i have some custom starter that centralize all the dependencies and the methods that are common for my microservices, in one of those starter i have a method that play the role of a filter of all the request of my projet in all the microservices,the problem is that this filter don't let the reactive request written in webflux to pass, when i test in postman or in a front web app i get a 200 OK response but an empty payload and empty json. I which to know if there is any way to allow my reactive request to pass without being blocked.

There is my filter method:

```<code>@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(
            (HttpServletRequest) servletRequest);
        MDC.clear();
        String uniqueId = String.valueOf(Instant.now().toEpochMilli());
        MDC.put("traceId", uniqueId);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(
                (HttpServletResponse) servletResponse);
        log.info("Request path {}, {}, Address {}", requestWrapper.getRequestURI(), requestWrapper.getMethod(),
                servletRequest.getRemoteAddr());
        filterChain.doFilter(servletRequest, responseWrapper);
        responseWrapper.setHeader("traceId", uniqueId);
        responseWrapper.copyBodyToResponse();
        MDC.put("status", String.valueOf(responseWrapper.getStatus()));
        log.info("Response path {} status {}", requestWrapper.getRequestURI(),
                String.valueOf(responseWrapper.getStatus()));
    MDC.clear();
}
</code>```

and there is an example of one of my reactive methods:

```<code>@GetMapping("/{id}")
    public Mono<ResponseEntity<List<ResponseDTO>>> retrieve(@PathVariable("id") String id) {
        return reactor.core.publisher.Mono.fromCallable(() -> new ResponseEntity<>(
                this.service.retrieveById(id), org.springframework.http.HttpStatus.OK)::get).subscriberContext(         ReactiveSecurityContextHolder.withSecurityContext(reactor.core.publisher.Mono.just(SecurityContextHolder.getContext())));
    }
</code>```

Dispose d’un menu contextuel

Body:
In my architecture, i have some custom starter that centralize all the dependencies and the methods that are common for my microservices, in one of those starter i have a method that play the role of a filter of all the request of my projet in all the microservices,the problem is that this filter don't let the reactive request written in webflux to pass, when i test in postman or in a front web app i get a 200 OK response but an empty payload and empty json. I which to know if there is any way to allow my reactive request to pass without being blocked.

There is my filter method:

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(
            (HttpServletRequest) servletRequest);
        MDC.clear();
        String uniqueId = String.valueOf(Instant.now().toEpochMilli());
        MDC.put("traceId", uniqueId);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(
                (HttpServletResponse) servletResponse);
        log.info("Request path {}, {}, Address {}", requestWrapper.getRequestURI(), requestWrapper.getMethod(),
                servletRequest.getRemoteAddr());
        filterChain.doFilter(servletRequest, responseWrapper);
        responseWrapper.setHeader("traceId", uniqueId);
        responseWrapper.copyBodyToResponse();
        MDC.put("status", String.valueOf(responseWrapper.getStatus()));
        log.info("Response path {} status {}", requestWrapper.getRequestURI(),
                String.valueOf(responseWrapper.getStatus()));
    MDC.clear();
}

and there is an example of one of my reactive methods:

@GetMapping("/{id}")
    public Mono<ResponseEntity<List<ResponseDTO>>> retrieve(@PathVariable("id") String id) {
        return reactor.core.publisher.Mono.fromCallable(() -> new ResponseEntity<>(
                this.service.retrieveById(id), org.springframework.http.HttpStatus.OK)::get).subscriberContext(         ReactiveSecurityContextHolder.withSecurityContext(reactor.core.publisher.Mono.just(SecurityContextHolder.getContext())));
    }

Dispose d’un menu contextuel


问:
Java - fast permission checks with 15k Customers and 3k Users in ArrayLists
I've build an Webapplication, with typical main classes like Customer and User (of the App).

```<code>public class Customer extends User implements Serializable {
    private boolean female;
    private int customerId;
    private DateTime dateOfBirth;
    ...
}

</code>```
```<code>public class User implements Serializable {
    private UUID uuid;
    private DateTime created;
    private String title;
    private String lastName;
    private String firstName;
    private String email;
    private String password;
    private Branch branch
    ...
}
</code>```

At the moment I store the Customers in an ArrayList, about 15k of them.
Not all the Users (I have 3k users) have permission to see all customers.
The determination process if a users has access to a customers varies in speed.

For example:

if the users has Admin privileges, it's very fast, just one statement.

if the users has no admin privileges, the user might get access because the customer is in the same branch as the user or because the user is not in the same branch but the key account of the user.

Also there is a user hierarchy, so if the manager of a user is logged in, he should get access the all the customers his subordinates (users) can access.

Worst case is, the user has no permission to see/edit customer, so my app needs to perform all the tests (loop through the whole hierarchy) to deny access eventually.

The problem is, in the menu of the application I show a counter of the number of customers accessible. So at the moment, for every page request the application needs to perform the same task over and over again.

I thought about caching the numbers of customers accessible and perform the update task for example every 5 minutes. I would like to avoid that, because the number is very volatile and might show the wrong number a lot of times.

Then I thought I create a separate ArrayList of all customers a user has permission for and link that array directly to the User class. In order to simply the permission method by just looking up if a certain customer is in the dedicated customer ArrayList of the user.
Drawbacks might be a need to sync it every time a customer gets created/changed permissions.

Do you have a better idea how to tackle the issue?

Thank you all!

Body:
I've build an Webapplication, with typical main classes like Customer and User (of the App).

public class Customer extends User implements Serializable {
    private boolean female;
    private int customerId;
    private DateTime dateOfBirth;
    ...
}

public class User implements Serializable {
    private UUID uuid;
    private DateTime created;
    private String title;
    private String lastName;
    private String firstName;
    private String email;
    private String password;
    private Branch branch
    ...
}

At the moment I store the Customers in an ArrayList, about 15k of them.
Not all the Users (I have 3k users) have permission to see all customers.
The determination process if a users has access to a customers varies in speed.

For example:

if the users has Admin privileges, it's very fast, just one statement.

if the users has no admin privileges, the user might get access because the customer is in the same branch as the user or because the user is not in the same branch but the key account of the user.

Also there is a user hierarchy, so if the manager of a user is logged in, he should get access the all the customers his subordinates (users) can access.

Worst case is, the user has no permission to see/edit customer, so my app needs to perform all the tests (loop through the whole hierarchy) to deny access eventually.

The problem is, in the menu of the application I show a counter of the number of customers accessible. So at the moment, for every page request the application needs to perform the same task over and over again.

I thought about caching the numbers of customers accessible and perform the update task for example every 5 minutes. I would like to avoid that, because the number is very volatile and might show the wrong number a lot of times.

Then I thought I create a separate ArrayList of all customers a user has permission for and link that array directly to the User class. In order to simply the permission method by just looking up if a certain customer is in the dedicated customer ArrayList of the user.
Drawbacks might be a need to sync it every time a customer gets created/changed permissions.

Do you have a better idea how to tackle the issue?

Thank you all!


问:
Flag value source is not clear
I have a component named dealsummary.ascx with the below code :

<asp:image id='status' runnat='server' imageurl='<%#GetDealstatusPicture(eval('flag'))%>'/>

And in code component dealsummary.ascx.cs GetDealstatusPicture() method is defined, but I am not able to find out the source of flag.
Can anyone point what could be the source, or what more information should I provide?

```<code>public string GetDealstatusPicture(object dataItem)
{
    string ImageURL = string.empty
    if dataItem != null {
    int status = convert.ToInt32(dataItem);

    if ((status==1))
    {
        ImageURL ==/*Path to image*/
    }

    if ((status==2))
    {
        ImageURL ==/*Path to image*/
    }

    if ((status==3))
    {
        ImageURL ==/*Path to image*/
    }
}
</code>```

Title: Flag value source is not clear

Body:
I have a component named dealsummary.ascx with the below code :

<asp:image id='status' runnat='server' imageurl='<%#GetDealstatusPicture(eval('flag'))%>'/>

And in code component dealsummary.ascx.cs GetDealstatusPicture() method is defined, but I am not able to find out the source of flag.
Can anyone point what could be the source, or what more information should I provide?

public string GetDealstatusPicture(object dataItem)
{
    string ImageURL = string.empty
    if dataItem != null {
    int status = convert.ToInt32(dataItem);

    if ((status==1))
    {
        ImageURL ==/*Path to image*/
    }

    if ((status==2))
    {
        ImageURL ==/*Path to image*/
    }

    if ((status==3))
    {
        ImageURL ==/*Path to image*/
    }
}


问:
Access Scalene Profile Object via Python Code
I want to access the profiler output in python code after scalene_profiler.stop() but I cant seem to find any function that can give me access to it? The reason i need it is because I want the time-consumed in seconds instead of the Percentages that are in the report generated, and I want to save this data in my own format. Is that possible somehow?

An attempt I made on my own (although I don't think its most efficient):

from scalene import scalene_profiler
import time

scalene_profiler.start()
time.sleep(3). # my code - i wud like only stats of the lines of code in between start and stop in a dictionary.
scalene_profiler.stop()

def ddict2dict(d):
    if not isinstance(d, dict):
        return d
    new_d = {}
    for k, v in d.items():
        if isinstance(v, dict):
            new_d[k] = ddict2dict(v)
        else:
            new_d[k] = v
    return new_d

# an example of a way i've tried so far - i see RunningStats object here instead of the actual stats so not sure if this is most efficient
data = {n: ddict2dict(getattr(scalene_profiler.Scalene._Scalene__stats, n)) for n in
        scalene_profiler.ScaleneStatistics.payload_contents}
print(data)
```

Output:
{'max_footprint': 0, 'max_footprint_loc': None, 'current_footprint': 0, 'elapsed_time': 3.0018277168273926, 'alloc_samples': 0, 'total_cpu_samples': 2.391642999999993, 'cpu_samples_c': {'tmp.py': {18: 0.0016429999999999865}}, 'cpu_samples_python': {'tmp.py': {18: 2.389999999999993}}, 'bytei_map': {}, 'cpu_samples': {'tmp.py': 2.391642999999993}, 'cpu_utilization': {'tmp.py': {18: <scalene.runningstats.RunningStats object at 0x1232298d0>}}, 'memory_malloc_samples': {}, 'memory_python_samples': {}, 'memory_free_samples': {}, 'memcpy_samples': {}, 'memory_max_footprint': {}, 'per_line_footprint_samples': {}, 'total_memory_free_samples': 0.0, 'total_memory_malloc_samples': 0.0, 'memory_footprint_samples': [], 'function_map': {}, 'firstline_map': {}, 'gpu_samples': {'tmp.py': {18: 0.0}}, 'total_gpu_samples': 0.0, 'memory_malloc_count': {}, 'memory_free_count': {}}

Thank you!

Body:
I want to access the profiler output in python code after scalene_profiler.stop() but I cant seem to find any function that can give me access to it? The reason i need it is because I want the time-consumed in seconds instead of the Percentages that are in the report generated, and I want to save this data in my own format. Is that possible somehow?

An attempt I made on my own (although I don't think its most efficient):

from scalene import scalene_profiler
import time

scalene_profiler.start()
time.sleep(3). # my code - i wud like only stats of the lines of code in between start and stop in a dictionary.
scalene_profiler.stop()

def ddict2dict(d):
    if not isinstance(d, dict):
        return d
    new_d = {}
    for k, v in d.items():
        if isinstance(v, dict):
            new_d[k] = ddict2dict(v)
        else:
            new_d[k] = v
    return new_d

# an example of a way i've tried so far - i see RunningStats object here instead of the actual stats so not sure if this is most efficient
data = {n: ddict2dict(getattr(scalene_profiler.Scalene._Scalene__stats, n)) for n in
        scalene_profiler.ScaleneStatistics.payload_contents}
print(data)

Output:
{'max_footprint': 0, 'max_footprint_loc': None, 'current_footprint': 0, 'elapsed_time': 3.0018277168273926, 'alloc_samples': 0, 'total_cpu_samples': 2.391642999999993, 'cpu_samples_c': {'tmp.py': {18: 0.0016429999999999865}}, 'cpu_samples_python': {'tmp.py': {18: 2.389999999999993}}, 'bytei_map': {}, 'cpu_samples': {'tmp.py': 2.391642999999993}, 'cpu_utilization': {'tmp.py': {18: <scalene.runningstats.RunningStats object at 0x1232298d0>}}, 'memory_malloc_samples': {}, 'memory_python_samples': {}, 'memory_free_samples': {}, 'memcpy_samples': {}, 'memory_max_footprint': {}, 'per_line_footprint_samples': {}, 'total_memory_free_samples': 0.0, 'total_memory_malloc_samples': 0.0, 'memory_footprint_samples': [], 'function_map': {}, 'firstline_map': {}, 'gpu_samples': {'tmp.py': {18: 0.0}}, 'total_gpu_samples': 0.0, 'memory_malloc_count': {}, 'memory_free_count': {}}

Thank you!


问:
Can I access a specific field value from an object through accessing by the related name, in Django?
I'm making a vote app (Django rest framework), where users can post content and have it voted on through two options. The Vote modelVote model code has a ForeignKey field to the Post model, with the related name attribute "votes". The vote model also has a field named 'option', where choices 'option1' and 'option2' can be selected.

My goal is to count the total number of votes on a post, number of option1 votes and number of option2 votes.

I've been able to count the number of votes on a post through:

```<code>queryset = Post.objects.annotate(
        votes_count=Count('votes', distinct=True),
    )
</code>```

Post views

I am unsure how to count the number of option1 and option2 votes, separately.

Body:
I'm making a vote app (Django rest framework), where users can post content and have it voted on through two options. The Vote modelVote model code has a ForeignKey field to the Post model, with the related name attribute "votes". The vote model also has a field named 'option', where choices 'option1' and 'option2' can be selected.

My goal is to count the total number of votes on a post, number of option1 votes and number of option2 votes.

I've been able to count the number of votes on a post through:

queryset = Post.objects.annotate(
        votes_count=Count('votes', distinct=True),
    )

Post views

I am unsure how to count the number of option1 and option2 votes, separately.


问:
Trying to redirect the user to a specific page after form validation in WordPress
I am trying to redirect a user to a specific page after login form validation in my function.php file. Everything is working fine but, when I try to redirect the user to a specific URL, it's showing a "parser error".  Here is my code in the function.php file.

```<code> add_action( 'elementor_pro/forms/new_record', function( $record, $ajax_handler ) {

  $form_name = $record->get_form_settings( 'form_name' );

      if($form_name=='userloginform'){
        $conn = new mysqli("localhost","mydatabase","myuser","mypass");
        $raw_fields = $record->get( 'fields' );
        $fields = [];
           foreach ( $raw_fields as $id => $field ){
               $fields[ $id ] = $field['value'];
               $email=trim($fields['email']);
               $password=trim($fields['pass']);
         }
       $result=mysqli_query($conn, "SELECT * FROM tablename where email='$email' ");
       $row = $result->fetch_assoc();
          if(!empty($row)){
               if($row['password']==$password){
                    header('Location: https://www.mywebsite.com');
                    exit;
            }
        else{
                $ajax_handler->add_error_message( 'Incorrect Password! Please try again...
         );

        }
        }else{

            $ajax_handler->add_error_message( 'Email adress not found! please enter a valid email address... ' );
            }

}
</code>```

when I enter the email and password it return the following error.

Body:
I am trying to redirect a user to a specific page after login form validation in my function.php file. Everything is working fine but, when I try to redirect the user to a specific URL, it's showing a "parser error".  Here is my code in the function.php file.

 add_action( 'elementor_pro/forms/new_record', function( $record, $ajax_handler ) {

  $form_name = $record->get_form_settings( 'form_name' );

      if($form_name=='userloginform'){
        $conn = new mysqli("localhost","mydatabase","myuser","mypass");
        $raw_fields = $record->get( 'fields' );
        $fields = [];
           foreach ( $raw_fields as $id => $field ){
               $fields[ $id ] = $field['value'];
               $email=trim($fields['email']);
               $password=trim($fields['pass']);
         }
       $result=mysqli_query($conn, "SELECT * FROM tablename where email='$email' ");
       $row = $result->fetch_assoc();
          if(!empty($row)){
               if($row['password']==$password){
                    header('Location: https://www.mywebsite.com');
                    exit;
            }
        else{
                $ajax_handler->add_error_message( 'Incorrect Password! Please try again...
         );

        }
        }else{

            $ajax_handler->add_error_message( 'Email adress not found! please enter a valid email address... ' );
            }

}

when I enter the email and password it return the following error.


问:
Can i change the language of a react native app. Like how i change my phones language to be greek
I would like to change the app language so that some third party libraries are translated to greek.
I am trying to use @react-native-community/datetimepicker and translate it to Greek.

1)I have tried creating a

res/xml/locales_config.xml
i did this like so:
srs/main/res/ and created a folder called xml and a file locales_config.xml

inside a placed this code:
android documentation

```<code><?xml version="1.0" encoding="utf-8"?>
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
   <locale android:name="el"/>
</locale-config>
</code>```

2)In the manifest, add a line pointing to this new file:

```<code>  <uses-permission android:name="android.permission.INTERNET" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme"
      **---> android:localeConfig="@xml/locales_config**">

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true"

        >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>

</code>```

The app fails to locate the file. Do you know how to actually achieve this?

Body:
I would like to change the app language so that some third party libraries are translated to greek.
I am trying to use @react-native-community/datetimepicker and translate it to Greek.

1)I have tried creating a

res/xml/locales_config.xml
i did this like so:
srs/main/res/ and created a folder called xml and a file locales_config.xml

inside a placed this code:
android documentation

<?xml version="1.0" encoding="utf-8"?>
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
   <locale android:name="el"/>
</locale-config>

2)In the manifest, add a line pointing to this new file:

  <uses-permission android:name="android.permission.INTERNET" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme"
      **---> android:localeConfig="@xml/locales_config**">

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true"

        >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>

The app fails to locate the file. Do you know how to actually achieve this?


问:
Spring events not working in Spring Boot tests
I wanted to test case that involves Spring application events. I don't see my EventListener code executed. I have create a simple test case. It doesn't work either. Is this a limitation of the Spring Events that it doesn't work in tests?
When I debug the code I can see that the publisher was replaced by some kind of mock.

```<code>@SpringBootTest(classes = {Application.class, PubListTest.class})
@Slf4j
@Configuration
class PubListTest {

    @Autowired
    TestClass testClass;

    @Test
    @SneakyThrows
    void test() {
        testClass.publish();
    }

    @RequiredArgsConstructor
    @Component
    public static class TestClass {

        private final ApplicationEventPublisher publisher;

        public void publish() {
            publisher.publishEvent(new UserGroupDeleted(UUID.randomUUID(), Set.of()));
        }

        @EventListener
        public void onUserGroupEvent(UserGroupDeleted event) {
            System.out.println("TEST!");
        }

    }

}
</code>```

Body:
I wanted to test case that involves Spring application events. I don't see my EventListener code executed. I have create a simple test case. It doesn't work either. Is this a limitation of the Spring Events that it doesn't work in tests?
When I debug the code I can see that the publisher was replaced by some kind of mock.

@SpringBootTest(classes = {Application.class, PubListTest.class})
@Slf4j
@Configuration
class PubListTest {

    @Autowired
    TestClass testClass;

    @Test
    @SneakyThrows
    void test() {
        testClass.publish();
    }

    @RequiredArgsConstructor
    @Component
    public static class TestClass {

        private final ApplicationEventPublisher publisher;

        public void publish() {
            publisher.publishEvent(new UserGroupDeleted(UUID.randomUUID(), Set.of()));
        }

        @EventListener
        public void onUserGroupEvent(UserGroupDeleted event) {
            System.out.println("TEST!");
        }

    }

}


问:
Move VisJs graph with UI Buttons
I'm creating a graph with react-vis-js. The graph should be moved in unity with a map that is shown behind the graph. Therefore, I created custom Arrow and Zoom keys. They Work fine with the map. Now I am trying to implement the keys for the graph.

I tried to find a way to move the center of the graph but unfortunately there isn't a way of doing this. Furthermore, I tried to find a way to trigger the keypress events of the keyboard in the onclick of the buttons. The only thing I found was jQuery code that looked like this:$('item').keydown();

This didn't seem to work either. I think it's because this is actually meant to be used as listener not as trigger.

Questions:

Is there a way to have custom buttons for visjs to move and zoom the graph?

Is there a way to trigger keyboard button events with javascript UI buttons?

Do you have other ideas of solving this issue?

Title: Move VisJs graph with UI Buttons


问:
Reconstruct dropout rate for edward2's DenseVariationalDropout layer
I am currently training a neural network based on simulated data.
The standard architecture of the model is as follows:

Input layer (5 features)

Dense hidden layer (64 units)

Dense hidden layer (32 units)

Dense output layer (2 units)

To improve the model's performance, I implemented dropout for the Dense layers and tried different dropout rates. In my case, lower dropout rates (close to 10%) worked best.

Now, I want to implement a Bayesian NN that learns the dropout rate itself, basically doing Variational Dropout. However, edward2's implementation of the DenseVariationalDropout layer does not implement the posterior distribution as a Bernoulli distribution as done in the original dropout method, but (as far as I understand) a Gaussian distribution N(mu, sd).

I already trained the BNN using DenseVariationalDropout layer for the hidden layers (2 and 3) mentioned above.
However, when I print the learned weights/parameters of e.g. the first DenseVariationalDropout layer, the learned stddev is negative.

My question now is, how do I interpret the learned stddev parameters of the layer and is there a way to somehow reconstruct the dropout rate?

In the end, I want to compare the learned dropout rate to my previous experiments using the default Dropout layers where I input the dropout rate as a hyperparameter.

Here, you can find the weights/parameter output of the second layer (first hidden layer), only showing the results for the first input node. However, other numbers look identical/similar:.

```<code><tf.Variable 'dense_variational_dropout/kernel/mean:0' shape=(5, 64) dtype=float32, numpy=
array([[ 0.706813  , -0.70008826,  0.6587434 ,  0.6841269 ,  0.7477593 ,
        -0.67054933,  0.6094059 , -0.66187423, -0.72358364, -0.71848536,
        -0.72730917, -0.7543011 , -0.70441514, -0.6896457 ,  0.6773513 ,
        -0.7390508 ,  0.71809   ,  0.70859045, -0.7311058 , -0.6940158 ,
        -0.6691812 ,  0.7317551 , -0.71782017, -0.7040768 ,  0.72268885,
         0.686578  , -0.71496195, -0.74330693,  0.68203586, -0.71308035,
        -0.7066761 , -0.7129957 , -0.7120187 , -0.7271574 , -0.6683003 ,
        -0.69519144,  0.72729176, -0.7753829 ,  0.727453  , -0.7636749 ,
        -0.63404703, -0.69619894,  0.69890517,  0.69997096,  0.7178513 ,
        -0.7171472 ,  0.7051604 ,  0.72245914, -0.75696194,  0.70270175,
        -0.66893655, -0.7003819 ,  0.7011036 , -0.7276705 ,  0.7002035 ,
        -0.7110728 , -0.7156996 , -0.7777113 , -0.7551749 , -0.7739159 ,
         0.68988633, -0.6978364 ,  0.6694619 , -0.6941327 ], ...

<tf.Variable 'dense_variational_dropout/kernel/stddev:0' shape=(5, 64) dtype=float32, numpy=
array([[-4.3544664, -4.369482 , -4.4166455, -4.3739653, -4.290909 ,
        -4.410798 , -4.4918427, -4.408001 , -4.332697 , -4.329703 ,
        -4.3302474, -4.2944455, -4.3497696, -4.376223 , -4.3921137,
        -4.310383 , -4.3301587, -4.3463225, -4.3161445, -4.371665 ,
        -4.3999367, -4.3134384, -4.355694 , -4.3571577, -4.3263173,
        -4.374832 , -4.331994 , -4.308331 , -4.3812027, -4.3389053,
        -4.3488293, -4.3432593, -4.335625 , -4.3250175, -4.410793 ,
        -4.3587666, -4.3182616, -4.269835 , -4.3176365, -4.272719 ,
        -4.4506063, -4.3802133, -4.3598847, -4.35998  , -4.33531  ,
        -4.330978 , -4.3620105, -4.336859 , -4.2905126, -4.3617153,
        -4.403421 , -4.350309 , -4.3518815, -4.3138742, -4.364904 ,
        -4.344313 , -4.329627 , -4.2587113, -4.30761  , -4.2633414,
        -4.369821 , -4.3550806, -4.4168577, -4.3864827], ...
</code>```

Body:
I am currently training a neural network based on simulated data.
The standard architecture of the model is as follows:

Input layer (5 features)

Dense hidden layer (64 units)

Dense hidden layer (32 units)

Dense output layer (2 units)

To improve the model's performance, I implemented dropout for the Dense layers and tried different dropout rates. In my case, lower dropout rates (close to 10%) worked best.

Now, I want to implement a Bayesian NN that learns the dropout rate itself, basically doing Variational Dropout. However, edward2's implementation of the DenseVariationalDropout layer does not implement the posterior distribution as a Bernoulli distribution as done in the original dropout method, but (as far as I understand) a Gaussian distribution N(mu, sd).

I already trained the BNN using DenseVariationalDropout layer for the hidden layers (2 and 3) mentioned above.
However, when I print the learned weights/parameters of e.g. the first DenseVariationalDropout layer, the learned stddev is negative.

My question now is, how do I interpret the learned stddev parameters of the layer and is there a way to somehow reconstruct the dropout rate?

In the end, I want to compare the learned dropout rate to my previous experiments using the default Dropout layers where I input the dropout rate as a hyperparameter.

Here, you can find the weights/parameter output of the second layer (first hidden layer), only showing the results for the first input node. However, other numbers look identical/similar:.

<tf.Variable 'dense_variational_dropout/kernel/mean:0' shape=(5, 64) dtype=float32, numpy=
array([[ 0.706813  , -0.70008826,  0.6587434 ,  0.6841269 ,  0.7477593 ,
        -0.67054933,  0.6094059 , -0.66187423, -0.72358364, -0.71848536,
        -0.72730917, -0.7543011 , -0.70441514, -0.6896457 ,  0.6773513 ,
        -0.7390508 ,  0.71809   ,  0.70859045, -0.7311058 , -0.6940158 ,
        -0.6691812 ,  0.7317551 , -0.71782017, -0.7040768 ,  0.72268885,
         0.686578  , -0.71496195, -0.74330693,  0.68203586, -0.71308035,
        -0.7066761 , -0.7129957 , -0.7120187 , -0.7271574 , -0.6683003 ,
        -0.69519144,  0.72729176, -0.7753829 ,  0.727453  , -0.7636749 ,
        -0.63404703, -0.69619894,  0.69890517,  0.69997096,  0.7178513 ,
        -0.7171472 ,  0.7051604 ,  0.72245914, -0.75696194,  0.70270175,
        -0.66893655, -0.7003819 ,  0.7011036 , -0.7276705 ,  0.7002035 ,
        -0.7110728 , -0.7156996 , -0.7777113 , -0.7551749 , -0.7739159 ,
         0.68988633, -0.6978364 ,  0.6694619 , -0.6941327 ], ...

<tf.Variable 'dense_variational_dropout/kernel/stddev:0' shape=(5, 64) dtype=float32, numpy=
array([[-4.3544664, -4.369482 , -4.4166455, -4.3739653, -4.290909 ,
        -4.410798 , -4.4918427, -4.408001 , -4.332697 , -4.329703 ,
        -4.3302474, -4.2944455, -4.3497696, -4.376223 , -4.3921137,
        -4.310383 , -4.3301587, -4.3463225, -4.3161445, -4.371665 ,
        -4.3999367, -4.3134384, -4.355694 , -4.3571577, -4.3263173,
        -4.374832 , -4.331994 , -4.308331 , -4.3812027, -4.3389053,
        -4.3488293, -4.3432593, -4.335625 , -4.3250175, -4.410793 ,
        -4.3587666, -4.3182616, -4.269835 , -4.3176365, -4.272719 ,
        -4.4506063, -4.3802133, -4.3598847, -4.35998  , -4.33531  ,
        -4.330978 , -4.3620105, -4.336859 , -4.2905126, -4.3617153,
        -4.403421 , -4.350309 , -4.3518815, -4.3138742, -4.364904 ,
        -4.344313 , -4.329627 , -4.2587113, -4.30761  , -4.2633414,
        -4.369821 , -4.3550806, -4.4168577, -4.3864827], ...


问:
context.output behaviour in tie with Windowing
I am trying understand behaviour of context.output method in Apache Beam

I saw that based on javadoc each message will be promoted to the next step with timestamp of negative infinity

I know that pub/sub will automatically populate publishTime based on this answer and based on docs from Apache Beam each element in a PCollection has an associated intrinsic timestamp that will be equal to publishTime as I understand.

Does it mean that context.output will overwrite publishTime by timestamp of negative infinity for the next step? And according to documentation about windows all messages will be in the same window in terms of usage of session window?


问:
Expo Eas: fail exporting
I have resumed a project that I started a few months ago, an app that I am building in react native. The problem is that when going to compile it told me that I had to update to eas. I have updated and now when trying to do a build it tells me:

```<code>[stderr] FAILURE: Build completed with 2 failures.
[stderr] 1: Task failed with an exception.
[stderr] -----------
[stderr] * Where:
[stderr] Build file '/home/expo/workingdir/build/node_modules/@unimodules/core/android/build.gradle' line: 3
[stderr] * What went wrong:
[stderr] A problem occurred evaluating project ':unimodules-core'.
[stderr] > Plugin with id 'maven' not found.
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] 2: Task failed with an exception.
[stderr] -----------
[stderr] * What went wrong:
[stderr] A problem occurred configuring project ':expo'.
[stderr] >
[stderr] compileSdkVersion is not specified. Please add it to build.gradle
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] * Get more help at https://help.gradle.org
[stderr] BUILD FAILED in 1m 43s
</code>```

my code in build.gradle is the following (I've already changed the maven call to maven-publish but it's still the same):

```<code>    apply plugin: 'com.android.library'
    apply plugin: 'kotlin-android'
    apply plugin: 'java-library'
    apply plugin: 'maven-publish'

    group = 'org.unimodules'
    version = '6.7.1'

    buildscript {
      // Simple helper that allows the root project to override versions declared by this library.
      ext.safeExtGet = { prop, fallback ->
        rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
      }

      repositories {
        mavenCentral()
      }

      dependencies {
        classpath 'com.android.tools.build:gradle:6.7.1'
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${safeExtGet('kotlinVersion', '1.4.21')}")
      }
    }

    //Upload android library to maven with javadoc and android sources
    configurations {
      deployerJars
    }

    //Creating sources with comments
    task androidSourcesJar(type: Jar) {
      classifier = 'sources'
      from android.sourceSets.main.java.srcDirs
    }

    //Put the androidSources and javadoc to the artifacts
    artifacts {
      archives androidSourcesJar
    }

    uploadArchives {
      repositories {
        mavenDeployer {
          configuration = configurations.deployerJars
          repository(url: mavenLocal().url)
        }
      }
    }

    android {
      compileSdkVersion safeExtGet("compileSdkVersion", 30)
      buildToolsVersion safeExtGet("buildToolsVersion", 30)
      minSdkVersion safeExtGet("minSdkVersion", 21)
      targetSdkVersion safeExtGet("targetSdkVersion", 21)
      buildToolsVersion "30.0.1"
      compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
      }

      defaultConfig {
        compileSdkVersion 30
        minSdkVersion safeExtGet("minSdkVersion", 21)
        targetSdkVersion safeExtGet("targetSdkVersion", 30)
        consumerProguardFiles 'proguard-rules.pro'
        versionCode 20
        versionName "7.1.2"
        minSdkVersion 21
        targetSdkVersion 30
        buildToolsVersion "30.0.1"
      }
      lintOptions {
        abortOnError false
      }
    }

    dependencies {
      implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${safeExtGet('kotlinVersion', '1.4.21')}"
    }

</code>```

Do you know how I can solve it? Thanks.

Title: Expo Eas: fail exporting

Body:
I have resumed a project that I started a few months ago, an app that I am building in react native. The problem is that when going to compile it told me that I had to update to eas. I have updated and now when trying to do a build it tells me:

[stderr] FAILURE: Build completed with 2 failures.
[stderr] 1: Task failed with an exception.
[stderr] -----------
[stderr] * Where:
[stderr] Build file '/home/expo/workingdir/build/node_modules/@unimodules/core/android/build.gradle' line: 3
[stderr] * What went wrong:
[stderr] A problem occurred evaluating project ':unimodules-core'.
[stderr] > Plugin with id 'maven' not found.
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] 2: Task failed with an exception.
[stderr] -----------
[stderr] * What went wrong:
[stderr] A problem occurred configuring project ':expo'.
[stderr] >
[stderr] compileSdkVersion is not specified. Please add it to build.gradle
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] * Get more help at https://help.gradle.org
[stderr] BUILD FAILED in 1m 43s

my code in build.gradle is the following (I've already changed the maven call to maven-publish but it's still the same):

    apply plugin: 'com.android.library'
    apply plugin: 'kotlin-android'
    apply plugin: 'java-library'
    apply plugin: 'maven-publish'

    group = 'org.unimodules'
    version = '6.7.1'

    buildscript {
      // Simple helper that allows the root project to override versions declared by this library.
      ext.safeExtGet = { prop, fallback ->
        rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
      }

      repositories {
        mavenCentral()
      }

      dependencies {
        classpath 'com.android.tools.build:gradle:6.7.1'
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${safeExtGet('kotlinVersion', '1.4.21')}")
      }
    }

    //Upload android library to maven with javadoc and android sources
    configurations {
      deployerJars
    }

    //Creating sources with comments
    task androidSourcesJar(type: Jar) {
      classifier = 'sources'
      from android.sourceSets.main.java.srcDirs
    }

    //Put the androidSources and javadoc to the artifacts
    artifacts {
      archives androidSourcesJar
    }

    uploadArchives {
      repositories {
        mavenDeployer {
          configuration = configurations.deployerJars
          repository(url: mavenLocal().url)
        }
      }
    }

    android {
      compileSdkVersion safeExtGet("compileSdkVersion", 30)
      buildToolsVersion safeExtGet("buildToolsVersion", 30)
      minSdkVersion safeExtGet("minSdkVersion", 21)
      targetSdkVersion safeExtGet("targetSdkVersion", 21)
      buildToolsVersion "30.0.1"
      compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
      }

      defaultConfig {
        compileSdkVersion 30
        minSdkVersion safeExtGet("minSdkVersion", 21)
        targetSdkVersion safeExtGet("targetSdkVersion", 30)
        consumerProguardFiles 'proguard-rules.pro'
        versionCode 20
        versionName "7.1.2"
        minSdkVersion 21
        targetSdkVersion 30
        buildToolsVersion "30.0.1"
      }
      lintOptions {
        abortOnError false
      }
    }

    dependencies {
      implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${safeExtGet('kotlinVersion', '1.4.21')}"
    }

Do you know how I can solve it? Thanks.


问:
Is there a way to manipulate/read web browsers without dependency
I want to read a webpage content without using an extension.
I tried selenium, but the dependency for web driver application is quite hard to expand the app to multiple machines without further configuration.
I want to know if anyone manage to have access to the DOM (at least as read-only) or dev console directly from an application. I saw multiple scenarios with this subject but I couldn't found a solution.
Basically I want to be able to get the title of all tabs opened, and the position on the screen of some html elements in a tab.

What I've tried:
Selenium
Chrome Extension with Manifest v3


问:
Pass down data trough router link to my axios api call
I wanted to ask if it is possible to pass data to my methods via router link in vue. I am a beginner who made a .net core api with the help of a youtube video and then call it in a html with vue/javascript. Now I have different components and each one is a separate js file which I don't find very nice because actually in all of them the same thing happens.

For example (html router link):

```<code><li class="nav-item m-2">
     <router-link class="btn btn-light btn-outline-primary" to="/home">GM10</router-link>
</li>
</code>```

goes to home compnent which calls the api here and stores the json in chashier:

```<code>data(){
    return{
        chasier:[],
    }
},
methods:{
    refreshData(){
        axios.get(variables.API_URL+'Store10')
        .then((response)=>{
            this.chasier=response.data
        })
    }
},
</code>```

Second router link would be

<router-link class="btn btn-light btn-outline-primary" to="/GM11">GM11</router-link>

which goes to component gm11 but home and gm11 are the same except in gm11 it says axios.get(variables.API_URL+'Store11')

I would like to use only one js so that the router link "to" is the same for both but depending on which router link you press the url ending changes.

I tried already some stuff from the web but I nothing is really working. I lack of understanding and only the Youtube Video was not enough

Body:
I wanted to ask if it is possible to pass data to my methods via router link in vue. I am a beginner who made a .net core api with the help of a youtube video and then call it in a html with vue/javascript. Now I have different components and each one is a separate js file which I don't find very nice because actually in all of them the same thing happens.

For example (html router link):

     <router-link class="btn btn-light btn-outline-primary" to="/home">GM10</router-link>

goes to home compnent which calls the api here and stores the json in chashier:

data(){
    return{
        chasier:[],
    }
},
methods:{
    refreshData(){
        axios.get(variables.API_URL+'Store10')
        .then((response)=>{
            this.chasier=response.data
        })
    }
},

Second router link would be

<router-link class="btn btn-light btn-outline-primary" to="/GM11">GM11</router-link>

which goes to component gm11 but home and gm11 are the same except in gm11 it says axios.get(variables.API_URL+'Store11')

I would like to use only one js so that the router link "to" is the same for both but depending on which router link you press the url ending changes.

I tried already some stuff from the web but I nothing is really working. I lack of understanding and only the Youtube Video was not enough


问:
alertmanager - send digest mail every 12 hours
We are using Prometheus alertmanager for sending emails.  We have a requirement to send alert emails as only digest every 12 hours.

So, we configured our receiver like this:

```<code>  - receiver: digest-receiver
    group_by: [...]
    continue: true
    group_wait: 12h
    group_interval: 12h
    repreat_interval: 3d

</code>```

Is there any bad implications of using 12h for group_wait?

Also, how can we avoid including all active alerts in next mail and include an alert only once in an email?  For example:

Email sent at 12 AM - contains 12 active alerts

New alerts showed up since then, say extra 10.  Original 12 alerts are still active.

Email sent at 12 PM - contains 22 active alerts (12 original, 10 that showed up in last 12 hours).

Is there a way for mail sent at 12 PM to include only 10 new alert?

Note: We are not generating alerts using prometheus, but instead we use alertmanager API to post alerts from our services.

Body:
We are using Prometheus alertmanager for sending emails.  We have a requirement to send alert emails as only digest every 12 hours.

So, we configured our receiver like this:

  - receiver: digest-receiver
    group_by: [...]
    continue: true
    group_wait: 12h
    group_interval: 12h
    repreat_interval: 3d

Is there any bad implications of using 12h for group_wait?

Also, how can we avoid including all active alerts in next mail and include an alert only once in an email?  For example:

Email sent at 12 AM - contains 12 active alerts

New alerts showed up since then, say extra 10.  Original 12 alerts are still active.

Email sent at 12 PM - contains 22 active alerts (12 original, 10 that showed up in last 12 hours).

Is there a way for mail sent at 12 PM to include only 10 new alert?

Note: We are not generating alerts using prometheus, but instead we use alertmanager API to post alerts from our services.


问:
Unable to view in-memory table from SQLite database in PyCharm
I am using PyCharm to capture some data from web and push it into in-memory database-table on SQLite. I have debugged the code, it works fine, in the debugger I can see data being fetched, it being pushed into db[table] location.

Python code is as below -

```<code>import requests
import dataset
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse

def begin():
    db = dataset.connect('sqlite:///quotes.db')
    authors_seen = set()
    base_url = 'http://quotes.toscrape.com/'

def clean_url(url):
    # Clean '/author/Steve-Martin' to 'Steve-Martin'
    # Use urljoin to make an absolute URL
    url = urljoin(base_url, url)
    # Use urlparse to get out the path part
    path = urlparse(url).path
    # Now split the path by '/' and get the second part
    # E.g. '/author/Steve-Martinvisual studio' -> ['','author', 'Steve-Martin']
    return path.split('/')[2]

def scrape_quotes(html_soup):
    for quote in html_soup.select('div.quote'):
        quote_text = quote.find(class_='text').get_text(strip=True)
        quote_author_url = clean_url(quote.find(class_='author').find_next_sibling('a').get('href'))
        quote_tag_urls = [clean_url(a.get('href')) for a in quote.find_all('a', class_='tag')]
        authors_seen.add(quote_author_url)
        # Store this quote and its tags
        quote_id = db['quotes'].insert({'text' : quote_text, 'author' : quote_author_url})
        db['quotes_tags'].insert_many([{'quote_id' : quote_id, 'tag_id' : tag} for tag in quote_tag_urls])

def scrape_author(html_soup, author_id):
    author_name = html_soup.find(class_='author-title').get_text(strip=True)
    author_born_date = html_soup.find(class_='author-born-date').get_text(strip=True)
    author_born_loc = html_soup.find(class_='author-born-location').get_text(strip=True)
    author_desc = html_soup.find(class_='author-description').get_text(strip=True)
    db['authors'].insert({'author_id': author_id, 'name': author_name,
                          'born_date': author_born_date, 'born_location': author_born_loc,
                          'description': author_desc})

# Start by scraping all the quote pages
print('*****Beginning scraping process - quotes first.*****')
url = base_url
while True:
    print('Now scraping page:', url)
    r = requests.get(url)
    html_soup = BeautifulSoup(r.text, 'html.parser')
    # Scrape the quotes
    scrape_quotes(html_soup)
    # Is there a next page?
    next_a = html_soup.select('li.next > a')
    if not next_a or not next_a[0].get('href'):
        break
    url = urljoin(url, next_a[0].get('href'))
# Now fetch out the author information
print('*****Scraping authors data.*****')
for author_id in authors_seen:
    url = urljoin(base_url, '/author/' + author_id)
    print('Now scraping author:', url)
    r = requests.get(url)
    html_soup = BeautifulSoup(r.text, 'html.parser')
    # Scrape the author information
    scrape_author(html_soup, author_id)

db.commit()
db.close()
</code>```

What I am struggling with is the pycharm IDE connection. As shown in the figure below, I can see quotes.sqlite database. It has only one table listed - sqlite_master. Under server objects there are collations, modules and routines, which is part of infrastructure provided by SQLite.

Also, when I view the db object (python's driver to SQLite) in debugger, I can see the relevant table as shown in the picture below -

Any ideas why PyCharm refuses to show relevant table/collection in the IDE?

Body:
I am using PyCharm to capture some data from web and push it into in-memory database-table on SQLite. I have debugged the code, it works fine, in the debugger I can see data being fetched, it being pushed into db[table] location.

Python code is as below -

import requests
import dataset
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse

def begin():
    db = dataset.connect('sqlite:///quotes.db')
    authors_seen = set()
    base_url = 'http://quotes.toscrape.com/'

def clean_url(url):
    # Clean '/author/Steve-Martin' to 'Steve-Martin'
    # Use urljoin to make an absolute URL
    url = urljoin(base_url, url)
    # Use urlparse to get out the path part
    path = urlparse(url).path
    # Now split the path by '/' and get the second part
    # E.g. '/author/Steve-Martinvisual studio' -> ['','author', 'Steve-Martin']
    return path.split('/')[2]

def scrape_quotes(html_soup):
    for quote in html_soup.select('div.quote'):
        quote_text = quote.find(class_='text').get_text(strip=True)
        quote_author_url = clean_url(quote.find(class_='author').find_next_sibling('a').get('href'))
        quote_tag_urls = [clean_url(a.get('href')) for a in quote.find_all('a', class_='tag')]
        authors_seen.add(quote_author_url)
        # Store this quote and its tags
        quote_id = db['quotes'].insert({'text' : quote_text, 'author' : quote_author_url})
        db['quotes_tags'].insert_many([{'quote_id' : quote_id, 'tag_id' : tag} for tag in quote_tag_urls])

def scrape_author(html_soup, author_id):
    author_name = html_soup.find(class_='author-title').get_text(strip=True)
    author_born_date = html_soup.find(class_='author-born-date').get_text(strip=True)
    author_born_loc = html_soup.find(class_='author-born-location').get_text(strip=True)
    author_desc = html_soup.find(class_='author-description').get_text(strip=True)
    db['authors'].insert({'author_id': author_id, 'name': author_name,
                          'born_date': author_born_date, 'born_location': author_born_loc,
                          'description': author_desc})

# Start by scraping all the quote pages
print('*****Beginning scraping process - quotes first.*****')
url = base_url
while True:
    print('Now scraping page:', url)
    r = requests.get(url)
    html_soup = BeautifulSoup(r.text, 'html.parser')
    # Scrape the quotes
    scrape_quotes(html_soup)
    # Is there a next page?
    next_a = html_soup.select('li.next > a')
    if not next_a or not next_a[0].get('href'):
        break
    url = urljoin(url, next_a[0].get('href'))
# Now fetch out the author information
print('*****Scraping authors data.*****')
for author_id in authors_seen:
    url = urljoin(base_url, '/author/' + author_id)
    print('Now scraping author:', url)
    r = requests.get(url)
    html_soup = BeautifulSoup(r.text, 'html.parser')
    # Scrape the author information
    scrape_author(html_soup, author_id)

db.commit()
db.close()

What I am struggling with is the pycharm IDE connection. As shown in the figure below, I can see quotes.sqlite database. It has only one table listed - sqlite_master. Under server objects there are collations, modules and routines, which is part of infrastructure provided by SQLite.

Also, when I view the db object (python's driver to SQLite) in debugger, I can see the relevant table as shown in the picture below -

Any ideas why PyCharm refuses to show relevant table/collection in the IDE?


问:
AzurePageable breaks operation c#
I am having difficulties working with azure pageable.
I have these dificulties in several places.......

What happens is, if i interact with an AzurePageable and something goes wrong, the thread just doesnt return ........

For example yesterday I had too many requests to Azure Appconfiguration, the following piece of code would just hang.......

```<code>// Get all the settings from Azure app configuration
private static Dictionary<string, string> GetAllXYZSettings(ConfigurationClient client)
{
    var settingsSelector = new SettingSelector() { KeyFilter = "xyz:*" };
    var settings = client.GetConfigurationSettings(settingsSelector);

    Dictionary<string, string> config = new();
    foreach (dynamic setting in settings)
    {
        string settingValue = (string)setting.Value;

        if (!string.IsNullOrEmpty(settingValue))
        {
            config.Add(setting.Key, settingValue);
        }
    }
    return config;
}
</code>```

I tried several things, wrapped everything in a try catch but my thread would just not return.
How should i read the config so i can do some correct error handeling .....

Same behaviour is also observed when reading the servicebus queues.......

wrapped in try catch, didn't work

Title: AzurePageable breaks operation c#

Body:
I am having difficulties working with azure pageable.
I have these dificulties in several places.......

What happens is, if i interact with an AzurePageable and something goes wrong, the thread just doesnt return ........

For example yesterday I had too many requests to Azure Appconfiguration, the following piece of code would just hang.......

// Get all the settings from Azure app configuration
private static Dictionary<string, string> GetAllXYZSettings(ConfigurationClient client)
{
    var settingsSelector = new SettingSelector() { KeyFilter = "xyz:*" };
    var settings = client.GetConfigurationSettings(settingsSelector);

    Dictionary<string, string> config = new();
    foreach (dynamic setting in settings)
    {
        string settingValue = (string)setting.Value;

        if (!string.IsNullOrEmpty(settingValue))
        {
            config.Add(setting.Key, settingValue);
        }
    }
    return config;
}

I tried several things, wrapped everything in a try catch but my thread would just not return.
How should i read the config so i can do some correct error handeling .....

Same behaviour is also observed when reading the servicebus queues.......

wrapped in try catch, didn't work


问:
How to make poisson noise from uniform random numbers using central limit theorem?
Using the fact that Gaussian(λ=σ) is an approximation of Poisson(λ), I want to compute an approximation of Poisson noise using only uniform random numbers without using factorials.

There are two things I have no clue.

How to approximate gaussian noise from uniform noise.

How to approximate Poisson noise with Gaussian noise when λ is small.


问:
How to make two arrays have the same dimensions?
I have this part of a for loop:

```<code>a1.append((x[t] - 2 * x[t - 1] + x[t-2]) / ((t + 1) - (t)) ** 2)

a2.append((y[t] - 2 * y[t - 1] + y[t-2]) / ((t + 1) - (t)) ** 2)

a3.append((z[t] - 2 * z[t - 1] + z[t-2]) / ((t + 1) - (t)) ** 2)
</code>```

To explain further - I am iterating through a list that has 160 values. Yet when I try to plot it placing the a1, a2 and a3 components on the y axis and time(dimension also 160) on the x axis, I am getting the error "ValueError: x and y must have same first dimension, but have shapes (160,) and (157,)". Any tips on how to fix it? Sorry in advance if the solution is very obvious, its the end of the semester and my brain is mush

Body:
I have this part of a for loop:

a1.append((x[t] - 2 * x[t - 1] + x[t-2]) / ((t + 1) - (t)) ** 2)

a2.append((y[t] - 2 * y[t - 1] + y[t-2]) / ((t + 1) - (t)) ** 2)

a3.append((z[t] - 2 * z[t - 1] + z[t-2]) / ((t + 1) - (t)) ** 2)

To explain further - I am iterating through a list that has 160 values. Yet when I try to plot it placing the a1, a2 and a3 components on the y axis and time(dimension also 160) on the x axis, I am getting the error "ValueError: x and y must have same first dimension, but have shapes (160,) and (157,)". Any tips on how to fix it? Sorry in advance if the solution is very obvious, its the end of the semester and my brain is mush


问:
MongoSocketOpenException while using mongo uri with ocp mongodb route
```<code>2023-01-13 11:02:36.291  INFO 1 --- [           main]
org.mongodb.driver.cluster: Cluster created with settings {hosts=mongo.apps.lab.pacosta.com:27017], mode=SINGLE, requiredClusterType=UNKNOWN, derverSelectionTimeout='30000 ms'}
2023-01-13 11:02:36.429  INFO 1 --- [costa.com:27017] org.mongodb.driver.cluster: Exception in monitor thread
while connecting to server mongo.apps.lab.pacosta.com:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
  at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.1.1.jar!/:na]
  at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.1.1.jar!/:na]
  at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.1.1.jar!/:na]
  at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.1.1.jar!/:na]
  at java.lang.Thread.run(Thread.java:748) [na:1.8.0_212] Caused by: java.net.ConnectException: Connection refused (Connection refused)
  at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_212]
  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_212]
  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_212]
  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_212]
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_212]
  at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_212]`
</code>```

Here are screenshots of OCP routes and environment variables.

We are doing the same thing in our spring boot service using OCP version 4.11 but instead of using service ip we are taking it as a domain in mongo uri which is unable to create the connection

Body:
2023-01-13 11:02:36.291  INFO 1 --- [           main]
org.mongodb.driver.cluster: Cluster created with settings {hosts=mongo.apps.lab.pacosta.com:27017], mode=SINGLE, requiredClusterType=UNKNOWN, derverSelectionTimeout='30000 ms'}
2023-01-13 11:02:36.429  INFO 1 --- [costa.com:27017] org.mongodb.driver.cluster: Exception in monitor thread
while connecting to server mongo.apps.lab.pacosta.com:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
  at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.1.1.jar!/:na]
  at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.1.1.jar!/:na]
  at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.1.1.jar!/:na]
  at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.1.1.jar!/:na]
  at java.lang.Thread.run(Thread.java:748) [na:1.8.0_212] Caused by: java.net.ConnectException: Connection refused (Connection refused)
  at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_212]
  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_212]
  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_212]
  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_212]
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_212]
  at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_212]`

Here are screenshots of OCP routes and environment variables.

We are doing the same thing in our spring boot service using OCP version 4.11 but instead of using service ip we are taking it as a domain in mongo uri which is unable to create the connection


问:
iOS code redemption sheet does not display app name properly
When using the presentCodeRedemptionSheet API, on TestFlight build the screen does not render the app name and offer price correctly (see screenshot).

Will it work in the production app or is there some setting in ASC or app bundle I need to fill out? The app name displays correctly everywhere else, in the store and in the system.


问:
How do i run crontab in shell script when i want to run 2 cron jobs
I have a shell script in that i am running daily cronetab

Now i wanted to run start script when system is rebooted.

```<code>mkdir /etc/cron.daily
mkdir /etc/cron.daily/filesCleanup
sudo sed -i '/filesCleanup/d' /etc/crontab | rev | cut -d":" -f2- | rev
echo "0 0 * * * root run-parts /etc/cron.daily/filesCleanup/" >> /etc/crontab

echo " @reboot /usr/bin/sleep 60;/opt/start.sh ">>/etc/cron.onReboot
</code>```

Body:
I have a shell script in that i am running daily cronetab

Now i wanted to run start script when system is rebooted.

mkdir /etc/cron.daily
mkdir /etc/cron.daily/filesCleanup
sudo sed -i '/filesCleanup/d' /etc/crontab | rev | cut -d":" -f2- | rev
echo "0 0 * * * root run-parts /etc/cron.daily/filesCleanup/" >> /etc/crontab

echo " @reboot /usr/bin/sleep 60;/opt/start.sh ">>/etc/cron.onReboot


问:
asserting value of selector
The following Minitest snippet

```<code>puts response.body.inspect

# assert response.body.include?("Log out of all other sessions")
assert_select "input[type='submit']" do
  assert_select "[value=?]", "Log out of all other sessions"
end
</code>```

is failing as Expected at least 1 element matching "[value="Log out of all other sessions"]", found 0..

Yet the inspection has the following string:

```<code><form class=\"button_to\" method=\"post\" action=\"/active_sessions/destroy_all\">
<input type=\"hidden\" name=\"_method\" value=\"delete\" autocomplete=\"off\" />
<button type=\"submit\">Log out of all other sessions</button>
</form>
</code>```

The value in the view is set via i18n:

```<code><%= button_to t('user.auth.session_delete_all'), destroy_all_active_sessions_path, method: :delete %>
</code>```

uncommenting assert response.body.include?("Log out of all other sessions") asserts.

How should the failing assertion be cast?

Title: asserting value of selector

Body:
The following Minitest snippet

puts response.body.inspect

# assert response.body.include?("Log out of all other sessions")
assert_select "input[type='submit']" do
  assert_select "[value=?]", "Log out of all other sessions"
end

is failing as Expected at least 1 element matching "[value="Log out of all other sessions"]", found 0..

Yet the inspection has the following string:

<form class=\"button_to\" method=\"post\" action=\"/active_sessions/destroy_all\">
<input type=\"hidden\" name=\"_method\" value=\"delete\" autocomplete=\"off\" />
<button type=\"submit\">Log out of all other sessions</button>
</form>

The value in the view is set via i18n:

<%= button_to t('user.auth.session_delete_all'), destroy_all_active_sessions_path, method: :delete %>

uncommenting assert response.body.include?("Log out of all other sessions") asserts.

How should the failing assertion be cast?


问:
Setting up a swipe-able content subviews within iOS App Programatically
I am adding some additional functionality to an existing App. The App controls various industrial hardware devices. We would like to add a sub section where the user selects the appropriate device and is then presented with instructions that are tailored to that specific device.

I would like the user to be able to swipe through these instructions as per the orange sections of the attached image.

I know I need to use UIPageController but I am unsure how I then link this up to the various subviews (x, y & z in drawing) so the user could swipe between them.

I could put all of my subclassed UIViews into a horizontal scroll but that doesn't feel right.

Do I need to use an additional view controller for this? If so how would I implement this in the view hierarchy?

```<code>class InstructionsQ44 : UIView{

required init?(coder: NSCoder) {
    super.init(coder: coder)
    setupView()

}

override required init(frame: CGRect) {
    super.init(frame: frame)
    setupView()
}

var _steps = 5 //TBC
var pageControl = UIPageControl()

private func setupView()
{
    pageControl.translatesAutoresizingMaskIntoConstraints = false
    self.pageControl.numberOfPages = _steps
     self.pageControl.currentPage = 0
     self.addSubview(pageControl)
    NSLayoutConstraint.activate([
        pageControl.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        pageControl.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        pageControl.bottomAnchor.constraint(equalTo: self.bottomAnchor)
    ])

    pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControl.Event.valueChanged)
}

 @objc private func changePage(sender: AnyObject) -> () {

 }
}
</code>```

how could i add a number of instance of UIView such that I could swipe between them?

Thanks

Body:
I am adding some additional functionality to an existing App. The App controls various industrial hardware devices. We would like to add a sub section where the user selects the appropriate device and is then presented with instructions that are tailored to that specific device.

I would like the user to be able to swipe through these instructions as per the orange sections of the attached image.

I know I need to use UIPageController but I am unsure how I then link this up to the various subviews (x, y & z in drawing) so the user could swipe between them.

I could put all of my subclassed UIViews into a horizontal scroll but that doesn't feel right.

Do I need to use an additional view controller for this? If so how would I implement this in the view hierarchy?

class InstructionsQ44 : UIView{

required init?(coder: NSCoder) {
    super.init(coder: coder)
    setupView()

}

override required init(frame: CGRect) {
    super.init(frame: frame)
    setupView()
}

var _steps = 5 //TBC
var pageControl = UIPageControl()

private func setupView()
{
    pageControl.translatesAutoresizingMaskIntoConstraints = false
    self.pageControl.numberOfPages = _steps
     self.pageControl.currentPage = 0
     self.addSubview(pageControl)
    NSLayoutConstraint.activate([
        pageControl.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        pageControl.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        pageControl.bottomAnchor.constraint(equalTo: self.bottomAnchor)
    ])

    pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControl.Event.valueChanged)
}

 @objc private func changePage(sender: AnyObject) -> () {

 }
}

how could i add a number of instance of UIView such that I could swipe between them?

Thanks


问:
Error installing Android Studio in Windows 11 with Openjdk
I'm trying to install Android Studio on my computer after formatting, however I'm getting the following error:

Error android studio

I already have openjdk 11 installed and the JAVA_HOME variable is already defined.

environment variables

Yesterday I performed the same process without any problems on a Windows 10 machine, however on my personal Windows 11 PC I am getting this problem.

I have tried different versions and distributions of JAVA, such as JAVA 8 provided by Oracle, OpenJDK 11 provided by Microsoft and Eclipse Foundation, however without success.


问:
Will DataStore conflict with SharedPreferences?
We're improving an old Java project which heavily uses SharedPreferences, for some new functions the need of saving small pieces of data arised again, so I thought about creating a DataStore instance to handle those new needs.
Will that create a conflict with existing SharePreferences instance?

This question isn't about migration, it's about if both tools use the same files and thus, creating a using Datastore for the first time without the migration option, will replace existing Sharedpreferences.

Thank you


问:
How to show ProgressBar after AdMob ads in Adapter?
i am making android app using Rest Api and date getting from my WordPress Website , all works fine , i have added AdMob ads between content and when its loading page 2 from page 1 there is ProgressBar showing that "Posts Are Loading" at the bottom , now the problem is that when ProgressBar and Ads comes to same number than ProgressBar hides under AdMob ads , i mean it doesn’t show than , how can i make it visible and should be visible after ad ?

this is my code in Adapter

```<code>public RecyclerView.ViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        if (viewType == AD) {

            adview = new AdView(mContext);
            adview.setAdSize( AdSize.LARGE_BANNER);

            adview.setAdUnitId(mContext.getResources().getString(R.string.banner_ad_unit_id));

            float density = mContext.getResources().getDisplayMetrics().density;
            int height = Math.round(AdSize.LARGE_BANNER.getHeight() * density);
            AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, height);
            adview.setLayoutParams(params);

            new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("C5468C2B8941779E34B14EB796B9EA1B"));

            AdRequest request = new AdRequest.Builder().build();
            adview.loadAd(request);
            return new Holder(adview);

        }
        if (viewType == viewTypeData){
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list,parent,false);
            return new MyDataHolder(view);
        }else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading,parent,false);
            return new MyProgressHolder(view);
        }
    }
</code>```
```<code> private int getRealPosition(int position) {
        if (LIST_AD_DELTA == 0) {
            return position;
        } else {
            return position - position / LIST_AD_DELTA;
        }
    }

    @Override
    public int getItemCount() {
        return dataset.size();
    }

    @Override
    public int getItemViewType(int position){
        if (position > 0 && position % LIST_AD_DELTA == 0) {
            return AD;
        }
        else if (dataset.get(position).title.equals("progress")) {
            return viewTypeProgress;

        }
        return viewTypeData;
    }
    void showHideProgress(boolean shouldShowProgress){
        if (shouldShowProgress){
            dataset.add(new Model("progress","","","","","","","","",""));
            Handler handler = new Handler();

            final Runnable r = new Runnable() {
                public void run() {
            notifyItemInserted(dataset.size()-1);
                }
            };

            handler.post(r);

        }else {
            dataset.remove(dataset.size()-1);
            notifyItemRemoved(dataset.size()-1);
        }
    }
</code>```

i have tried to change LIST_AD_DELTA numbers but still no gain

```<code> int viewTypeData = 0,viewTypeProgress = 2 ;
    private static final int AD = 1;
    private static final int LIST_AD_DELTA = 4;
</code>```

Body:
i am making android app using Rest Api and date getting from my WordPress Website , all works fine , i have added AdMob ads between content and when its loading page 2 from page 1 there is ProgressBar showing that "Posts Are Loading" at the bottom , now the problem is that when ProgressBar and Ads comes to same number than ProgressBar hides under AdMob ads , i mean it doesn’t show than , how can i make it visible and should be visible after ad ?

this is my code in Adapter

public RecyclerView.ViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        if (viewType == AD) {

            adview = new AdView(mContext);
            adview.setAdSize( AdSize.LARGE_BANNER);

            adview.setAdUnitId(mContext.getResources().getString(R.string.banner_ad_unit_id));

            float density = mContext.getResources().getDisplayMetrics().density;
            int height = Math.round(AdSize.LARGE_BANNER.getHeight() * density);
            AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, height);
            adview.setLayoutParams(params);

            new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("C5468C2B8941779E34B14EB796B9EA1B"));

            AdRequest request = new AdRequest.Builder().build();
            adview.loadAd(request);
            return new Holder(adview);

        }
        if (viewType == viewTypeData){
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list,parent,false);
            return new MyDataHolder(view);
        }else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading,parent,false);
            return new MyProgressHolder(view);
        }
    }

 private int getRealPosition(int position) {
        if (LIST_AD_DELTA == 0) {
            return position;
        } else {
            return position - position / LIST_AD_DELTA;
        }
    }

    @Override
    public int getItemCount() {
        return dataset.size();
    }

    @Override
    public int getItemViewType(int position){
        if (position > 0 && position % LIST_AD_DELTA == 0) {
            return AD;
        }
        else if (dataset.get(position).title.equals("progress")) {
            return viewTypeProgress;

        }
        return viewTypeData;
    }
    void showHideProgress(boolean shouldShowProgress){
        if (shouldShowProgress){
            dataset.add(new Model("progress","","","","","","","","",""));
            Handler handler = new Handler();

            final Runnable r = new Runnable() {
                public void run() {
            notifyItemInserted(dataset.size()-1);
                }
            };

            handler.post(r);

        }else {
            dataset.remove(dataset.size()-1);
            notifyItemRemoved(dataset.size()-1);
        }
    }

i have tried to change LIST_AD_DELTA numbers but still no gain

 int viewTypeData = 0,viewTypeProgress = 2 ;
    private static final int AD = 1;
    private static final int LIST_AD_DELTA = 4;


问:
How do I reply to user's input in a chatbot
I am trying to create a chatbot that when chatted up gives the user a list of options on what the user wants eg A.check account balance B.Send money, then when the user enters A, the online chatbot should reply that particular user with another set of options eg if the user replies with B(Send money), the second set of options should be which bank do you want to transfer money to A.standard bank B.Union bank etc, how do I make it so that when the user enters A, the onlin  chatbot will the know the particular question that A belongs to, the first question or the second or the third

In building the chatbot, I tried giving every single option a unique letter so that I can check for what to reply when given that specific letter, but then the sequence of actions will be disordered


问:
mat-expansion-panel 'closed' event is called with random index instead of 'destroyed'
I am using mat-expansion-panel inside cdk-virtual-scroll.
I want to hit a function when the panel is destroyed after scrolling, but the (closed) event is called instead of the (destroyed) event, having a random index as a parameter.

```<code><mat-accordion>
  <cdk-virtual-scroll-viewport itemSize="50" [minBufferPx]="700" [maxBufferPx]="1000" scrollWindow>
    <mat-expansion-panel *cdkVirtualFor="let item of items;  let i = index;"
    (opened)="panelOpened(i)"
    (closed)="panelClosed(i)"
    (destroyed)="panelDestroyed(item.status, i)"
    [(expanded)]="item.status">
      <mat-expansion-panel-header>
        <mat-label>
          <mat-label> {{item.id}} </mat-label>
          <mat-label> isOpened: {{item.status}}</mat-label>
        </mat-label>
      </mat-expansion-panel-header>
      <div>
        <div>{{item.detail}}</div>
        <div>
          <button mat-raised-button color="accent">OK</button>
        </div>
      </div>
    </mat-expansion-panel>
  </cdk-virtual-scroll-viewport>
</mat-accordion>
</code>```

You can test the scenario here

Steps to recreate the issue:

open console

open any expansion panel (let's say item5)

scroll down till opened panel is destroyed.

the console will show a Closed 'random index number' message instead of Destroyed 5.

I do not want to use templateCacheSize: 0, it causes slow item rendering on scrolling.

Body:
I am using mat-expansion-panel inside cdk-virtual-scroll.
I want to hit a function when the panel is destroyed after scrolling, but the (closed) event is called instead of the (destroyed) event, having a random index as a parameter.

<mat-accordion>
  <cdk-virtual-scroll-viewport itemSize="50" [minBufferPx]="700" [maxBufferPx]="1000" scrollWindow>
    <mat-expansion-panel *cdkVirtualFor="let item of items;  let i = index;"
    (opened)="panelOpened(i)"
    (closed)="panelClosed(i)"
    (destroyed)="panelDestroyed(item.status, i)"
    [(expanded)]="item.status">
      <mat-expansion-panel-header>
        <mat-label>
          <mat-label> {{item.id}} </mat-label>
          <mat-label> isOpened: {{item.status}}</mat-label>
        </mat-label>
      </mat-expansion-panel-header>

{{item.detail}}

          <button mat-raised-button color="accent">OK</button>

    </mat-expansion-panel>
  </cdk-virtual-scroll-viewport>
</mat-accordion>

You can test the scenario here

Steps to recreate the issue:

open console

open any expansion panel (let's say item5)

scroll down till opened panel is destroyed.

the console will show a Closed 'random index number' message instead of Destroyed 5.

I do not want to use templateCacheSize: 0, it causes slow item rendering on scrolling.


问:
How can we use digital analytics to improve our website's user experience and increase conversions?
I am not getting conversions.

I have used good CTA buttons, headlines, and images but still not getting conversions.


问:
Fetch IP from selected directory through ansible & selection from frontend portal
can anyone suggest the ansible playbook for fetching provided IP is available or not in selected directory. selection of directory from GUI portal.

ansible playbook with ip address, directory selection manual. search will be in automatic give the return msg available  or not available.