问:
Prometheus not scrapping mysql metrics on the web
I created a mysql8 docker container like this:

```<code>$ docker network create db_network

$ docker run -d
--name mysql80
--publish 3306
--network db_network
--restart unless-stopped
--env MYSQL_ROOT_PASSWORD=mypassword
--volume mysql80-datadir:/var/lib/mysql
mysql:8
--default-authentication-plugin=mysql_native_password
</code>```

Then I configured the docker daemon like this

```<code>$ vim /etc/docker/daemon.json

{
  "metrics-addr" : " 157.90.21.142:9323",
  "experimental" : true
}

$ systemctl restart docker
</code>```

Then I deployed the mysql exporter like this:

```<code>$ docker exec -it mysql80 mysql -uroot -p
Enter password:

mysql> CREATE USER 'exporter'@'%' IDENTIFIED BY 'exporterpassword' WITH MAX_USER_CONNECTIONS 3;
mysql> GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'%';
</code>```

The mysql80 exporter is in a container like this

```<code>$ docker run -d
--name mysql80-exporter
--publish 9104
--network db_network
--restart always
--env DATA_SOURCE_NAME="exporter:exporterpassword@(mysql80:3306)/"
prom/mysqld-exporter:latest
--collect.info_schema.processlist
--collect.info_schema.innodb_metrics
--collect.info_schema.tablestats
--collect.info_schema.tables
--collect.info_schema.userstats
--collect.engine_innodb_status
</code>```

If I curl it from my server it scrapes metrics perfectly from mysql80 container.

Then i created the prometheus.yml like

```<code>$ vim ~/prometheus.yml

global:
  scrape_interval:     5s
  scrape_timeout:      3s
  evaluation_interval: 5s

# Our alerting rule files
rule_files:
  - "alert.rules"

# Scrape endpoints
scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['157.90.21.142:9090']

  - job_name: 'mysql'
    static_configs:
      - targets: ['mysql80-exporter:9104']

  - job_name: 'docker'
    static_configs:
      - targets: ['157.90.21.142:9323']
</code>```

And finally a container was created for prometheus like this.

```<code>$docker run -d  --name my-prometheus --network db_network  --mount
type=bind,src="$(pwd)"/prometheus.yml,destination=/etc/prometheus/prometheus.yml --publish
published=9090,target=9090,protocol=tcp  prom/prometheus
</code>```

In Prometheus web UI, the docker and prometheus metrics are scrapped perfectly. But, its not scrapping the mysql80-exporter:9104 metrics at all.

Can somebody provide a solution for this?

Body:
I created a mysql8 docker container like this:

$ docker network create db_network

$ docker run -d
--name mysql80
--publish 3306
--network db_network
--restart unless-stopped
--env MYSQL_ROOT_PASSWORD=mypassword
--volume mysql80-datadir:/var/lib/mysql
mysql:8
--default-authentication-plugin=mysql_native_password

Then I configured the docker daemon like this

$ vim /etc/docker/daemon.json

{
  "metrics-addr" : " 157.90.21.142:9323",
  "experimental" : true
}

$ systemctl restart docker

Then I deployed the mysql exporter like this:

$ docker exec -it mysql80 mysql -uroot -p
Enter password:

mysql> CREATE USER 'exporter'@'%' IDENTIFIED BY 'exporterpassword' WITH MAX_USER_CONNECTIONS 3;
mysql> GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'%';

The mysql80 exporter is in a container like this

$ docker run -d
--name mysql80-exporter
--publish 9104
--network db_network
--restart always
--env DATA_SOURCE_NAME="exporter:exporterpassword@(mysql80:3306)/"
prom/mysqld-exporter:latest
--collect.info_schema.processlist
--collect.info_schema.innodb_metrics
--collect.info_schema.tablestats
--collect.info_schema.tables
--collect.info_schema.userstats
--collect.engine_innodb_status

If I curl it from my server it scrapes metrics perfectly from mysql80 container.

Then i created the prometheus.yml like

$ vim ~/prometheus.yml

global:
  scrape_interval:     5s
  scrape_timeout:      3s
  evaluation_interval: 5s

# Our alerting rule files
rule_files:
  - "alert.rules"

# Scrape endpoints
scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['157.90.21.142:9090']

  - job_name: 'mysql'
    static_configs:
      - targets: ['mysql80-exporter:9104']

  - job_name: 'docker'
    static_configs:
      - targets: ['157.90.21.142:9323']

And finally a container was created for prometheus like this.

$docker run -d  --name my-prometheus --network db_network  --mount
type=bind,src="$(pwd)"/prometheus.yml,destination=/etc/prometheus/prometheus.yml --publish
published=9090,target=9090,protocol=tcp  prom/prometheus

In Prometheus web UI, the docker and prometheus metrics are scrapped perfectly. But, its not scrapping the mysql80-exporter:9104 metrics at all.

Can somebody provide a solution for this?


来源: stackexchange

问:
Least-Worst name data matching method between 1) a list of full names, and 2) a list of last names and first initials
For reasons outside my of control, I am sadly responsible for attempting to match two generally incompatible datasets. I was hoping for some advice and refinement on my current strategy, or a proposal for something entirely different.

Problem

I have two sets of data that contains different information about the same people, and my task is as efficiently as possible match up these two sets of data so all the information about a person can be stored in the same place. We're talking about a list of approx. ~3,000 people on each list. Names on one list, because of terrible data management, won't necessarily be on the other, so there's no guarantee of a match. The only common piece of data between both sets are names. Data set (1) contains people's full names in one cell. Data set (2) contains people's first initial and last name, separated by a comma. Here's some (fake) examples, with me having matched the data.

Data Set (1)
Data Set (2)

Alexander Brodbois
Brodbois, A

Anna Brulé
Brule, A

Auben Caramell
Caramell, A

This is currently being done on excel, but I also often use google sheets.

Current Strategy and its problems
My current strategy is to generate a common search key that has this format:

[LastName][FirstInitial]

So, for example:

Data Set (1)
Data Set (2)
Search Key

Auben Caramell
Caramell, A
CaramellA

This is working with ~90% accuracy; however I've noticed that there's a %5-7 failure due to a few cases:

One data set has an accent on a name, and the other doesn't; e.g. BruléA does not match with BruleA

Sometimes people have multiple names (up to 5), and the final name on Data Set (1) does not always correspond to what counts as the 'last name' in Data Set (2); it could be the 3rd or 4th name.

One data set has someone's name as one combined word, whereas the other counts the last name as being a 'middle' and a 'last' name.

I am also concerned with the possibility of incorrect matches, although this seems to have not happened yet. When I looked at one of the data sets, there was only 2 people with the same last name, and they had different initials.

I'm not expected to get 100% accuracy, but higher the better, obviously.

Any advice? The method I currently have works, but is not reliable and will require me to do heaps of manual work. I would just do the manual work, but this is a task that will have to be done monthly, and I don't have control over how the input is presented to me.

I swear there must be a smart regex method here that I haven't thought of, but I'm no expert at this.

ContentLicense: CC BY-SA 4.0


问:
How do I determine at execution time what version of Jest I am running?
I have a piece of code that I want to use in both Jest 26 and Jest 29

However, the syntax for jest.useFakeTimers has changed from 26 and 29

I wanted to do something like

```<code>if (jest.version.startsWith("26") {
  jest.useFakeTimers('modern');
} else if (jest.version.startsWith("29")) {
  jest.useFakeTimers({advanceTimers: true);
}
</code>```

Body:
I have a piece of code that I want to use in both Jest 26 and Jest 29

However, the syntax for jest.useFakeTimers has changed from 26 and 29

I wanted to do something like

if (jest.version.startsWith("26") {
  jest.useFakeTimers('modern');
} else if (jest.version.startsWith("29")) {
  jest.useFakeTimers({advanceTimers: true);
}


问:
fetch data from a network to feed k6 tests
I wanted to parametrize data in k6 and looked at the documentation, as well as other sites , but, I didn't find anything that used async/await syntax. Although, it does have a lifecycle method, and using the k6/http module, I might be able to do the request.

But, what if I have to clear/create a database schema , or use an ORM query in the setup method of k6? They all require some form of promises, which k6 doesn't seem to support?[2018 ref.]. How do I achieve this?


问:
Undefined reference to `GetProcessMemoryInfo'
Hello I wanted to get the memory usage of a program (so i can for example detect memory leaks), but no matter what I do compiler throws:

undefined reference to `GetProcessMemoryInfo' collect2.exe: error: ld returned 1 exit status

I compile the program using batch file:

```<code>set FLAGS=-Wall -Wextra -g3 -O -Werror
set LINK=-static-libgcc -lpsapi -lkernel32
set SRC=*.c src/*.c test/*c
set OUT_FILE=-o build/build.exe

gcc %FLAGS% %LINK% %SRC% %OUT_FILE%
</code>```

My code (simplified):

```<code>#include <windows.h>
#include <psapi.h>
#include <stdio.h>

int some_func_name()
{
    PROCESS_MEMORY_COUNTERS pmc;
    if ( !GetProcessMemoryInfo(GetCurrentProcess(),&pmc,sizeof(pmc)) ) { return 0; }
    return 1;
}
</code>```

Iv searched for similar problems but all of them are solved by including -lpsapi or -lkernel32 but in my case neither helps to solve this error. Would appreciate some help or explanation as to why my method doesn't work

Body:
Hello I wanted to get the memory usage of a program (so i can for example detect memory leaks), but no matter what I do compiler throws:

undefined reference to `GetProcessMemoryInfo' collect2.exe: error: ld returned 1 exit status

I compile the program using batch file:

set FLAGS=-Wall -Wextra -g3 -O -Werror
set LINK=-static-libgcc -lpsapi -lkernel32
set SRC=*.c src/*.c test/*c
set OUT_FILE=-o build/build.exe

gcc %FLAGS% %LINK% %SRC% %OUT_FILE%

My code (simplified):

#include <windows.h>
#include <psapi.h>
#include <stdio.h>

int some_func_name()
{
    PROCESS_MEMORY_COUNTERS pmc;
    if ( !GetProcessMemoryInfo(GetCurrentProcess(),&pmc,sizeof(pmc)) ) { return 0; }
    return 1;
}

Iv searched for similar problems but all of them are solved by including -lpsapi or -lkernel32 but in my case neither helps to solve this error. Would appreciate some help or explanation as to why my method doesn't work


问:
How to see all the the records regardless of the company or branch that I am logged in?
I have a custom DAC called Unidad and I need to see all the records regardless of the company or branch that I am logged in,

I tried to do this but it did not work: How do I return data for other branches for a user with access to only one branch?

This is my custom DAC:

```<code>using System;
using PX.Data;
using PX.Objects.AP;
using PX.Objects.GL;
using PX.CS;
using PX.Objects.CR;
using PX.Objects.AR;
using HgDevTraficoLocal;

namespace HgDevSeguridad
{
  [Serializable]
  [PXCacheName("Unidad")]
  public class Unidad : IBqlTable
  {
    #region BranchID
    [Branch()]
    [PXUIField(DisplayName = "Branch ID")]
    public virtual int? BranchID { get; set; }
    public abstract class branchID : PX.Data.BQL.BqlInt.Field<branchID> { }
    #endregion

    #region UnidadID
    [PXDBIdentity()]
    public virtual int? UnidadID { get; set; }
    public abstract class unidadID : PX.Data.BQL.BqlInt.Field<unidadID> { }
    #endregion

    #region UnidadCD
    [PXDBString(255, InputMask = "", IsKey = true, IsUnicode = true)]
    [PXUIField(DisplayName = "Unidad ID")]
    [PXSelector(
      typeof(Search<Unidad.unidadCD>),
      typeof(Unidad.unidadCD),
      typeof(Unidad.description),
      typeof(Unidad.marcaID),
      typeof(Unidad.tipoid),
      typeof(Unidad.estadoID))]
    public virtual string UnidadCD { get; set; }
    public abstract class unidadCD : PX.Data.BQL.BqlString.Field<unidadCD> { }
    #endregion

    #region Description
    [PXDBString(255, InputMask = "")]
    [PXUIField(DisplayName = "Description")]
    public virtual string Description { get; set; }
    public abstract class description : PX.Data.BQL.BqlString.Field<description> { }
    #endregion

    #region Noteid
    [PXNote()]
    public virtual Guid? Noteid { get; set; }
    public abstract class noteid : PX.Data.BQL.BqlGuid.Field<noteid> { }
    #endregion
  }

  public class constantTipoTransfer: PX.Data.Constant<string>
  {
    public constantTipoTransfer() : base("TRANSFER") { }
  }

  public class constantTipoPermisionario: PX.Data.Constant<string>
  {
    public constantTipoPermisionario() : base("PERM") { }
  }
}
</code>```

This is my custom graph:

```<code>public PXSelect<Unidad> UnidadView;

public virtual IEnumerable unidadView()
{
    using (new PXReadBranchRestrictedScope())
    {
        PXResultset<Unidad> Results = PXSelect<Unidad>.Select(this);

        foreach (PXResult<Unidad> result in Results)
        {
            Unidad unidad = result;

            yield return new PXResult<Unidad>(unidad);

        }
    }
}
</code>```

Can you help me with this?

Body:
I have a custom DAC called Unidad and I need to see all the records regardless of the company or branch that I am logged in,

I tried to do this but it did not work: How do I return data for other branches for a user with access to only one branch?

This is my custom DAC:

using System;
using PX.Data;
using PX.Objects.AP;
using PX.Objects.GL;
using PX.CS;
using PX.Objects.CR;
using PX.Objects.AR;
using HgDevTraficoLocal;

namespace HgDevSeguridad
{
  [Serializable]
  [PXCacheName("Unidad")]
  public class Unidad : IBqlTable
  {
    #region BranchID
    [Branch()]
    [PXUIField(DisplayName = "Branch ID")]
    public virtual int? BranchID { get; set; }
    public abstract class branchID : PX.Data.BQL.BqlInt.Field<branchID> { }
    #endregion

    #region UnidadID
    [PXDBIdentity()]
    public virtual int? UnidadID { get; set; }
    public abstract class unidadID : PX.Data.BQL.BqlInt.Field<unidadID> { }
    #endregion

    #region UnidadCD
    [PXDBString(255, InputMask = "", IsKey = true, IsUnicode = true)]
    [PXUIField(DisplayName = "Unidad ID")]
    [PXSelector(
      typeof(Search<Unidad.unidadCD>),
      typeof(Unidad.unidadCD),
      typeof(Unidad.description),
      typeof(Unidad.marcaID),
      typeof(Unidad.tipoid),
      typeof(Unidad.estadoID))]
    public virtual string UnidadCD { get; set; }
    public abstract class unidadCD : PX.Data.BQL.BqlString.Field<unidadCD> { }
    #endregion

    #region Description
    [PXDBString(255, InputMask = "")]
    [PXUIField(DisplayName = "Description")]
    public virtual string Description { get; set; }
    public abstract class description : PX.Data.BQL.BqlString.Field<description> { }
    #endregion

    #region Noteid
    [PXNote()]
    public virtual Guid? Noteid { get; set; }
    public abstract class noteid : PX.Data.BQL.BqlGuid.Field<noteid> { }
    #endregion
  }

  public class constantTipoTransfer: PX.Data.Constant<string>
  {
    public constantTipoTransfer() : base("TRANSFER") { }
  }

  public class constantTipoPermisionario: PX.Data.Constant<string>
  {
    public constantTipoPermisionario() : base("PERM") { }
  }
}

This is my custom graph:

public PXSelect<Unidad> UnidadView;

public virtual IEnumerable unidadView()
{
    using (new PXReadBranchRestrictedScope())
    {
        PXResultset<Unidad> Results = PXSelect<Unidad>.Select(this);

        foreach (PXResult<Unidad> result in Results)
        {
            Unidad unidad = result;

            yield return new PXResult<Unidad>(unidad);

        }
    }
}

Can you help me with this?


问:
<no module named serial> named Struggling to Import Serial
I am trying to import 'serial' on a Raspberry Pi Pico for some code for the Gravity I2C and UART O2 Sensor. When I try to run the code, the error message that I get is:

```<code>  File "<stdin>", line 12, in <module>
ImportError: no module named 'serial'
</code>```

I am not sure how to install 'serial' and I am not sure how to install it on the Raspberry Pi Pico - I am using Thonny as my editor.

This shows the error message.

I tried to install 'serial' through 'pip3 install serial' on my Macbook and it works, but when I re-run my code, the error message is still the same.

Thank you for any help and please do ask if there is any more information you need - I am relatively new to this so I may have missed something!

Body:
I am trying to import 'serial' on a Raspberry Pi Pico for some code for the Gravity I2C and UART O2 Sensor. When I try to run the code, the error message that I get is:

  File "<stdin>", line 12, in <module>
ImportError: no module named 'serial'

I am not sure how to install 'serial' and I am not sure how to install it on the Raspberry Pi Pico - I am using Thonny as my editor.

This shows the error message.

I tried to install 'serial' through 'pip3 install serial' on my Macbook and it works, but when I re-run my code, the error message is still the same.

Thank you for any help and please do ask if there is any more information you need - I am relatively new to this so I may have missed something!


问:
Mix 2 audios using FFMPEG based on main audio duration
I want to mix 2 audios into one audio using FFmpeg. There concept is one main audio running while the other keep repeating util its duration equals to main audio's duration</p>


问:
Does replication in Redis provide high availability too? Apart from increasing read performance
While going through redis documentation : Redis documentation, it says replication provides high-availability.

My understanding is that replication is used when we need to improve Read performance. It does not improve availability or write performance. But the documentation (link included above) says:

Replication can be used both for scalability, to have multiple
replicas for read-only queries (for example, slow O(N) operations can
be offloaded to replicas), or simply for improving data safety and
high availability

How does replication provide high availability? Don't we need redis in cluster/sentinel mode for high availability?


问:
How to execute in parallel the Kafka consumer and router handlers in a Vertx Java application?
I have a Java application that uses the Vertx framework and Kafka.

There is a Kafka consumer with a handler containing my custom code and a Vertx router that simply returns an "OK" to the requests.

While consuming messages from the topic, it happens that the router does not return "OK" immediately, but the request is pending for some seconds (even minutes) before returning the response.
This happens specifically when there are a lot of messages on the topic (e.g., 30K messages). I highlight that every single execution of the consumer lasts less than one second.

How can I consume the messages without blocking the Vertx route so that I can immediately receive the response from the route while the Kafka consumer is running?

It is important that the executions of the Kafka consumer must go sequentially between them (e.g., the execution of the consumer must start before the previous one is finished). I just want that the consumer execution and the router execution can run in parallel.

Here is the Vertx router:

```<code>  private Router createRouter() {
    final Router router = Router.router(vertx);
    router.get("/healthcheck").handler(rc -> rc.response().end("OK"));
    return router;
  }
</code>```

Here is the Kafka consumer:

```<code>  private void createKafkaConsumer() {
    KafkaConfiguration kafkaConfig = new KafkaConfiguration(config());
    consumer = KafkaConsumer.create(vertx, kafkaConfig.kafkaConsumerConfig());
    consumer.exceptionHandler(event -> log.error(event.getMessage()));

    consumer.handler(record -> {
        try {

           // Here is my consumer function that interacts with a database

        } catch (Exception e) {
          log.warn("Something is wrong: ",e);
        }
        consumer.commit();
    });
</code>```

EDIT:

Consumer Class:

```<code>public class ConsumerVerticle extends CustomAbstractVerticle {
  @Override
  public void start(Promise<Void> promise) {
    createKafkaConsumer(); // function above
  }
}
</code>```

Web Service class:

```<code>public class WebServiceVerticle extends CustomAbstractVerticle {
    @Override
    public void start(Promise<Void> promise) {
      createAnHttpServer(vertx, createRouter(), config(), promise); // createRouter() is the function above
    }
}
</code>```

Main Class:

```<code>public class MainVerticle extends CustomVerticle {

  private Future<Void> deployAllVerticles(Vertx vertx, JsonObject config, Class[] classes) {
    final Promise<Void> promise = Promise.promise();
    List<Future> futureList = new ArrayList<>();
    for (Class verticleClass : classes) {
      futureList.add(deployVerticle(vertx, verticleClass));
    }
  }

  private Future<String> deployVerticle(Vertx vertx, Class clazz) {
    return Future.future(promise -> vertx.deployVerticle(clazz.getName(), promise));
  }

  @Override
  public void start() {

    vertx = Vertx.vertx(new VertxOptions()
           .setMaxEventLoopExecuteTime(TimeUnit.SECONDS.toNanos(5))
    deployAllVerticles(vertx, new Class[] {ConsumerVerticle.class, WebServiceVerticle.class});
  }
}
</code>```

Body:
I have a Java application that uses the Vertx framework and Kafka.

There is a Kafka consumer with a handler containing my custom code and a Vertx router that simply returns an "OK" to the requests.

While consuming messages from the topic, it happens that the router does not return "OK" immediately, but the request is pending for some seconds (even minutes) before returning the response.
This happens specifically when there are a lot of messages on the topic (e.g., 30K messages). I highlight that every single execution of the consumer lasts less than one second.

How can I consume the messages without blocking the Vertx route so that I can immediately receive the response from the route while the Kafka consumer is running?

It is important that the executions of the Kafka consumer must go sequentially between them (e.g., the execution of the consumer must start before the previous one is finished). I just want that the consumer execution and the router execution can run in parallel.

Here is the Vertx router:

  private Router createRouter() {
    final Router router = Router.router(vertx);
    router.get("/healthcheck").handler(rc -> rc.response().end("OK"));
    return router;
  }

Here is the Kafka consumer:

  private void createKafkaConsumer() {
    KafkaConfiguration kafkaConfig = new KafkaConfiguration(config());
    consumer = KafkaConsumer.create(vertx, kafkaConfig.kafkaConsumerConfig());
    consumer.exceptionHandler(event -> log.error(event.getMessage()));

    consumer.handler(record -> {
        try {

           // Here is my consumer function that interacts with a database

        } catch (Exception e) {
          log.warn("Something is wrong: ",e);
        }
        consumer.commit();
    });

EDIT:

Consumer Class:

public class ConsumerVerticle extends CustomAbstractVerticle {
  @Override
  public void start(Promise<Void> promise) {
    createKafkaConsumer(); // function above
  }
}

Web Service class:

public class WebServiceVerticle extends CustomAbstractVerticle {
    @Override
    public void start(Promise<Void> promise) {
      createAnHttpServer(vertx, createRouter(), config(), promise); // createRouter() is the function above
    }
}

Main Class:

public class MainVerticle extends CustomVerticle {

  private Future<Void> deployAllVerticles(Vertx vertx, JsonObject config, Class[] classes) {
    final Promise<Void> promise = Promise.promise();
    List<Future> futureList = new ArrayList<>();
    for (Class verticleClass : classes) {
      futureList.add(deployVerticle(vertx, verticleClass));
    }
  }

  private Future<String> deployVerticle(Vertx vertx, Class clazz) {
    return Future.future(promise -> vertx.deployVerticle(clazz.getName(), promise));
  }

  @Override
  public void start() {

    vertx = Vertx.vertx(new VertxOptions()
           .setMaxEventLoopExecuteTime(TimeUnit.SECONDS.toNanos(5))
    deployAllVerticles(vertx, new Class[] {ConsumerVerticle.class, WebServiceVerticle.class});
  }
}


问:
Jasmine mocked clock is not reflected in dates declared const outside functions
I am running unit test for Angular using Jasmine.

I am mocking the dates in the test runs:

```<code> beforeEach(() => {
    jasmine.clock().install();
    jasmine.clock().mockDate(mockedNow);
});
</code>```

The dates created in the tests is mocked.
The dates created in any function called in the code running for that specific test case is mocked.

However if I reference a date that is declared const outside of any function (declared in dates.ts):

```<code>export const ONE_YEAR_BACK = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
export const YESTERDAY = new Date(Date.now() - 1000 * 60 * 60 * 24);
export const TODAY = new Date(Date.now());
</code>```

The dates above will not be mocked and reflect the actual date.
This will break my test cases.

How do I ensure that these dates is also mocked?

Body:
I am running unit test for Angular using Jasmine.

I am mocking the dates in the test runs:

 beforeEach(() => {
    jasmine.clock().install();
    jasmine.clock().mockDate(mockedNow);
});

The dates created in the tests is mocked.
The dates created in any function called in the code running for that specific test case is mocked.

However if I reference a date that is declared const outside of any function (declared in dates.ts):

export const ONE_YEAR_BACK = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
export const YESTERDAY = new Date(Date.now() - 1000 * 60 * 60 * 24);
export const TODAY = new Date(Date.now());

The dates above will not be mocked and reflect the actual date.
This will break my test cases.

How do I ensure that these dates is also mocked?


问:
Why does one of my MouseListeners stop working when I add a new one?
Below is a code example which might look awkward because it's only a small part of a bigger program. I wanted to add a MouseWheelListener so that I can use the mouseWheelMoved method to zoom in and out, which is located in the "Visualization" class. The good news is that the zooming actually works, but the problem is that my mouse dragging code in the "SomeTest" class stopped working once I added a MouseListener in the constructor of the Visualization class.

```<code>package sometest;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JViewport;

public class SomeTest implements Runnable
{
    public static void main(String[] args)
    {
        SomeTest st = new SomeTest();
        st.run();
    }

    @Override
    public void run()
    {
        JFrame f = new JFrame("Example");
        Visualization v = new Visualization();
        JScrollPane sp = new JScrollPane(v);

        MouseAdapter mouseAdapter = new MouseAdapter()
        {
            private Point origin;

            @Override
            public void mousePressed(MouseEvent e)
            {
                origin = new Point(e.getPoint());
            }

            @Override
            public void mouseDragged(MouseEvent e)
            {
                JViewport vp = null;

                if (origin != null)
                {
                    vp = sp.getViewport();
                }

                if (vp != null)
                {
                    int deltaX = origin.x - e.getX();
                    int deltaY = origin.y - e.getY();

                    Rectangle view = vp.getViewRect();
                    view.x += deltaX;
                    view.y += deltaY;

                    v.scrollRectToVisible(view);
                }
            }
        };

        sp.getViewport().addMouseListener(mouseAdapter);
        sp.getViewport().addMouseMotionListener(mouseAdapter);

        f.add(sp);
        f.setContentPane(sp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
</code>```
```<code>package sometest;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;
import javax.swing.Scrollable;
public class Visualization extends JPanel implements Scrollable, MouseWheelListener
{
    private double zoomFactor = 1;
    private double prevZoomFactor = 1;
    private boolean zoomer;
    private double xOffset = 0;
    private double yOffset = 0;

    public Visualization()
    {
        addMouseWheelListener(this);
        Font currentFont = getFont();
        Font newFont = currentFont.deriveFont(currentFont.getSize() * 15F);
        setFont(newFont);
        setBackground(Color.WHITE);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();

         if(zoomer)
         {
            AffineTransform at = new AffineTransform();

            double xRel = MouseInfo.getPointerInfo().getLocation().getX() - getLocationOnScreen().getX();
            double yRel = MouseInfo.getPointerInfo().getLocation().getY() - getLocationOnScreen().getY();

            double zoomDiv = zoomFactor / prevZoomFactor;

            xOffset = (zoomDiv) * (xOffset) + (1 - zoomDiv) * xRel;
            yOffset = (zoomDiv) * (yOffset) + (1 - zoomDiv) * yRel;

            at.translate(xOffset, yOffset);
            at.scale(zoomFactor, zoomFactor);
            prevZoomFactor = zoomFactor;
            g2d.transform(at);
            zoomer = false;
        }

        g2d.drawString("1234567890", 500, 200);

        g2d.dispose();
    }

    @Override
    public void mouseWheelMoved(MouseWheelEvent e)
    {
        zoomer = true;

        if (e.getWheelRotation() < 0)
        {
            zoomFactor *= 1.1;
            repaint();
        }

        if (e.getWheelRotation() > 0)
        {
            zoomFactor /= 1.1;
            repaint();
        }
    }

    @Override
        public Dimension getPreferredSize()
        {
            return new Dimension(2000, 800);
        }

        @Override
        public Dimension getPreferredScrollableViewportSize()
        {
            return new Dimension(1550, 800);
        }

        @Override
        public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
        {
            return 32;
        }

        @Override
        public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
        {
            return 32;
        }

        @Override
        public boolean getScrollableTracksViewportWidth()
        {
            return false;
        }

        @Override
        public boolean getScrollableTracksViewportHeight()
        {
            return false;
        }
}
</code>```

The desired result is that I want to be able to zoom in and out of my JScrollPane, but also be able to move through the JScrollPane by dragging my mouse. Did I implement the MouseListeners incorrectly, or is my problem something entirely different?

Body:
Below is a code example which might look awkward because it's only a small part of a bigger program. I wanted to add a MouseWheelListener so that I can use the mouseWheelMoved method to zoom in and out, which is located in the "Visualization" class. The good news is that the zooming actually works, but the problem is that my mouse dragging code in the "SomeTest" class stopped working once I added a MouseListener in the constructor of the Visualization class.

package sometest;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JViewport;

public class SomeTest implements Runnable
{
    public static void main(String[] args)
    {
        SomeTest st = new SomeTest();
        st.run();
    }

    @Override
    public void run()
    {
        JFrame f = new JFrame("Example");
        Visualization v = new Visualization();
        JScrollPane sp = new JScrollPane(v);

        MouseAdapter mouseAdapter = new MouseAdapter()
        {
            private Point origin;

            @Override
            public void mousePressed(MouseEvent e)
            {
                origin = new Point(e.getPoint());
            }

            @Override
            public void mouseDragged(MouseEvent e)
            {
                JViewport vp = null;

                if (origin != null)
                {
                    vp = sp.getViewport();
                }

                if (vp != null)
                {
                    int deltaX = origin.x - e.getX();
                    int deltaY = origin.y - e.getY();

                    Rectangle view = vp.getViewRect();
                    view.x += deltaX;
                    view.y += deltaY;

                    v.scrollRectToVisible(view);
                }
            }
        };

        sp.getViewport().addMouseListener(mouseAdapter);
        sp.getViewport().addMouseMotionListener(mouseAdapter);

        f.add(sp);
        f.setContentPane(sp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

package sometest;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;
import javax.swing.Scrollable;
public class Visualization extends JPanel implements Scrollable, MouseWheelListener
{
    private double zoomFactor = 1;
    private double prevZoomFactor = 1;
    private boolean zoomer;
    private double xOffset = 0;
    private double yOffset = 0;

    public Visualization()
    {
        addMouseWheelListener(this);
        Font currentFont = getFont();
        Font newFont = currentFont.deriveFont(currentFont.getSize() * 15F);
        setFont(newFont);
        setBackground(Color.WHITE);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();

         if(zoomer)
         {
            AffineTransform at = new AffineTransform();

            double xRel = MouseInfo.getPointerInfo().getLocation().getX() - getLocationOnScreen().getX();
            double yRel = MouseInfo.getPointerInfo().getLocation().getY() - getLocationOnScreen().getY();

            double zoomDiv = zoomFactor / prevZoomFactor;

            xOffset = (zoomDiv) * (xOffset) + (1 - zoomDiv) * xRel;
            yOffset = (zoomDiv) * (yOffset) + (1 - zoomDiv) * yRel;

            at.translate(xOffset, yOffset);
            at.scale(zoomFactor, zoomFactor);
            prevZoomFactor = zoomFactor;
            g2d.transform(at);
            zoomer = false;
        }

        g2d.drawString("1234567890", 500, 200);

        g2d.dispose();
    }

    @Override
    public void mouseWheelMoved(MouseWheelEvent e)
    {
        zoomer = true;

        if (e.getWheelRotation() < 0)
        {
            zoomFactor *= 1.1;
            repaint();
        }

        if (e.getWheelRotation() > 0)
        {
            zoomFactor /= 1.1;
            repaint();
        }
    }

    @Override
        public Dimension getPreferredSize()
        {
            return new Dimension(2000, 800);
        }

        @Override
        public Dimension getPreferredScrollableViewportSize()
        {
            return new Dimension(1550, 800);
        }

        @Override
        public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
        {
            return 32;
        }

        @Override
        public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
        {
            return 32;
        }

        @Override
        public boolean getScrollableTracksViewportWidth()
        {
            return false;
        }

        @Override
        public boolean getScrollableTracksViewportHeight()
        {
            return false;
        }
}

The desired result is that I want to be able to zoom in and out of my JScrollPane, but also be able to move through the JScrollPane by dragging my mouse. Did I implement the MouseListeners incorrectly, or is my problem something entirely different?


问:
IN R, how can here() escapes from package path inside tests (w/ testthat)?
I have a function in a package that calls here()

hello <- function() {
  here <- here::here()
  print(paste0(
    "Hello world!, I'm here: ", here
  ))
  here
}
```
<p>I would like to check its output somewhere outside the package path (w/ <code>{testthat}</code>)</p>
<pre class="lang-r prettyprint-override"><code># tentative 1
test_that("hello works outside", {
  pkj_here <- hello()  # pkj source path

  withr::with_tempdir({
    usethis::create_project(".", rstudio = FALSE, open = FALSE)
    local_here <- hello()
  })

  expect_false(pkj_here == local_here)
})

</code>```

The output of running the test is

ℹ Testing local
✔ | F W S  OK | Context
⠏ |         0 | hello
[1] "Hello, world! I'm here:  /home/cl/local"
v Setting active project to '/tmp/RtmpgOJplo/file4374633ed35'
v Creating 'R/'
v Writing a sentinel file '.here'
* Build robust paths within your project via `here::here()`
* Learn more at <https://here.r-lib.org>
v Setting active project to '<no active project>'
[1] "Hello, world! I'm here:  /home/cl/local"
✖ | 1       0 | hello [0.2s]
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Failure (test-hello.R:10): hello works
pkj_here == local_here is not FALSE

`actual`:   TRUE
`expected`: FALSE
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

══ Results ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
Duration: 0.2 s

[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]
```
<p>So the temp project seams created, activated, and setup for <code>here()</code> correctly, but the local <code>hello()</code> returns the same path as the global one.</p>
<p><strong>Question 1: Why if I am in a temp correctly activated project <code>here()</code> returns the package path?</strong></p>
<p>Looking at the <code>here</code> tests on GitHub, I tried to used <code>usethis::local_project()</code></p>
<pre class="lang-r prettyprint-override"><code># tentative 2
test_that("hello works outside", {
  usethis::local_project()
  local_here <- hello()
  expect_false("/home/cl/local" == local_here)
})
</code>```

but the test still failing (even if usethis::local_project() is outside of test_that call).

ℹ Testing local
✔ | F W S  OK | Context
⠏ |         0 | hello
✔ Setting active project to '/home/cl/local'
[1] "Hello, world! I'm here:  /home/cl/local"
⠋ | 1       0 | hello
✔ Setting active project to '<no active project>'
✖ | 1       0 | hello [0.2s]
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Failure (test-hello.R:11): hello works
"/home/cl/local" == local_here is not FALSE

`actual`:   TRUE
`expected`: FALSE
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

══ Results ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
Duration: 0.2 s

[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]
```
<p><strong>Question 2: Why if I activate a local (temp) project I return a message of no-activated-project, and <code>here()</code> still return my package path?</strong></p>
<p>Finally, combining both the solutions and even without creating a project in the tmp dir:</p>
<pre class="lang-r prettyprint-override"><code># solution 3
test_that("hello works", {
  usethis::local_project()
  withr::with_tempdir({
    local_here <- hello()
  })

  expect_false("/home/cl/local" == local_here)
})

</code>```

the test passes!

ℹ Testing local
✔ | F W S  OK | Context
⠏ |         0 | hello
v Setting active project to '/home/cl/local'
[1] "Hello, world! I'm here:  /tmp/Rtmpz1ZNSb/file43c0b381fb52e"
v Setting active project to '<no active project>'
✔ |         1 | hello
```
<p><strong>Question 3: Why if I activate a local project which states it is active at <code>/home/cl/local</code> and from there I go outside in a temp folder, <code>here()</code> returns the temp folder? (this seams even more strange the the failures)</strong></p>
<p>Moreover, to completely let you know that I do not understand possibly anything (:-)), I tried a modification of the solution which seams more logic to me:</p>
<pre class="lang-r prettyprint-override"><code># solution 4
test_that("hello works", {
  withr::with_tempdir({
    usethis::local_project()
    local_here <- hello()
  })

  expect_false("/home/cl/local" == local_here)
})

</code>```

and it fails even earlier...

ℹ Testing local
✔ | F W S  OK | Context
⠏ |         0 | hello
v Setting active project to '<no active project>'
✖ | 1       0 | hello
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Error (test-hello.R:2): hello works
<usethis_error/error/condition>
Error: Path '/tmp/RtmplPurvD/file43ef6750611af/' does not appear to be inside a project or package.
Backtrace:
 1. withr::with_tempdir(...)
      at test-hello.R:2:2
 4. usethis::local_project()
      at test-hello.R:3:4
 5. usethis::proj_set(path = path, force = force)
 6. usethis::ui_stop("Path {ui_path(path)} does not appear to be inside a project or package.")
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

══ Results ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]
```
<p><strong>Question 4: why if I switch to a temp folder, and try to activate a local project there I get an error because I am not in a project?! (I know I not in a project, so I could like there a local temporary/isolated one)</strong></p>
<p>Can someone (answer directly if it would be sufficiently short, or) point me to some resource to study and have an answer by myself?</p>
<p>Thank you all!
Corrado.</p>

 Session info

<pre class="lang-r prettyprint-override"><code>> devtools::session_info()
─ Session info ─────────────────────────────────────────────────────────
 setting  value
 version  R version 4.2.2 Patched (2022-11-10 r83330)
 os       Ubuntu 22.04.1 LTS
 system   x86_64, linux-gnu
 ui       RStudio
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       Europe/Rome
 date     2022-12-23
 rstudio  2022.12.0+353 Elsbeth Geranium (desktop)
 pandoc   NA

─ Packages ─────────────────────────────────────────────────────────────
 ! package     * version date (UTC) lib source
   brio          1.1.3   2021-11-30 [1] RSPM (R 4.2.0)
   cachem        1.0.6   2021-08-19 [1] RSPM (R 4.2.0)
   callr         3.7.3   2022-11-02 [1] RSPM (R 4.2.0)
 P cli           3.5.0   2022-12-20 [?] RSPM (R 4.2.0)
 P crayon        1.5.2   2022-09-29 [?] CRAN (R 4.2.2)
 P desc          1.4.2   2022-09-08 [?] CRAN (R 4.2.2)
   devtools    * 2.4.5   2022-10-11 [1] RSPM (R 4.2.0)
   digest        0.6.31  2022-12-11 [1] RSPM (R 4.2.0)
   ellipsis      0.3.2   2021-04-29 [1] RSPM (R 4.2.0)
   fansi         1.0.3   2022-03-24 [1] RSPM (R 4.2.0)
   fastmap       1.1.0   2021-01-25 [1] RSPM (R 4.2.0)
 P fs            1.5.2   2021-12-08 [?] CRAN (R 4.2.2)
 P glue          1.6.2   2022-02-24 [?] CRAN (R 4.2.2)
 P here          1.0.1   2020-12-13 [?] CRAN (R 4.2.2)
   htmltools     0.5.4   2022-12-07 [1] RSPM (R 4.2.0)
   htmlwidgets   1.6.0   2022-12-15 [1] RSPM (R 4.2.0)
   httpuv        1.6.7   2022-12-14 [1] RSPM (R 4.2.0)
   later         1.3.0   2021-08-18 [1] RSPM (R 4.2.0)
 P lifecycle     1.0.3   2022-10-07 [?] CRAN (R 4.2.2)
 P magrittr      2.0.3   2022-03-30 [?] CRAN (R 4.2.2)
   memoise       2.0.1   2021-11-26 [1] RSPM (R 4.2.0)
 P mime          0.12    2021-09-28 [?] CRAN (R 4.2.2)
   miniUI        0.1.1.1 2018-05-18 [1] RSPM (R 4.2.0)
   pillar        1.8.1   2022-08-19 [1] RSPM (R 4.2.0)
   pkgbuild      1.4.0   2022-11-27 [1] RSPM (R 4.2.0)
   pkgload       1.3.2   2022-11-16 [1] RSPM (R 4.2.0)
   prettyunits   1.1.1   2020-01-24 [1] RSPM (R 4.2.0)
   processx      3.8.0   2022-10-26 [1] RSPM (R 4.2.0)
   profvis       0.3.7   2020-11-02 [1] RSPM (R 4.2.0)
   promises      1.2.0.1 2021-02-11 [1] RSPM (R 4.2.0)
   ps            1.7.2   2022-10-26 [1] RSPM (R 4.2.0)
 P purrr         1.0.0   2022-12-20 [?] RSPM (R 4.2.0)
 P R6            2.5.1   2021-08-19 [?] CRAN (R 4.2.2)
   Rcpp          1.0.9   2022-07-08 [1] RSPM (R 4.2.0)
   remotes       2.4.2   2021-11-30 [1] RSPM (R 4.2.0)
   renv          0.16.0  2022-09-29 [1] CRAN (R 4.2.2)
 P rlang         1.0.6   2022-09-24 [?] CRAN (R 4.2.2)
 P rprojroot     2.0.3   2022-04-02 [?] CRAN (R 4.2.2)
 P rstudioapi    0.14    2022-08-22 [?] CRAN (R 4.2.2)
   sessioninfo   1.2.2   2021-12-06 [1] RSPM (R 4.2.0)
   shiny         1.7.4   2022-12-15 [1] RSPM (R 4.2.0)
   stringi       1.7.8   2022-07-11 [1] RSPM (R 4.2.0)
   stringr       1.5.0   2022-12-02 [1] RSPM (R 4.2.0)
   testthat      3.1.6   2022-12-09 [1] RSPM (R 4.2.0)
   urlchecker    1.0.1   2021-11-30 [1] RSPM (R 4.2.0)
 P usethis     * 2.1.6   2022-05-25 [?] CRAN (R 4.2.2)
   utf8          1.2.2   2021-07-24 [1] RSPM (R 4.2.0)
 P vctrs         0.5.1   2022-11-16 [?] RSPM (R 4.2.0)
 P withr         2.5.0   2022-03-03 [?] CRAN (R 4.2.2)
   xtable        1.8-4   2019-04-21 [1] RSPM (R 4.2.0)

 [1] /home/cl/.cache/R/renv/library/local-04c28f88/R-4.2/x86_64-pc-linux-gnu
 [2] /home/cl/local/renv/sandbox/R-4.2/x86_64-pc-linux-gnu/9a444a72

 P ── Loaded and on-disk path mismatch.

────────────────────────────────────────────────────────────────────────
</code>```

Body:
I have a function in a package that calls here()

hello <- function() {
  here <- here::here()
  print(paste0(
    "Hello world!, I'm here: ", here
  ))
  here
}

I would like to check its output somewhere outside the package path (w/ {testthat})

# tentative 1
test_that("hello works outside", {
  pkj_here <- hello()  # pkj source path

  withr::with_tempdir({
    usethis::create_project(".", rstudio = FALSE, open = FALSE)
    local_here <- hello()
  })

  expect_false(pkj_here == local_here)
})

The output of running the test is

ℹ Testing local
✔ | F W S  OK | Context
⠏ |         0 | hello
[1] "Hello, world! I'm here:  /home/cl/local"
v Setting active project to '/tmp/RtmpgOJplo/file4374633ed35'
v Creating 'R/'
v Writing a sentinel file '.here'
* Build robust paths within your project via `here::here()`
* Learn more at <https://here.r-lib.org>
v Setting active project to '<no active project>'
[1] "Hello, world! I'm here:  /home/cl/local"
✖ | 1       0 | hello [0.2s]
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Failure (test-hello.R:10): hello works
pkj_here == local_here is not FALSE

`actual`:   TRUE
`expected`: FALSE
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

══ Results ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
Duration: 0.2 s

[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]

So the temp project seams created, activated, and setup for here() correctly, but the local hello() returns the same path as the global one.

Question 1: Why if I am in a temp correctly activated project here() returns the package path?

Looking at the here tests on GitHub, I tried to used usethis::local_project()

# tentative 2
test_that("hello works outside", {
  usethis::local_project()
  local_here <- hello()
  expect_false("/home/cl/local" == local_here)
})

but the test still failing (even if usethis::local_project() is outside of test_that call).

ℹ Testing local
✔ | F W S  OK | Context
⠏ |         0 | hello
✔ Setting active project to '/home/cl/local'
[1] "Hello, world! I'm here:  /home/cl/local"
⠋ | 1       0 | hello
✔ Setting active project to '<no active project>'
✖ | 1       0 | hello [0.2s]
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Failure (test-hello.R:11): hello works
"/home/cl/local" == local_here is not FALSE

`actual`:   TRUE
`expected`: FALSE
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

══ Results ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
Duration: 0.2 s

[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]

Question 2: Why if I activate a local (temp) project I return a message of no-activated-project, and here() still return my package path?

Finally, combining both the solutions and even without creating a project in the tmp dir:

# solution 3
test_that("hello works", {
  usethis::local_project()
  withr::with_tempdir({
    local_here <- hello()
  })

  expect_false("/home/cl/local" == local_here)
})

the test passes!

ℹ Testing local
✔ | F W S  OK | Context
⠏ |         0 | hello
v Setting active project to '/home/cl/local'
[1] "Hello, world! I'm here:  /tmp/Rtmpz1ZNSb/file43c0b381fb52e"
v Setting active project to '<no active project>'
✔ |         1 | hello

Question 3: Why if I activate a local project which states it is active at /home/cl/local and from there I go outside in a temp folder, here() returns the temp folder? (this seams even more strange the the failures)

Moreover, to completely let you know that I do not understand possibly anything (:-)), I tried a modification of the solution which seams more logic to me:

# solution 4
test_that("hello works", {
  withr::with_tempdir({
    usethis::local_project()
    local_here <- hello()
  })

  expect_false("/home/cl/local" == local_here)
})

and it fails even earlier...

ℹ Testing local
✔ | F W S  OK | Context
⠏ |         0 | hello
v Setting active project to '<no active project>'
✖ | 1       0 | hello
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Error (test-hello.R:2): hello works
<usethis_error/error/condition>
Error: Path '/tmp/RtmplPurvD/file43ef6750611af/' does not appear to be inside a project or package.
Backtrace:
 1. withr::with_tempdir(...)
      at test-hello.R:2:2
 4. usethis::local_project()
      at test-hello.R:3:4
 5. usethis::proj_set(path = path, force = force)
 6. usethis::ui_stop("Path {ui_path(path)} does not appear to be inside a project or package.")
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

══ Results ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]

Question 4: why if I switch to a temp folder, and try to activate a local project there I get an error because I am not in a project?! (I know I not in a project, so I could like there a local temporary/isolated one)

Can someone (answer directly if it would be sufficiently short, or) point me to some resource to study and have an answer by myself?

Thank you all!
Corrado.

 Session info

> devtools::session_info()
─ Session info ─────────────────────────────────────────────────────────
 setting  value
 version  R version 4.2.2 Patched (2022-11-10 r83330)
 os       Ubuntu 22.04.1 LTS
 system   x86_64, linux-gnu
 ui       RStudio
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       Europe/Rome
 date     2022-12-23
 rstudio  2022.12.0+353 Elsbeth Geranium (desktop)
 pandoc   NA

─ Packages ─────────────────────────────────────────────────────────────
 ! package     * version date (UTC) lib source
   brio          1.1.3   2021-11-30 [1] RSPM (R 4.2.0)
   cachem        1.0.6   2021-08-19 [1] RSPM (R 4.2.0)
   callr         3.7.3   2022-11-02 [1] RSPM (R 4.2.0)
 P cli           3.5.0   2022-12-20 [?] RSPM (R 4.2.0)
 P crayon        1.5.2   2022-09-29 [?] CRAN (R 4.2.2)
 P desc          1.4.2   2022-09-08 [?] CRAN (R 4.2.2)
   devtools    * 2.4.5   2022-10-11 [1] RSPM (R 4.2.0)
   digest        0.6.31  2022-12-11 [1] RSPM (R 4.2.0)
   ellipsis      0.3.2   2021-04-29 [1] RSPM (R 4.2.0)
   fansi         1.0.3   2022-03-24 [1] RSPM (R 4.2.0)
   fastmap       1.1.0   2021-01-25 [1] RSPM (R 4.2.0)
 P fs            1.5.2   2021-12-08 [?] CRAN (R 4.2.2)
 P glue          1.6.2   2022-02-24 [?] CRAN (R 4.2.2)
 P here          1.0.1   2020-12-13 [?] CRAN (R 4.2.2)
   htmltools     0.5.4   2022-12-07 [1] RSPM (R 4.2.0)
   htmlwidgets   1.6.0   2022-12-15 [1] RSPM (R 4.2.0)
   httpuv        1.6.7   2022-12-14 [1] RSPM (R 4.2.0)
   later         1.3.0   2021-08-18 [1] RSPM (R 4.2.0)
 P lifecycle     1.0.3   2022-10-07 [?] CRAN (R 4.2.2)
 P magrittr      2.0.3   2022-03-30 [?] CRAN (R 4.2.2)
   memoise       2.0.1   2021-11-26 [1] RSPM (R 4.2.0)
 P mime          0.12    2021-09-28 [?] CRAN (R 4.2.2)
   miniUI        0.1.1.1 2018-05-18 [1] RSPM (R 4.2.0)
   pillar        1.8.1   2022-08-19 [1] RSPM (R 4.2.0)
   pkgbuild      1.4.0   2022-11-27 [1] RSPM (R 4.2.0)
   pkgload       1.3.2   2022-11-16 [1] RSPM (R 4.2.0)
   prettyunits   1.1.1   2020-01-24 [1] RSPM (R 4.2.0)
   processx      3.8.0   2022-10-26 [1] RSPM (R 4.2.0)
   profvis       0.3.7   2020-11-02 [1] RSPM (R 4.2.0)
   promises      1.2.0.1 2021-02-11 [1] RSPM (R 4.2.0)
   ps            1.7.2   2022-10-26 [1] RSPM (R 4.2.0)
 P purrr         1.0.0   2022-12-20 [?] RSPM (R 4.2.0)
 P R6            2.5.1   2021-08-19 [?] CRAN (R 4.2.2)
   Rcpp          1.0.9   2022-07-08 [1] RSPM (R 4.2.0)
   remotes       2.4.2   2021-11-30 [1] RSPM (R 4.2.0)
   renv          0.16.0  2022-09-29 [1] CRAN (R 4.2.2)
 P rlang         1.0.6   2022-09-24 [?] CRAN (R 4.2.2)
 P rprojroot     2.0.3   2022-04-02 [?] CRAN (R 4.2.2)
 P rstudioapi    0.14    2022-08-22 [?] CRAN (R 4.2.2)
   sessioninfo   1.2.2   2021-12-06 [1] RSPM (R 4.2.0)
   shiny         1.7.4   2022-12-15 [1] RSPM (R 4.2.0)
   stringi       1.7.8   2022-07-11 [1] RSPM (R 4.2.0)
   stringr       1.5.0   2022-12-02 [1] RSPM (R 4.2.0)
   testthat      3.1.6   2022-12-09 [1] RSPM (R 4.2.0)
   urlchecker    1.0.1   2021-11-30 [1] RSPM (R 4.2.0)
 P usethis     * 2.1.6   2022-05-25 [?] CRAN (R 4.2.2)
   utf8          1.2.2   2021-07-24 [1] RSPM (R 4.2.0)
 P vctrs         0.5.1   2022-11-16 [?] RSPM (R 4.2.0)
 P withr         2.5.0   2022-03-03 [?] CRAN (R 4.2.2)
   xtable        1.8-4   2019-04-21 [1] RSPM (R 4.2.0)

 [1] /home/cl/.cache/R/renv/library/local-04c28f88/R-4.2/x86_64-pc-linux-gnu
 [2] /home/cl/local/renv/sandbox/R-4.2/x86_64-pc-linux-gnu/9a444a72

 P ── Loaded and on-disk path mismatch.

────────────────────────────────────────────────────────────────────────


问:
Select a random row from database table (Mysql) which is not displayed in datagridview
I want to select a random row from MySql datatable and this table line should not be in Datagridview2 Rows counting on the id of this table which is displayed in datagridview reacords with other details .

is there any solution to this problem or any ideas that can help ?

```<code>private void SelectedArticleMin()

        {
            foreach (DataGridViewRow dgcRows in dataGridView2.Rows)
            {
                Random rnd = new Random();
                Random rnd2 = new Random();
                int OverOneMostly;
                string queryy = "select codeArt,Designation,Qtemin,qtemax,Puht,Puttc,tva from articletbl where codeArt not in (select codeArt from articletbl where codeArt='" + dgcRows.Cells[1].Value.ToString() + "') and pk_frn='" + SupplIdLbl.Text + "' and Puht<400  order by rand() limit 1";
                con = new MySqlConnection(conString);
                com = new MySqlCommand(queryy, con);
                con.Open();
                dr = com.ExecuteReader();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        ArtId = dr[0].ToString();
                        DesArticle = dr[1].ToString();
                        qmin = dr[2].ToString();
                        qmax = dr[3].ToString();
                        phtart = dr[4].ToString();
                        ttc = dr[5].ToString();
                        tva = dr[6].ToString();

                        if ((Convert.ToDecimal(phtart) * Convert.ToDecimal(tva)) / 100 + Convert.ToDecimal(phtart) <= 100)
                        {
                            OverOneMostly = rnd2.Next(1, 7);
                            GenQty = rnd.Next(Convert.ToInt16(OverOneMostly), 9).ToString();
                            TotalHtDet = (Convert.ToDecimal(phtart) * Convert.ToInt16(GenQty)).ToString("#,##");
                        }

                        if ((Convert.ToDecimal(phtart) * Convert.ToDecimal(tva)) / 100 + Convert.ToDecimal(phtart) > 100)
                        {
                            OverOneMostly = rnd2.Next(1, 2);
                            GenQty = rnd.Next(Convert.ToInt16(OverOneMostly), 3).ToString();
                            TotalHtDet = (Convert.ToDecimal(phtart) * Convert.ToInt16(GenQty)).ToString("#,##");
                        }

                    }

                    dataGridView2.Rows.Add(InvoiceIdLbl.Text, ArtId, DesArticle, phtart, GenQty, TotalHtDet);
                }
                else
                {
                    GenTimer.Stop();
                    rjButton1.PerformClick();

                }

                com.Dispose();
                dr.Close();
                con.Close();
            }

        }
</code>```

Body:
I want to select a random row from MySql datatable and this table line should not be in Datagridview2 Rows counting on the id of this table which is displayed in datagridview reacords with other details .

is there any solution to this problem or any ideas that can help ?

private void SelectedArticleMin()

        {
            foreach (DataGridViewRow dgcRows in dataGridView2.Rows)
            {
                Random rnd = new Random();
                Random rnd2 = new Random();
                int OverOneMostly;
                string queryy = "select codeArt,Designation,Qtemin,qtemax,Puht,Puttc,tva from articletbl where codeArt not in (select codeArt from articletbl where codeArt='" + dgcRows.Cells[1].Value.ToString() + "') and pk_frn='" + SupplIdLbl.Text + "' and Puht<400  order by rand() limit 1";
                con = new MySqlConnection(conString);
                com = new MySqlCommand(queryy, con);
                con.Open();
                dr = com.ExecuteReader();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        ArtId = dr[0].ToString();
                        DesArticle = dr[1].ToString();
                        qmin = dr[2].ToString();
                        qmax = dr[3].ToString();
                        phtart = dr[4].ToString();
                        ttc = dr[5].ToString();
                        tva = dr[6].ToString();

                        if ((Convert.ToDecimal(phtart) * Convert.ToDecimal(tva)) / 100 + Convert.ToDecimal(phtart) <= 100)
                        {
                            OverOneMostly = rnd2.Next(1, 7);
                            GenQty = rnd.Next(Convert.ToInt16(OverOneMostly), 9).ToString();
                            TotalHtDet = (Convert.ToDecimal(phtart) * Convert.ToInt16(GenQty)).ToString("#,##");
                        }

                        if ((Convert.ToDecimal(phtart) * Convert.ToDecimal(tva)) / 100 + Convert.ToDecimal(phtart) > 100)
                        {
                            OverOneMostly = rnd2.Next(1, 2);
                            GenQty = rnd.Next(Convert.ToInt16(OverOneMostly), 3).ToString();
                            TotalHtDet = (Convert.ToDecimal(phtart) * Convert.ToInt16(GenQty)).ToString("#,##");
                        }

                    }

                    dataGridView2.Rows.Add(InvoiceIdLbl.Text, ArtId, DesArticle, phtart, GenQty, TotalHtDet);
                }
                else
                {
                    GenTimer.Stop();
                    rjButton1.PerformClick();

                }

                com.Dispose();
                dr.Close();
                con.Close();
            }

        }


问:
Having trouble to set up SSH socks proxy
I am trying to set up a SSH socks tunnel for my personal use. When I am using this command ssh -D 1080 -N root@[server public IP] to start the proxy I am getting this error: open failed: administratively prohibited: open failed. Please help me.

Server SSHD Config:

```<code>tcpkeepalive yes
allowtcpforwarding yes
permitopen any
</code>```

Server Info: CentOS 7

Body:
I am trying to set up a SSH socks tunnel for my personal use. When I am using this command ssh -D 1080 -N root@[server public IP] to start the proxy I am getting this error: open failed: administratively prohibited: open failed. Please help me.

Server SSHD Config:

tcpkeepalive yes
allowtcpforwarding yes
permitopen any

Server Info: CentOS 7


问:
Loss for LSTM-Bayesian Neural Network
```<code>
</code>```

def NLL (y, distr):
return -distr.log_prob(y)

```<code>
prob_bnn1 = Sequential()
prob_bnn1.add(LSTM(128,input_shape=(187,1),activation='tanh',recurrent_activation='sigmoid',use_bias=True,dropout=0.0,recurrent_dropout=0.0,return_sequences=True,))
prob_bnn1.add(LSTM(128,activation='tanh',recurrent_activation='sigmoid',use_bias=True,dropout=0.0,recurrent_dropout=0.0,return_sequences=False,))
prob_bnn1.add(tfp.layers.DenseVariational(units=16,make_prior_fn=prior,make_posterior_fn=posterior,kl_weight=1 /len(X_TRAIN),activation="ReLU",kl_use_exact=True))
prob_bnn1.add(tfp.layers.DenseVariational(units=32,make_prior_fn=prior,make_posterior_fn=posterior,kl_weight=1 /len(X_TRAIN),activation="ReLU",kl_use_exact=True))
prob_bnn1.add(Dropout(0.5))
prob_bnn1.add(Flatten())
prob_bnn1.add(Dense(tfp.layers.IndependentBernoulli.params_size(1)))
prob_bnn1.add(tfp.layers.IndependentBernoulli(1))
</code>```
```<code>prob_bnn1.compile(optimizer=optimizer,loss= NLL,metrics = ["acc"])
</code>```
```<code>history_prob_bnn = prob_bnn1.fit(X_data,Y_data,validation_split=0.2, epochs = epochs, batch_size = 256,callbacks=[save_best_weights,EarlyStopping])
</code>```

which loss function is used? should we use only NLL or we have to add more loss. like binary cross entropy and if then how?

Title: Loss for LSTM-Bayesian Neural Network

Body:
def NLL (y, distr):
return -distr.log_prob(y)

prob_bnn1 = Sequential()
prob_bnn1.add(LSTM(128,input_shape=(187,1),activation='tanh',recurrent_activation='sigmoid',use_bias=True,dropout=0.0,recurrent_dropout=0.0,return_sequences=True,))
prob_bnn1.add(LSTM(128,activation='tanh',recurrent_activation='sigmoid',use_bias=True,dropout=0.0,recurrent_dropout=0.0,return_sequences=False,))
prob_bnn1.add(tfp.layers.DenseVariational(units=16,make_prior_fn=prior,make_posterior_fn=posterior,kl_weight=1 /len(X_TRAIN),activation="ReLU",kl_use_exact=True))
prob_bnn1.add(tfp.layers.DenseVariational(units=32,make_prior_fn=prior,make_posterior_fn=posterior,kl_weight=1 /len(X_TRAIN),activation="ReLU",kl_use_exact=True))
prob_bnn1.add(Dropout(0.5))
prob_bnn1.add(Flatten())
prob_bnn1.add(Dense(tfp.layers.IndependentBernoulli.params_size(1)))
prob_bnn1.add(tfp.layers.IndependentBernoulli(1))

prob_bnn1.compile(optimizer=optimizer,loss= NLL,metrics = ["acc"])

history_prob_bnn = prob_bnn1.fit(X_data,Y_data,validation_split=0.2, epochs = epochs, batch_size = 256,callbacks=[save_best_weights,EarlyStopping])

which loss function is used? should we use only NLL or we have to add more loss. like binary cross entropy and if then how?


问:
Setting table height fixed in multipage pdf
I am trying to create a multipage PDF but the problem is that height of the table is currently adjusted on the basis of content in it.
Tried using height and min-height attributes of CSS but it didn't work.

How do I keep the height of table fixed across all pages?

The second page doesn't has the same height as first page table

Demo

@page {
    size: 8.5in 11in;
    margin-top: 50mm;
    margin-bottom: 50mm;
    @top-center { content: element(header); }
    page-break-after: always;
     @bottom-center { content: element(footer) }
}
header {
    display: block; text-align: center;
    position: running(header);
}
footer {
    display: block; text-align: center;
    position: running(footer);
}
table {
    border: 1px;
    border-spacing: 0;
    clear: both;
    width: 100%;
    -fs-table-paginate: paginate;
    -fs-page-sequence: auto;
    page-break-after:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
    <head>
        <meta charset="utf-8">
            <title>Creating Fixed Header and Footer with CSS</title>
            <style></style>
  </head>
  <body>
    <div class="page">
      <header>
        <table border="2" width="100%">
          <thead>
            <tr style="height:100px">
              <br/>
              <th>------  Document  (HEADER) ------</th>
              <br/>
            </tr>
          </thead>
        </table>

      </header>

    </div>
    <div class='content'>
      <table border="2" width="100%">
        <thead>
          <tr>
            <th bgcolor="#C0C0C0">Header one</th>
            <th bgcolor="#C0C0C0">Header two</th>
            <th bgcolor="#C0C0C0">Header three</th>
          </tr>
        </thead>
        <tbody>
          <tr class="page-break">
            <td align="left" valign="top"/>
            <td align="left" valign="top">
              <p>
                    Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti nemo qui assumenda voluptates qui maxime provident qui reiciendis nostrum nam omnis perferendis id nemo dolorum. In perspiciatis nihil eum neque velit in culpa assumenda et enim possimus! Qui facilis inventore eos quam voluptate et repellendus error.
                  </p>
              <br/>
            </td>
            <td align="left" valign="top"/>
          </tr>
          <tr class="page-break">
            <td align="left" valign="top">Data</td>
            <td align="left" valign="top">
              <p>Lorem ipsum dolor sit amet</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
              <br/>
              <p>Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti</p>
            </td>
            <td align="left" valign="top">0.00</td>
          </tr>

        </tbody>

      </table>
    </div>
  </body>
</html></code>```

Body:
I am trying to create a multipage PDF but the problem is that height of the table is currently adjusted on the basis of content in it.
Tried using height and min-height attributes of CSS but it didn't work.

How do I keep the height of table fixed across all pages?

The second page doesn't has the same height as first page table

Demo

@page {
    size: 8.5in 11in;
    margin-top: 50mm;
    margin-bottom: 50mm;
    @top-center { content: element(header); }
    page-break-after: always;
     @bottom-center { content: element(footer) }
}
header {
    display: block; text-align: center;
    position: running(header);
}
footer {
    display: block; text-align: center;
    position: running(footer);
}
table {
    border: 1px;
    border-spacing: 0;
    clear: both;
    width: 100%;
    -fs-table-paginate: paginate;
    -fs-page-sequence: auto;
    page-break-after:auto;
}

        <meta charset="utf-8">
            <title>Creating Fixed Header and Footer with CSS</title>

              ------  Document  (HEADER) ------

            Header one
            Header two
            Header three

                    Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti nemo qui assumenda voluptates qui maxime provident qui reiciendis nostrum nam omnis perferendis id nemo dolorum. In perspiciatis nihil eum neque velit in culpa assumenda et enim possimus! Qui facilis inventore eos quam voluptate et repellendus error.

            Data

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

Lorem ipsum dolor sit amet. Ad ipsum rerum non deleniti

            0.00


问:
EntityExistsException occurs when using deleteAllinBatch and saveAll in the same transaction in JPA
EntityExistsException for deleteAllinBatch and saveAll in the same transaction in JPA.

I am flushing after delete, but the following error occurs due to duplicate primary key at save time.

Caused by: jakarta.persistence.EntityExistsException:

A different object with the same identifier value was already associated with the session :

[jp.co.hoge.entities.db.HogeEntitiy#HogeKey(
id1=000000001, id2=000000002)
]

```
<ul>
<li>DB Entity</li>
</ul>
<pre class="lang-java prettyprint-override"><code>package jp.co.hoge.entities;

import lombok.Data;
import org.springframework.data.domain.Persistable;

@Data
public abstract class BaseDbEntity<T> implements Persistable<T> {

    private boolean newFlag = true;

    @Override
    public boolean isNew() {
        return newFlag;
    }
}
</code>```

package jp.co.hoge.entities.db;

import jakarta.persistence.*;
import jp.co.hoge.entities.BaseDbEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.math.BigDecimal;

@Entity
@Table(name = "hoge_table")
@Data
@EqualsAndHashCode(callSuper=true)
@ToString(callSuper=true)
public class HogenEntitiy extends BaseDbEntity<HogeKey> {

    public HogenEntitiy() {
    }

    public HogenEntitiy(HogeKey primaryKey, String a, BigDecimal b) {
        this.primaryKey = primaryKey;
        this.a = a;
        this.b = b;
    }

    @EmbeddedId
    private HogeKey primaryKey;

    @Column(name = "A")
    private String a;

    @Column(name = "B")
    private BigDecimal b;

    @Override
    public HogeKey getId() {
        return this.primaryKey;
    }
}
```
<pre class="lang-java prettyprint-override"><code>@Embeddable
@Data
public class HogeKey implements Serializable {

    @Column(name = "id1", nullable = false)
    private String id1;

    @Column(name = "id2", nullable = false)
    private String id2;

}
</code>```

Repo

package jp.co.hoge.repositories.db;

import jp.co.hoge.entities.db.HogeEntitiy;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface HogeRepository extends JpaRepository<HogeEntitiy, String> {

}
```
<ul>
<li>Logic</li>
</ul>
<pre class="lang-java prettyprint-override"><code>    @Autowired
    private HogeRepository hogeRepository;
・
・
・
    @Transactional
    public void deleteAndSave(List<HogeEntitiy> entitiyList) throws Exception {

        hogeRepository.deleteAllInBatch();
        hogeRepository.flush();
        if(hogeRepository.count() == 0) {
            hogeRepository.saveAllAndFlush(entitiyList);
        }

}
</code>```

insert data

```<code>000000001, 000000002, a1, 1
000000001, 000000003, a2, 2
</code>```

Why do I get duplicate primary keys even though I flush after delete? is the reason why duplicate primary keys occur?

Body:
EntityExistsException for deleteAllinBatch and saveAll in the same transaction in JPA.

I am flushing after delete, but the following error occurs due to duplicate primary key at save time.

Caused by: jakarta.persistence.EntityExistsException:

A different object with the same identifier value was already associated with the session :

[jp.co.hoge.entities.db.HogeEntitiy#HogeKey(
id1=000000001, id2=000000002)
]

DB Entity

package jp.co.hoge.entities;

import lombok.Data;
import org.springframework.data.domain.Persistable;

@Data
public abstract class BaseDbEntity<T> implements Persistable<T> {

    private boolean newFlag = true;

    @Override
    public boolean isNew() {
        return newFlag;
    }
}

package jp.co.hoge.entities.db;

import jakarta.persistence.*;
import jp.co.hoge.entities.BaseDbEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.math.BigDecimal;

@Entity
@Table(name = "hoge_table")
@Data
@EqualsAndHashCode(callSuper=true)
@ToString(callSuper=true)
public class HogenEntitiy extends BaseDbEntity<HogeKey> {

    public HogenEntitiy() {
    }

    public HogenEntitiy(HogeKey primaryKey, String a, BigDecimal b) {
        this.primaryKey = primaryKey;
        this.a = a;
        this.b = b;
    }

    @EmbeddedId
    private HogeKey primaryKey;

    @Column(name = "A")
    private String a;

    @Column(name = "B")
    private BigDecimal b;

    @Override
    public HogeKey getId() {
        return this.primaryKey;
    }
}

@Embeddable
@Data
public class HogeKey implements Serializable {

    @Column(name = "id1", nullable = false)
    private String id1;

    @Column(name = "id2", nullable = false)
    private String id2;

}

Repo

package jp.co.hoge.repositories.db;

import jp.co.hoge.entities.db.HogeEntitiy;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface HogeRepository extends JpaRepository<HogeEntitiy, String> {

}

Logic

    @Autowired
    private HogeRepository hogeRepository;
・
・
・
    @Transactional
    public void deleteAndSave(List<HogeEntitiy> entitiyList) throws Exception {

        hogeRepository.deleteAllInBatch();
        hogeRepository.flush();
        if(hogeRepository.count() == 0) {
            hogeRepository.saveAllAndFlush(entitiyList);
        }

}

insert data

000000001, 000000002, a1, 1
000000001, 000000003, a2, 2

Why do I get duplicate primary keys even though I flush after delete? is the reason why duplicate primary keys occur?


问:
package.json run 2 git command on 1 script
Currently I have thiss script in my package.json:

```<code>"submodule-install": "git submodule add ../my-utils.git modules/my-utils --force",
"submodule-update": "git submodule update --init --force --recursive --remote",
</code>```

I need to add an extra git command, plus, I need to use some variable on it.

I need to git checkout to some specific branch according some environment defined on an external file, for instance a .env file.

Is there a way that I could do that?

My idea is something like:

```<code>"submodule-install": "git submodule add ../my-utils.git modules/my-utils --force && git checkout $ENV",
"submodule-update": "git submodule update --init --force --recursive --remote && git checkout $ENV",
</code>```

Where $ENV be an environment value taken from .env file.

Is that even possible?

Body:
Currently I have thiss script in my package.json:

"submodule-install": "git submodule add ../my-utils.git modules/my-utils --force",
"submodule-update": "git submodule update --init --force --recursive --remote",

I need to add an extra git command, plus, I need to use some variable on it.

I need to git checkout to some specific branch according some environment defined on an external file, for instance a .env file.

Is there a way that I could do that?

My idea is something like:

"submodule-install": "git submodule add ../my-utils.git modules/my-utils --force && git checkout $ENV",
"submodule-update": "git submodule update --init --force --recursive --remote && git checkout $ENV",

Where $ENV be an environment value taken from .env file.

Is that even possible?


问:
How can I create FAT JAR using maven without main class?
I try to create a library by creating a fat jar with maven in IntelliJ.
However, in that library I don't need main class because all methods and classes were tested with unit tests.
So, the main class is simply there because all java programs need it and if I delete it I would get an error.
How could I create a jar with dependencies (fat jar or uber jar) without main class?

I tried to use it with maven assembly plugin.


问:
How to mock private object method in google test?
I want to mock the private object method in Gmock. I had prepared a simplified example to describe what I want to achieve:

Foo class is calling some external library functions. I decided to create an interface that I can use later for tests.

Foo interface (Ifoo.h)

```<code>class IFoo {
    public:
       virtual ~IFoo() = default;
       virtual void foo_function() const = 0;
};
</code>```

(foo.h)

```<code>#include "Ifoo.h"

class Foo : public IFoo {
    public:
        virtual ~Foo() = default;
        void foo_function() const override {};
};
</code>```

(foo.cpp)

```<code>#include <iostream>
#include "foo.h"

void Foo::foo_function() const {
    std::cout<<"Foo function is calling some library function\n";
}
</code>```

Base class is my main class where all logic sits. As you see Foo obj is declared here as a private member (my design decision, tbh I am not sure if good, for sure problematic for tests).

base.h

```<code>#include "foo.h"

class Base {
    public:
       void caller() const {};
    private:
       Foo obj{};
};
</code>```

And problematic (for me) caller function:
base.cpp

```<code>#include <base.h>
#include <iostream>

void Base::caller() const
{
    std::cout << "Base class is calling foo class: " << std::endl;
    obj.foo_function();
}
</code>```

My goal is to test Base::caller() method using google test. I did mock for foo:

```<code>#include "Ifoo.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>

class MockFoo : public IFoo
{
    MOCK_METHOD(void, foo_function, (), (const override));
};
</code>```

And source file where I perform the test:

```<code>#include "mockFoo.h"
#include "base.h"

class BaseMock : public ::testing::Test
{
    public:
        Base base_obj{};
};

TEST_F(BaseMock, test1)
{
    MockFoo mocked_foo{};

    EXPECT_CALL(mocked_foo, foo_function()).Times(1);
    base_obj.caller();
}
</code>```

Base::caller() will be executed from my test so Foo::foo_function() also. The problem is that foo_function() won't be executed for mocked object but for a real one (since Base class has it as a private data member). Can you give me suggestions please how to make it possible to test and execute mocked function instead of real one?

Body:
I want to mock the private object method in Gmock. I had prepared a simplified example to describe what I want to achieve:

Foo class is calling some external library functions. I decided to create an interface that I can use later for tests.

Foo interface (Ifoo.h)

class IFoo {
    public:
       virtual ~IFoo() = default;
       virtual void foo_function() const = 0;
};

(foo.h)

#include "Ifoo.h"

class Foo : public IFoo {
    public:
        virtual ~Foo() = default;
        void foo_function() const override {};
};

(foo.cpp)

#include <iostream>
#include "foo.h"

void Foo::foo_function() const {
    std::cout<<"Foo function is calling some library function\n";
}

Base class is my main class where all logic sits. As you see Foo obj is declared here as a private member (my design decision, tbh I am not sure if good, for sure problematic for tests).

base.h

#include "foo.h"

class Base {
    public:
       void caller() const {};
    private:
       Foo obj{};
};

And problematic (for me) caller function:
base.cpp

#include <base.h>
#include <iostream>

void Base::caller() const
{
    std::cout << "Base class is calling foo class: " << std::endl;
    obj.foo_function();
}

My goal is to test Base::caller() method using google test. I did mock for foo:

#include "Ifoo.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>

class MockFoo : public IFoo
{
    MOCK_METHOD(void, foo_function, (), (const override));
};

And source file where I perform the test:

#include "mockFoo.h"
#include "base.h"

class BaseMock : public ::testing::Test
{
    public:
        Base base_obj{};
};

TEST_F(BaseMock, test1)
{
    MockFoo mocked_foo{};

    EXPECT_CALL(mocked_foo, foo_function()).Times(1);
    base_obj.caller();
}

Base::caller() will be executed from my test so Foo::foo_function() also. The problem is that foo_function() won't be executed for mocked object but for a real one (since Base class has it as a private data member). Can you give me suggestions please how to make it possible to test and execute mocked function instead of real one?


问:
Static website hosted in AWS S3 and CloudFront
I have hosted Static website in AWS S3 and CloudFront. website contexts is multiple pages. I do have a problem with distribution. For example i do have have domain example.cloudfront.net when i am accessing it from this domain no problem i can go there and click on every page that i have lets say i am in a main page and i click about and domain automatically becomes example.cloudfront.net/about/ when i cope this path and paste it in a new page it gives

```<code><Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
</code>```

not sure what is the issue. Is there anyone who could help?
Thank you

Tried to give permission to access multiple folder inside of the bucket individually and also for whole bucket. Tried to recreate everything from scratch if I missed something but nothing helps. We can not make bucket public FYI

Body:
I have hosted Static website in AWS S3 and CloudFront. website contexts is multiple pages. I do have a problem with distribution. For example i do have have domain example.cloudfront.net when i am accessing it from this domain no problem i can go there and click on every page that i have lets say i am in a main page and i click about and domain automatically becomes example.cloudfront.net/about/ when i cope this path and paste it in a new page it gives

<Error>
AccessDenied
<Message>Access Denied</Message>

not sure what is the issue. Is there anyone who could help?
Thank you

Tried to give permission to access multiple folder inside of the bucket individually and also for whole bucket. Tried to recreate everything from scratch if I missed something but nothing helps. We can not make bucket public FYI


问:
What is the correct call to find "Related Contacts" on a Salesforce Account?
I am trying to identify the correct field in Salesforce to be able to link a new "Contact" with their own "Account" to the "Related Contact" section of another "Account"."To do this I'm first trying establish how you can read the details on an "Account" and report on who the "Related Contacts" and the information held against them (if any).

I am using a GET request like this for example:

```<code>https://website.sandbox.my.salesforce.com/services/data/v56.0/query/?q=SELECT+Account_Id__c,Other_Contact_Names__c+from+Account+WHERE+Partner_Approved__c+=+true+AND+Type+=+'Developer'
</code>```

So I can return values for "Account_Id__c" and "Other_Contact_Names__c" just to prove the call is generally correct.  But I don't know how to pull the "Related Contacts" information in the Account.  I have looked under the Object Manager in Setup through all likely Objects and their related Fields, but I cannot find a Field Name for this.

Once I find this I hope to be able to POST information from another system to link a Contact to a specific Account as a "Related Contact".

I'd be grateful to hear from anyone with experience in doing this before.

Body:
I am trying to identify the correct field in Salesforce to be able to link a new "Contact" with their own "Account" to the "Related Contact" section of another "Account"."To do this I'm first trying establish how you can read the details on an "Account" and report on who the "Related Contacts" and the information held against them (if any).

I am using a GET request like this for example:

https://website.sandbox.my.salesforce.com/services/data/v56.0/query/?q=SELECT+Account_Id__c,Other_Contact_Names__c+from+Account+WHERE+Partner_Approved__c+=+true+AND+Type+=+'Developer'

So I can return values for "Account_Id__c" and "Other_Contact_Names__c" just to prove the call is generally correct.  But I don't know how to pull the "Related Contacts" information in the Account.  I have looked under the Object Manager in Setup through all likely Objects and their related Fields, but I cannot find a Field Name for this.

Once I find this I hope to be able to POST information from another system to link a Contact to a specific Account as a "Related Contact".

I'd be grateful to hear from anyone with experience in doing this before.


问:
How to Toggle between elements in Divi?
I need to know if here's a way to make an element appear and disappear when I click another element. I'm working with Divi, so I can't edit the HTML source. I can add CSS and Java Script f needed.

What I want to achieve is this:
When I click on my
, the
 should appear and disappear on every click.

```<code><article id="post-301">

    <h2 class="entry-title">Best Practices</h2>

      <div class="post-content"><div class="post-content-inner et_pb_blog_show_content">
               <p>The ten central child protection steps through which organizations will progress as part of the Aleinu campaign.</p>
</div></div>
</article>
</code>```

I tried adding this script, but didn't work at all:

```<code><script>
jQuery(function ($) {
    $( document ).ready(function() {
        $(".entry-title").on("click", function(){var x = document.getElementsByClassName(".post-content");
            if (x.style.display === "none") {
            x.style.display = "block";
            } else {
            x.style.display = "none";
};
});
});});)
</script>
</code>```

Title: How to Toggle between elements in Divi?

Body:
I need to know if here's a way to make an element appear and disappear when I click another element. I'm working with Divi, so I can't edit the HTML source. I can add CSS and Java Script f needed.

What I want to achieve is this:
When I click on my
, the
 should appear and disappear on every click.

Best Practices

The ten central child protection steps through which organizations will progress as part of the Aleinu campaign.

I tried adding this script, but didn't work at all:


问:
Element with higher z-index is still on the background of another elements
Here is me trying to hover over 'delete' popup button positioned absolute relatively to three dots to the left.

As you can see it ignores the delete button completely, even though I even explicitly added a higher z-index to it. It has the same effect with any other elements on the background, so I estimate that problem is somewhere in code relevant to 'delete' button and it's popover. There are no elements with sticky or fixed positioning in this project. Here is my JSX with TailwindCSS and Headless UI's Popover component:

```<code>Relative part of parent component.

<Disclosure.Panel className="w-full text-gray-900 flex flex-col" >
        {projects?.map(project => Object.keys(project).map(key => (
          <div className={`w-4/5 py-2 hover:font-medium cursor-pointer self-end pl-2 flex items-center justify-between ${selectedProject === key ? 'bg-gray-900 text-gray-50 font-medium' : ''}`} onClick={() => handleSelect(key)} key={key}>
            <p>{key}</p>
            <Popover className='relative z-100'>
              <Popover.Button className='flex items-center'><EllipsisHorizontalIcon className='w-8 h-6 pr-2 hover:text-zinc-400'/></Popover.Button>
              <ProjectSettingsPopover selectedProject={selectedProject} />
            </Popover>
          </div>
        )))}
        <div className="flex gap-2 h-7 mt-2 w-4/5 ml-auto">
          <input type='text' className='w-4/5 bg-background rounded-md px-2 py-1 text-sm border-2 border-grayDark' placeholder='New Project' value={input} onChange={(e) => setInput(e.target.value)}></input>
          <button className='bg-black p-1 rounded-full flex items-center justify-center hover:bg-zinc-700' onClick={() => handleNewProject()}><PlusCircleIcon className='text-primary h-5 w-5 group-hover:text-primaryDark'/></button>
        </div>
</Disclosure.Panel>

</code>```
```<code>ProjectSettingsPopover.js
return (
    <Transition
        enter="transition ease-out duration-200"
        enterFrom="opacity-0 -translate-x-1"
        enterTo="opacity-100 -translate-x-0"
        leave="transition ease-in duration-150"
        leaveFrom="opacity-100 -translate-x-0"
        leaveTo="opacity-0 -translate-x-1"
        appear
    >
        <Popover.Panel className="left-9 -top-8 w-24 text-sm z-50 rounded-sm flex flex-col absolute bg-background shadow-lg ring-1 border border-black ring-black ring-opacity-5">
            <Button btnStyle='default' btnSize='edgy' onClick={deleteProject}>delete</Button>
        </Popover.Panel>
    </Transition>
  )

</code>```

What is the reason of such a weird behavior?

Body:
Here is me trying to hover over 'delete' popup button positioned absolute relatively to three dots to the left.

As you can see it ignores the delete button completely, even though I even explicitly added a higher z-index to it. It has the same effect with any other elements on the background, so I estimate that problem is somewhere in code relevant to 'delete' button and it's popover. There are no elements with sticky or fixed positioning in this project. Here is my JSX with TailwindCSS and Headless UI's Popover component:

Relative part of parent component.

<Disclosure.Panel className="w-full text-gray-900 flex flex-col" >
        {projects?.map(project => Object.keys(project).map(key => (
          <div className={`w-4/5 py-2 hover:font-medium cursor-pointer self-end pl-2 flex items-center justify-between ${selectedProject === key ? 'bg-gray-900 text-gray-50 font-medium' : ''}`} onClick={() => handleSelect(key)} key={key}>

{key}

            <Popover className='relative z-100'>
              <Popover.Button className='flex items-center'><EllipsisHorizontalIcon className='w-8 h-6 pr-2 hover:text-zinc-400'/></Popover.Button>
              <ProjectSettingsPopover selectedProject={selectedProject} />
            </Popover>

        )))}

          <input type='text' className='w-4/5 bg-background rounded-md px-2 py-1 text-sm border-2 border-grayDark' placeholder='New Project' value={input} onChange={(e) => setInput(e.target.value)}></input>
          <button className='bg-black p-1 rounded-full flex items-center justify-center hover:bg-zinc-700' onClick={() => handleNewProject()}><PlusCircleIcon className='text-primary h-5 w-5 group-hover:text-primaryDark'/></button>

</Disclosure.Panel>

ProjectSettingsPopover.js
return (
    <Transition
        enter="transition ease-out duration-200"
        enterFrom="opacity-0 -translate-x-1"
        enterTo="opacity-100 -translate-x-0"
        leave="transition ease-in duration-150"
        leaveFrom="opacity-100 -translate-x-0"
        leaveTo="opacity-0 -translate-x-1"
        appear
    >
        <Popover.Panel className="left-9 -top-8 w-24 text-sm z-50 rounded-sm flex flex-col absolute bg-background shadow-lg ring-1 border border-black ring-black ring-opacity-5">
            <Button btnStyle='default' btnSize='edgy' onClick={deleteProject}>delete</Button>
        </Popover.Panel>
    </Transition>
  )

What is the reason of such a weird behavior?


问:
Using an external DLL in a Qt Project
I have a DLL containing multiple functions that can fastly perform arithmetic operations on extremely large integers. My test program runs smoothly in my Visual Studio 2019, as follows.

```<code>int main()
 {
    HINSTANCE myDDL = LoadLibrary(L".\\BigIntDLL.dll");
    typedef string (*func)(string a, string b);
    func expBigInt = (func)GetProcAddress(myDDL, "expBigInt");
    string y= expBigInt("2", "10000");//it can calculate 2^10000 and return it as a string
    cout << y;
}
</code>```

So, I moved the code directly into my Qt project as a part in widget.cpp, and also placed the BigIntDLL.dll and .lib in the same directory of the project. The compilation was successful, but when debugging my interface, the program broke with a Segmentation fault error due to a call to the expBigInt function.

```<code>void Widget::on_expButton_clicked()
{
    getTextEditNum();
    Output=expBigInt(Input1,Input2);//crashed here
    writeResult(Output);
}
</code>```

I am not really sure where the real problem is, but I now suspect that I have not successfully called the functions in this DLL, causing some memory issues.

Title: Using an external DLL in a Qt Project

Body:
I have a DLL containing multiple functions that can fastly perform arithmetic operations on extremely large integers. My test program runs smoothly in my Visual Studio 2019, as follows.

int main()
 {
    HINSTANCE myDDL = LoadLibrary(L".\\BigIntDLL.dll");
    typedef string (*func)(string a, string b);
    func expBigInt = (func)GetProcAddress(myDDL, "expBigInt");
    string y= expBigInt("2", "10000");//it can calculate 2^10000 and return it as a string
    cout << y;
}

So, I moved the code directly into my Qt project as a part in widget.cpp, and also placed the BigIntDLL.dll and .lib in the same directory of the project. The compilation was successful, but when debugging my interface, the program broke with a Segmentation fault error due to a call to the expBigInt function.

void Widget::on_expButton_clicked()
{
    getTextEditNum();
    Output=expBigInt(Input1,Input2);//crashed here
    writeResult(Output);
}

I am not really sure where the real problem is, but I now suspect that I have not successfully called the functions in this DLL, causing some memory issues.