问:
Change redirect target URL every X hours
I am wondering if there is a way I can code a website to redirect to a different target every 24 hours or so, we are wanting to use a referral code from EVE Online on our website, but we'd like it to redirect to a different link every 24 hours or so. This would give all directors a chance to get some rewards and not just one of us.

Is this something that is pssible at all? Or is this too far fetched.

Thanks in advance!

I tried to find the solutions on Google lol


来源: stackexchange

问:
How can I specify factor choice in Variable Importance Chart?
```<code>library(class)

fit <- rfsrc(as.factor(DEFAULT) ~ .,
             data = CD,
             ntree = 1000,
             importance = TRUE,
             nsplit = 5)

plot(fit)
</code>```

I'm trying to code a variable importance chart from the randomForestSRC package. I want to get results for All only. I can't find anything online or within the manual that could help me achieve that as All isn't part of the variable itself.

ContentLicense: CC BY-SA 4.0

Body:
library(class)

fit <- rfsrc(as.factor(DEFAULT) ~ .,
             data = CD,
             ntree = 1000,
             importance = TRUE,
             nsplit = 5)

plot(fit)

I'm trying to code a variable importance chart from the randomForestSRC package. I want to get results for All only. I can't find anything online or within the manual that could help me achieve that as All isn't part of the variable itself.


问:
How do I replace a routing table in the middle of simulation in NS3?
I'm new to ns3. I'd like to replace a default routing table to an another routing table in the middle of simulation.

How can I do that?

In this situation, some routing tables are prepared in advance manually and I'd like to apply one of them in the middle of simulation.

We can get a routing table by using  IPv4GlobalRoutingHelper::PopulateRoutingTables() first and the most of sample codes don't change the routing table during the simulation. So, I couldn't find no idea about my above question and I'd like to know how to do.


问:
CMake include libraries with executable
I am using CMake and trying to include libraries I use with the executable for distribution. One library I am using is boost for which I am using the statement

```<code>find_package(Boost REQUIRED thread filesystem)
</code>```

This works fine, but I cannot redistribute to a computer where boost is not installed.

I then tried to use fetch_content but when cpack generates the installer, the library files built still aren't included.

```<code>set(BOOST_INCLUDE_LIBRARIES thread filesystem)
set(BOOST_ENABLE_CMAKE ON)
FetchContent_Declare(build_boost GIT_REPOSITORY https://github.com/boostorg/boost.git GIT_TAG boost-1.80.0)
FetchContent_GetProperties(build_boost)
if(NOT build_boost_POPULATED)
    FetchContent_Populate(build_boost)
    add_subdirectory(${build_boost_SOURCE_DIR} ${build_boost_BINARY_DIR} EXCLUDE_FROM_ALL)
endif()
</code>```

How can I package the library files with the executable?

OwnerDisplayName: Vinay

Title: CMake include libraries with executable

Body:
I am using CMake and trying to include libraries I use with the executable for distribution. One library I am using is boost for which I am using the statement

find_package(Boost REQUIRED thread filesystem)

This works fine, but I cannot redistribute to a computer where boost is not installed.

I then tried to use fetch_content but when cpack generates the installer, the library files built still aren't included.

set(BOOST_INCLUDE_LIBRARIES thread filesystem)
set(BOOST_ENABLE_CMAKE ON)
FetchContent_Declare(build_boost GIT_REPOSITORY https://github.com/boostorg/boost.git GIT_TAG boost-1.80.0)
FetchContent_GetProperties(build_boost)
if(NOT build_boost_POPULATED)
    FetchContent_Populate(build_boost)
    add_subdirectory(${build_boost_SOURCE_DIR} ${build_boost_BINARY_DIR} EXCLUDE_FROM_ALL)
endif()

How can I package the library files with the executable?


问:
Trying to implement recursive koch function in Tkinter Python
I am trying to create a koch snowflake in python using tkinter. At the moment, here is the code I have come up with.

```<code>class koch_snowflake:
    def __init__(self, canv, x, y, canv_width, canv_length, depth, colour, width):
        self.canv = canv
        self.x = x
        self.y = y
        self.canv_width = canv_width
        self.canv_length = canv_length
        self.colour = colour
        self.depth = depth
        self.width = width

    def draw_line(self, x0, y0, x1, y1):
        self.canv.create_line(
            x0, y0, x1, y1, fill=self.colour, width=self.width)

    def rotate_points_60(self, xa, ya, xb, yb, angle):
        # uses the rotation matrix to calculate the coordinates of the apex of the triangle which is xc, yc

        sin, cos = math.sin(math.radians(angle)), math.cos(math.radians(angle))
        x_c = cos*(xb-xa)-sin*(yb-ya) + xa
        y_c = sin*(xb-xa)+cos*(yb-ya) + ya
        return x_c, y_c

    def trisection(self, x_0, y_0, x_1, y_1):
        # calculating one third and 2 thirds of the line segment (x_a, y_a) and (x_b, y_b)
        x_a = (2*x_0)/3 + x_1/3
        y_a = (2*y_0)/3 + y_1/3
        x_b = x_0/3 + (2*x_1)/3
        y_b = y_0/3 + (2*y_1)/3
        return x_a, y_a, x_b, y_b

    def first_iter(self):
        xa, ya, xb, yb = self.trisection(self.x, self.canv_length/2, 500, self.canv_length/2)

        xc, yc = self.rotate_points_60(xa, ya, xb, yb, -60)
        self.draw_line(self.x, self.y, xa, ya)
        self.draw_line(xa, ya, xc, yc)
        self.draw_line(xc, yc, xb, yb)
        self.draw_line(xb, yb, self.canv_width, self.y)

    #def koch(self, size):
        # base case
        #if self.depth == 0:
            #self.first_iter()
        # recursive case
        #else:
</code>```

The rotate_points, trisection and first_iteration work together perfectly to draw the first iteration of the koch snowflake as I have already tested it in my canvas, but I am confused about how to implement the function recursively for the other generations, so that it finds the trisection of the line segments, then does it smaller and smaller for each line segment. I would really appreciate some hint, or help to put me on the right path as I am feeling quite lost.

Body:
I am trying to create a koch snowflake in python using tkinter. At the moment, here is the code I have come up with.

class koch_snowflake:
    def __init__(self, canv, x, y, canv_width, canv_length, depth, colour, width):
        self.canv = canv
        self.x = x
        self.y = y
        self.canv_width = canv_width
        self.canv_length = canv_length
        self.colour = colour
        self.depth = depth
        self.width = width

    def draw_line(self, x0, y0, x1, y1):
        self.canv.create_line(
            x0, y0, x1, y1, fill=self.colour, width=self.width)

    def rotate_points_60(self, xa, ya, xb, yb, angle):
        # uses the rotation matrix to calculate the coordinates of the apex of the triangle which is xc, yc

        sin, cos = math.sin(math.radians(angle)), math.cos(math.radians(angle))
        x_c = cos*(xb-xa)-sin*(yb-ya) + xa
        y_c = sin*(xb-xa)+cos*(yb-ya) + ya
        return x_c, y_c

    def trisection(self, x_0, y_0, x_1, y_1):
        # calculating one third and 2 thirds of the line segment (x_a, y_a) and (x_b, y_b)
        x_a = (2*x_0)/3 + x_1/3
        y_a = (2*y_0)/3 + y_1/3
        x_b = x_0/3 + (2*x_1)/3
        y_b = y_0/3 + (2*y_1)/3
        return x_a, y_a, x_b, y_b

    def first_iter(self):
        xa, ya, xb, yb = self.trisection(self.x, self.canv_length/2, 500, self.canv_length/2)

        xc, yc = self.rotate_points_60(xa, ya, xb, yb, -60)
        self.draw_line(self.x, self.y, xa, ya)
        self.draw_line(xa, ya, xc, yc)
        self.draw_line(xc, yc, xb, yb)
        self.draw_line(xb, yb, self.canv_width, self.y)

    #def koch(self, size):
        # base case
        #if self.depth == 0:
            #self.first_iter()
        # recursive case
        #else:

The rotate_points, trisection and first_iteration work together perfectly to draw the first iteration of the koch snowflake as I have already tested it in my canvas, but I am confused about how to implement the function recursively for the other generations, so that it finds the trisection of the line segments, then does it smaller and smaller for each line segment. I would really appreciate some hint, or help to put me on the right path as I am feeling quite lost.


问:
How to merge two model in one fieldset in django admin module
I have two table like below

tableA

field1

field2

field3

tableB

field4

field5

Group 1

field1: textfield (tableA)

field3: textfield (tableA)

field5: textfield (tableB)

Group 2

field2: radiobutton (tableA)

field4: textfield (tableB)

I tried the solution like form inlines but I want the grouping of fields in one form, not a separate inline form.


问:
Where to do "huge" graph calculations - Flutter, php

I'm planning on doing an application that create the shortest possible path to some interest points.

Each point is an activity separated from the other by a distance (e.g. p1 --50m--> p2). Later there will be a wait time for each point so it'll look like p1(5) --50m--> p2(15)

The user chooses his points and then the app create the shortest possible path to do every point the less walk to do for the user.

To accomplish that I though using a weighted graph (maybe a search-tree or something else should be better, I'm open to suggestions).

My question is that what's the better (faster) between doing the calculation for the path search : directly in the app (Flutter - dart) or on the server and then the app shall go get the result there ?
Thanks for your help guys :D


问:
Pass args to a jar launched by a Kubernetes cron job
I have deployed a Kubernetes cron job that executes a java jar.

```<code>apiVersion: batch/v1
kind: CronJob
metadata:
  name: my-cron-job
  namespace: test
  labels:
    app: my-cron-job
    release: dev
    tiers: backend
spec:
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: app_name
              image: docker-image
              command: ["/bin/bash", "-c"]
              args:
                - |
                  java -jar /app.jar
              env:
                - name: USER
                  valueFrom:
                    secretKeyRef:
                      name: secrets
                      key: user
                - name: PASSWORD
                  valueFrom:
                    secretKeyRef:
                      name: secrets
                      key: pwd
              resources:
                requests:
                  memory: "20Mi"
                  cpu: "50m"
                limits:
                  memory: "20Mi"

  schedule: "0 0 * * *"
  concurrencyPolicy: Forbid
</code>```

For testing, I'd like to execute this cron job as a one time job while passing certain args to the java jar.

I was able to run the one time job using :

```<code>kubectl create job my-cron-job-manual --from=cronjob/my-cron-job
</code>```

but couldn't find a way to pass any dynamic args to the jar in a similar way to this :

```<code>java -Dtest_arg=XXXXX -jar /app.jar
</code>```

Can you please point me to directions I can investigate ? Maybe I'm missing something with Kubernetes / cron jobs ?

Thank you.

Body:
I have deployed a Kubernetes cron job that executes a java jar.

apiVersion: batch/v1
kind: CronJob
metadata:
  name: my-cron-job
  namespace: test
  labels:
    app: my-cron-job
    release: dev
    tiers: backend
spec:
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: app_name
              image: docker-image
              command: ["/bin/bash", "-c"]
              args:
                - |
                  java -jar /app.jar
              env:
                - name: USER
                  valueFrom:
                    secretKeyRef:
                      name: secrets
                      key: user
                - name: PASSWORD
                  valueFrom:
                    secretKeyRef:
                      name: secrets
                      key: pwd
              resources:
                requests:
                  memory: "20Mi"
                  cpu: "50m"
                limits:
                  memory: "20Mi"

  schedule: "0 0 * * *"
  concurrencyPolicy: Forbid

For testing, I'd like to execute this cron job as a one time job while passing certain args to the java jar.

I was able to run the one time job using :

kubectl create job my-cron-job-manual --from=cronjob/my-cron-job

but couldn't find a way to pass any dynamic args to the jar in a similar way to this :

java -Dtest_arg=XXXXX -jar /app.jar

Can you please point me to directions I can investigate ? Maybe I'm missing something with Kubernetes / cron jobs ?

Thank you.


问:
Checking equality of Arrays by values in c#
I WOULD LIKE TO AVOID USING LINQ IF POSSIBLE

I have a List<int[]> of 2 integers that represent coordinate pairs on a grid. Eg:

List<int[]> coords = new List<int[]> which grows and shrinks very often as it is iterated over. These values represent cells that are on fire (its a console-based burning forest simulator). As the fire spreads, I update the list and remove the previously burning list elements. My problem comes from having duplicate values, and being unable to rapidly check for this and get it fixed.

I have tried using coords.Distinct() but it did not work as int[] are not simple types, and I don't know C# well enough to start using LINQ and all that stuff and since this is due in a few days, I don't really have the time, patience, inclination or stress level to dive into it. I did try to get it to work, but it was equally ineffective.

public bool Equals(int[] x, int[] y)
{
     string stringx = string.Join(",", x);
     string stringy = string.Join(",", y);
     Console.WriteLine("x: " + stringx + "y: " + stringy);
     return stringx == stringy;
}
```
<p>Currently this is my equality checker, as it seemed that changing them to strings and then comparing them would be faster than checking if the 0th and 1st element of each array are equal, but still I am getting duplicates in my list.</p>
<p>I call the <code>Equals()</code> method like this:</p>
<pre class="lang-c prettyprint-override"><code>foreach (KeyValuePair<int[], char> entry in returns)
{
     if (entry.Value == 'x')
     {
        foreach (int[] burn in burnzones)
        {
           if (!Equals(burn, entry.Key))
           {
              newburns.Add(entry.Key);
           }
        }
     }
}
</code>```

returns is a dictionary of {coord, state (burning or not, represented as 'x'if burning), burnzones, is my list that is passed as a parameter into the function of List<int[]> typing and if it is both burning and not equal to an element already in the list, it gets added to a new list (newburns). It's a lot of code so I didn't want to include too much, but I'm happy to add anything that might clarify what is happening if there are gaps (I'm on about four hours of sleep from staying up last night trying to get this to work), so apologies.

Body:
I WOULD LIKE TO AVOID USING LINQ IF POSSIBLE

I have a List<int[]> of 2 integers that represent coordinate pairs on a grid. Eg:

List<int[]> coords = new List<int[]> which grows and shrinks very often as it is iterated over. These values represent cells that are on fire (its a console-based burning forest simulator). As the fire spreads, I update the list and remove the previously burning list elements. My problem comes from having duplicate values, and being unable to rapidly check for this and get it fixed.

I have tried using coords.Distinct() but it did not work as int[] are not simple types, and I don't know C# well enough to start using LINQ and all that stuff and since this is due in a few days, I don't really have the time, patience, inclination or stress level to dive into it. I did try to get it to work, but it was equally ineffective.

public bool Equals(int[] x, int[] y)
{
     string stringx = string.Join(",", x);
     string stringy = string.Join(",", y);
     Console.WriteLine("x: " + stringx + "y: " + stringy);
     return stringx == stringy;
}

Currently this is my equality checker, as it seemed that changing them to strings and then comparing them would be faster than checking if the 0th and 1st element of each array are equal, but still I am getting duplicates in my list.

I call the Equals() method like this:

foreach (KeyValuePair<int[], char> entry in returns)
{
     if (entry.Value == 'x')
     {
        foreach (int[] burn in burnzones)
        {
           if (!Equals(burn, entry.Key))
           {
              newburns.Add(entry.Key);
           }
        }
     }
}

returns is a dictionary of {coord, state (burning or not, represented as 'x'if burning), burnzones, is my list that is passed as a parameter into the function of List<int[]> typing and if it is both burning and not equal to an element already in the list, it gets added to a new list (newburns). It's a lot of code so I didn't want to include too much, but I'm happy to add anything that might clarify what is happening if there are gaps (I'm on about four hours of sleep from staying up last night trying to get this to work), so apologies.


问:
Order column datatable
I am want to order columns but keep the actual order of the table

```<code>var table = $('table1').Datatables({
  "order": [[ 3, 'desc' ],[4, 'desc']],
  "pageLength": 100,
  "lengthMenu": [ 50, 100, 200, 300, 500 ],
  "rowGroup":{
    "dataSrc": 'week',
    "startRender": function( rows, group ){
        return 'Week ' + group
    }
  },
  "columns": [
      {
        "name": "first_name",
        "title": "First name",
        "data": "first_name",
        "searchable": true
      }
      ,{
        "name": "second_name",
        "title": "Second name",
        "data": "second_name",
        "searchable": true
      }
      ,{
        "name": "email",
        "title": "Email",
        "data": "email",
        "searchable": true
      }
      ,{
        "name": "added_on",
        "title": "Date",
        "data": "added_on",
        "searchable": true,
        "visible": false
      }
      ,{
        "name": "week",
        "title": "Week",
        "data": "week",
        "searchable": true,
        "visible": false
      }
    ]//end columns
  })
</code>```

I order the table by added_on desc and week desc, but when I click first_name I want to order by added_on desc and week desc and first name on click to be asc and desc, how can I achive that cause with orderData is not working

Title: Order column datatable

Body:
I am want to order columns but keep the actual order of the table

var table = $('table1').Datatables({
  "order": [[ 3, 'desc' ],[4, 'desc']],
  "pageLength": 100,
  "lengthMenu": [ 50, 100, 200, 300, 500 ],
  "rowGroup":{
    "dataSrc": 'week',
    "startRender": function( rows, group ){
        return 'Week ' + group
    }
  },
  "columns": [
      {
        "name": "first_name",
        "title": "First name",
        "data": "first_name",
        "searchable": true
      }
      ,{
        "name": "second_name",
        "title": "Second name",
        "data": "second_name",
        "searchable": true
      }
      ,{
        "name": "email",
        "title": "Email",
        "data": "email",
        "searchable": true
      }
      ,{
        "name": "added_on",
        "title": "Date",
        "data": "added_on",
        "searchable": true,
        "visible": false
      }
      ,{
        "name": "week",
        "title": "Week",
        "data": "week",
        "searchable": true,
        "visible": false
      }
    ]//end columns
  })

I order the table by added_on desc and week desc, but when I click first_name I want to order by added_on desc and week desc and first name on click to be asc and desc, how can I achive that cause with orderData is not working


问:
Create An Account That Has Registered Can Not Register Again(Express.js)
so my case is when someone with same email register he can't re-register because there is same email in database.
Logically, the email is checked, especially if the email is not registered, the registration is continued and if the email has been registered, the message "User has been registered before" will appear.
Any suggestions for making this program?

Here my code Register

```<code>export const createUser = async (req, res) => {
    const {name, email, password, confPassword, number, role} = req.body;
    const user = await User.findOne({
        where : {
            email: req.body.email
        }
    });
    if (!user) return res.status(404).json({msg: "User has been register before"});
    if (password !== confPassword) return res.status(400).json({msg: 'Password Tidak Sama!!'});
    const hashPassword = await argon2.hash(password);
    try{
        await User.create({
            name: name,
            email: email,
            password: hashPassword,
            number: number,
            role: role
        });

        const transporter = nodemailer.createTransport({
            service: "gmail",
            auth: {
                user: process.env.EMAIL,
                pass: process.env.PASSWORD,
            },
        });
        const mailOptions = {
            from: process.env.EMAIL,
            to: email,
            subject: "Register Telah Berhasil",
            html: `<h1>Selamat Bergabung</h1>`,
        };
        transporter.sendMail(mailOptions, (err, info) => {
            if (err) {
                console.log(err);
            } else {
                console.log(`Email sent: ${info.response}`);
            }
        });

        res.status(201).json({msg: "Registrasi Berhasil!!"});
    } catch (error){
        res.status(400).json(error);
    }
}
</code>```

Body:
so my case is when someone with same email register he can't re-register because there is same email in database.
Logically, the email is checked, especially if the email is not registered, the registration is continued and if the email has been registered, the message "User has been registered before" will appear.
Any suggestions for making this program?

Here my code Register

export const createUser = async (req, res) => {
    const {name, email, password, confPassword, number, role} = req.body;
    const user = await User.findOne({
        where : {
            email: req.body.email
        }
    });
    if (!user) return res.status(404).json({msg: "User has been register before"});
    if (password !== confPassword) return res.status(400).json({msg: 'Password Tidak Sama!!'});
    const hashPassword = await argon2.hash(password);
    try{
        await User.create({
            name: name,
            email: email,
            password: hashPassword,
            number: number,
            role: role
        });

        const transporter = nodemailer.createTransport({
            service: "gmail",
            auth: {
                user: process.env.EMAIL,
                pass: process.env.PASSWORD,
            },
        });
        const mailOptions = {
            from: process.env.EMAIL,
            to: email,
            subject: "Register Telah Berhasil",
            html: `<h1>Selamat Bergabung</h1>`,
        };
        transporter.sendMail(mailOptions, (err, info) => {
            if (err) {
                console.log(err);
            } else {
                console.log(`Email sent: ${info.response}`);
            }
        });

        res.status(201).json({msg: "Registrasi Berhasil!!"});
    } catch (error){
        res.status(400).json(error);
    }
}


问:
Pipe file bigger than 64Kb and get the size and send it to char *
I am trying to create a simple program using pipes, even though that are easier options for the same task (fopen(), lseek(), ftell(), etc).

First I use execve() to perform a terminal cat, and send the information through the pipe so I may be able to print the size of the file descriptor and read it to a malloc'd char pointer. My solution is this one:

```<code>#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <fcntl.h>

int main (int argc, char *argv[]) {

    int fd[2], active;
    int pipe_sz = 0;
    char *name;

    pipe(fd);

    //change /bin/cat according to your system
    char *cmd[] = {"/bin/cat", "example.txt", NULL};

    if (fork() == 0) {

        //CHILD
        dup2(fd[1], STDOUT_FILENO);
        close(fd[1]);

        active = execve(cmd[0], cmd, NULL);

    } else {

        //PARENT
        wait(NULL);

        int ioctl_sz = ioctl(fd[0], FIONREAD, &pipe_sz);

        name = malloc(pipe_sz + 1);
        int result = read(fd[0], name, pipe_sz);
        name[pipe_sz] = '\0';

        printf("LEN NAME: %ld\n", strlen(name));

        close(fd[0]);
        close(fd[1]);

    }

    return 0;

}
</code>```

Everything works fine as long as I keep myself inside the pipe's limits (my LINUX system is able to hold 65536 bytes). I decided to push the limits, and see what could happen. As expected, the program stays stuck when my file was above 65536 bytes.

I do not want to manually change my pipe's limits through fcntl(pipefd, F_SETPIPE_SZ, size) (since I "don't know" my file's size). Therefore, I researched, and came across the pipe2(pipefd, O_NONBLOCK) in order to avoid my pipe from stopping the reading process. Unfortunately, I received only this message:

```<code>/bin/cat: write error: Resource temporarily unavailable
</code>```

I even tried a while loop read() and realloc() to see if my code could at least give the char pointer result, but I was not successful, and part of file was lost.

Is it possible to produce a code that may provide the same results as mine above with files bigger than 65536 bytes?
Is there a way to interrupt the pipe if it takes too long to finish the process? Or even make a while loop to guess and resize the pipe through
fcntl()?

Thanks everyone for the help!

Body:
I am trying to create a simple program using pipes, even though that are easier options for the same task (fopen(), lseek(), ftell(), etc).

First I use execve() to perform a terminal cat, and send the information through the pipe so I may be able to print the size of the file descriptor and read it to a malloc'd char pointer. My solution is this one:

#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <fcntl.h>

int main (int argc, char *argv[]) {

    int fd[2], active;
    int pipe_sz = 0;
    char *name;

    pipe(fd);

    //change /bin/cat according to your system
    char *cmd[] = {"/bin/cat", "example.txt", NULL};

    if (fork() == 0) {

        //CHILD
        dup2(fd[1], STDOUT_FILENO);
        close(fd[1]);

        active = execve(cmd[0], cmd, NULL);

    } else {

        //PARENT
        wait(NULL);

        int ioctl_sz = ioctl(fd[0], FIONREAD, &pipe_sz);

        name = malloc(pipe_sz + 1);
        int result = read(fd[0], name, pipe_sz);
        name[pipe_sz] = '\0';

        printf("LEN NAME: %ld\n", strlen(name));

        close(fd[0]);
        close(fd[1]);

    }

    return 0;

}

Everything works fine as long as I keep myself inside the pipe's limits (my LINUX system is able to hold 65536 bytes). I decided to push the limits, and see what could happen. As expected, the program stays stuck when my file was above 65536 bytes.

I do not want to manually change my pipe's limits through fcntl(pipefd, F_SETPIPE_SZ, size) (since I "don't know" my file's size). Therefore, I researched, and came across the pipe2(pipefd, O_NONBLOCK) in order to avoid my pipe from stopping the reading process. Unfortunately, I received only this message:

/bin/cat: write error: Resource temporarily unavailable

I even tried a while loop read() and realloc() to see if my code could at least give the char pointer result, but I was not successful, and part of file was lost.

Is it possible to produce a code that may provide the same results as mine above with files bigger than 65536 bytes?
Is there a way to interrupt the pipe if it takes too long to finish the process? Or even make a while loop to guess and resize the pipe through
fcntl()?

Thanks everyone for the help!


问:
How to use react google charts with dynamic data from rest api using react hooks?
I have tried the following way :
the state of the graph :

```<code>const [datalinechart, setDataLineChart] = useState([]);
</code>```

taking the data from the api rest :

```<code>const loadingServices = () => {
    axios.get('/services')
        .then((res) => {
            console.log('res services : ', res.data.data);
            setServices(res.data.data);
            setDataLineChart(res.data.data)
            setServicesLength(res.data.data.length)
        })
        .catch((err) => console.log('err service : ', err))
        .finally();
}
</code>```

I am using the graph as follows :

```<code><Chart
                                chartType="LineChart"
                                width="100%"
                                height="400px"
                                data={[
                                    ['name'],
                                    [datalinechart.map(d => [d.name])]
                                ]}
                                options={optionslinechart}
                            />
</code>```

Body:
I have tried the following way :
the state of the graph :

const [datalinechart, setDataLineChart] = useState([]);

taking the data from the api rest :

const loadingServices = () => {
    axios.get('/services')
        .then((res) => {
            console.log('res services : ', res.data.data);
            setServices(res.data.data);
            setDataLineChart(res.data.data)
            setServicesLength(res.data.data.length)
        })
        .catch((err) => console.log('err service : ', err))
        .finally();
}

I am using the graph as follows :

<Chart
                                chartType="LineChart"
                                width="100%"
                                height="400px"
                                data={[
                                    ['name'],
                                    [datalinechart.map(d => [d.name])]
                                ]}
                                options={optionslinechart}
                            />


问:
Cannot calculate reliability for diary data
I did a diary study and people had to answer to 2 times a day for 5 days.
They had to answer in the morning and in the afternoon, and the variables used in both assessments were different (for instance: in the morning I asked about sleeping problems from the night before, in the afternoon I did not ask about sleeping problems).

I joined both databases for morning and afternoon.
I was trying to calculate the reliability for each variable (calculating RkF), but I always get the same error.

```<code>I was trying to calculate Sleeping Problems:

I put:

base_w_final = dataset
code= the code they had to create before fulfilling each assessment
register_ the day (day 1, day 2, day 3, day 4 and day 5).
items= columns 20 to 24 correspond to the columns for sleeping problems.

library(psych)
mlr(base_w_final, grp = "code", Time = "register", items = c(20:24))

</code>```

At least one item had no variance  when finding alpha for subject = 1. Proceed with caution
At least one item had no variance  when finding alpha for subject = 2. Proceed with caution
At least one item had no variance  when finding alpha for subject = 3. Proceed with caution
At least one item had no variance  when finding alpha for subject = 5. Proceed with caution
At least one item had no variance  when finding alpha for subject = 6. Proceed with caution
At least one item had no variance  when finding alpha for subject = 7. Proceed with caution
At least one item had no variance  when finding alpha for subject = 8. Proceed with caution
At least one item had no variance  when finding alpha for subject = 9. Proceed with caution
At least one item had no variance  when finding alpha for subject = 10. Proceed with caution
At least one item had no variance  when finding alpha for subject = 11. Proceed with caution
At least one item had no variance  when finding alpha for subject = 13. Proceed with caution
At least one item had no variance  when finding alpha for subject = 15. Proceed with caution
At least one item had no variance  when finding alpha for subject = 16. Proceed with caution
At least one item had no variance  when finding alpha for subject = 17. Proceed with caution
At least one item had no variance  when finding alpha for subject = 18. Proceed with caution
At least one item had no variance  when finding alpha for subject = 19. Proceed with caution
At least one item had no variance  when finding alpha for subject = 20. Proceed with caution
At least one item had no variance  when finding alpha for subject = 21. Proceed with caution
At least one item had no variance  when finding alpha for subject = 23. Proceed with caution
At least one item had no variance  when finding alpha for subject = 24. Proceed with caution
At least one item had no variance  when finding alpha for subject = 25. Proceed with caution
At least one item had no variance  when finding alpha for subject = 27. Proceed with caution
At least one item had no variance  when finding alpha for subject = 29. Proceed with caution
At least one item had no variance  when finding alpha for subject = 30. Proceed with caution
At least one item had no variance  when finding alpha for subject = 33. Proceed with caution
At least one item had no variance  when finding alpha for subject = 34. Proceed with caution
At least one item had no variance  when finding alpha for subject = 37. Proceed with caution
At least one item had no variance  when finding alpha for subject = 38. Proceed with caution
At least one item had no variance  when finding alpha for subject = 40. Proceed with caution
At least one item had no variance  when finding alpha for subject = 41. Proceed with caution
At least one item had no variance  when finding alpha for subject = 42. Proceed with caution
At least one item had no variance  when finding alpha for subject = 43. Proceed with caution
At least one item had no variance  when finding alpha for subject = 44. Proceed with caution
At least one item had no variance  when finding alpha for subject = 45. Proceed with caution
At least one item had no variance  when finding alpha for subject = 47. Proceed with caution
At least one item had no variance  when finding alpha for subject = 49. Proceed with caution
At least one item had no variance  when finding alpha for subject = 51. Proceed with caution
At least one item had no variance  when finding alpha for subject = 52. Proceed with caution
At least one item had no variance  when finding alpha for subject = 53. Proceed with caution
At least one item had no variance  when finding alpha for subject = 55. Proceed with caution
At least one item had no variance  when finding alpha for subject = 56. Proceed with caution
At least one item had no variance  when finding alpha for subject = 57. Proceed with caution
At least one item had no variance  when finding alpha for subject = 58. Proceed with caution
At least one item had no variance  when finding alpha for subject = 59. Proceed with caution
At least one item had no variance  when finding alpha for subject = 60. Proceed with caution
At least one item had no variance  when finding alpha for subject = 63. Proceed with caution
At least one item had no variance  when finding alpha for subject = 64. Proceed with caution
At least one item had no variance  when finding alpha for subject = 65. Proceed with caution
At least one item had no variance  when finding alpha for subject = 66. Proceed with caution
At least one item had no variance  when finding alpha for subject = 67. Proceed with caution
At least one item had no variance  when finding alpha for subject = 69. Proceed with caution
At least one item had no variance  when finding alpha for subject = 70. Proceed with caution
At least one item had no variance  when finding alpha for subject = 71. Proceed with caution
At least one item had no variance  when finding alpha for subject = 72. Proceed with caution
At least one item had no variance  when finding alpha for subject = 73. Proceed with caution
At least one item had no variance  when finding alpha for subject = 77. Proceed with caution
At least one item had no variance  when finding alpha for subject = 78. Proceed with caution
At least one item had no variance  when finding alpha for subject = 80. Proceed with caution
At least one item had no variance  when finding alpha for subject = 81. Proceed with caution
At least one item had no variance  when finding alpha for subject = 82. Proceed with caution
At least one item had no variance  when finding alpha for subject = 84. Proceed with caution
At least one item had no variance  when finding alpha for subject = 85. Proceed with caution
At least one item had no variance  when finding alpha for subject = 86. Proceed with caution
At least one item had no variance  when finding alpha for subject = 87. Proceed with caution
At least one item had no variance  when finding alpha for subject = 89. Proceed with caution
At least one item had no variance  when finding alpha for subject = 91. Proceed with caution
At least one item had no variance  when finding alpha for subject = 93. Proceed with caution
At least one item had no variance  when finding alpha for subject = 96. Proceed with caution
At least one item had no variance  when finding alpha for subject = 98. Proceed with caution
At least one item had no variance  when finding alpha for subject = 99. Proceed with caution
At least one item had no variance  when finding alpha for subject = 103. Proceed with caution
At least one item had no variance  when finding alpha for subject = 105. Proceed with caution
At least one item had no variance  when finding alpha for subject = 106. Proceed with caution
At least one item had no variance  when finding alpha for subject = 107. Proceed with caution
At least one item had no variance  when finding alpha for subject = 110. Proceed with caution
At least one item had no variance  when finding alpha for subject = 112. Proceed with caution
At least one item had no variance  when finding alpha for subject = 113. Proceed with caution
At least one item had no variance  when finding alpha for subject = 114. Proceed with caution
At least one item had no variance  when finding alpha for subject = 115. Proceed with caution
At least one item had no variance  when finding alpha for subject = 116. Proceed with caution
At least one item had no variance  when finding alpha for subject = 118. Proceed with caution
At least one item had no variance  when finding alpha for subject = 120. Proceed with caution
At least one item had no variance  when finding alpha for subject = 121. Proceed with caution
At least one item had no variance  when finding alpha for subject = 123. Proceed with caution
At least one item had no variance  when finding alpha for subject = 125. Proceed with caution
At least one item had no variance  when finding alpha for subject = 127. Proceed with caution
At least one item had no variance  when finding alpha for subject = 128. Proceed with caution
At least one item had no variance  when finding alpha for subject = 130. Proceed with caution
At least one item had no variance  when finding alpha for subject = 131. Proceed with caution
At least one item had no variance  when finding alpha for subject = 132. Proceed with caution
At least one item had no variance  when finding alpha for subject = 134. Proceed with caution
At least one item had no variance  when finding alpha for subject = 135. Proceed with caution
Error in dimnames(x) <- dn :
length of 'dimnames' [1] not equal to array extent
In addition: There were 50 or more warnings (use warnings() to see the first 50)

```<code>

I think this is due to the fact that I have NA values when it´s the afternoon assessments. But I tried to sperate the datasets (have 1 for the morning assessments and have 1 for the afternoon assessments) and calculate then, but I still get errors.
If I keep the same database, is there any possibility to tell RStudio to dismiss missing values or do you think the error has nothing to do with that?

Thank you so much for all the help!
</code>```

Body:
I did a diary study and people had to answer to 2 times a day for 5 days.
They had to answer in the morning and in the afternoon, and the variables used in both assessments were different (for instance: in the morning I asked about sleeping problems from the night before, in the afternoon I did not ask about sleeping problems).

I joined both databases for morning and afternoon.
I was trying to calculate the reliability for each variable (calculating RkF), but I always get the same error.

I was trying to calculate Sleeping Problems:

I put:

base_w_final = dataset
code= the code they had to create before fulfilling each assessment
register_ the day (day 1, day 2, day 3, day 4 and day 5).
items= columns 20 to 24 correspond to the columns for sleeping problems.

library(psych)
mlr(base_w_final, grp = "code", Time = "register", items = c(20:24))

At least one item had no variance  when finding alpha for subject = 1. Proceed with caution
At least one item had no variance  when finding alpha for subject = 2. Proceed with caution
At least one item had no variance  when finding alpha for subject = 3. Proceed with caution
At least one item had no variance  when finding alpha for subject = 5. Proceed with caution
At least one item had no variance  when finding alpha for subject = 6. Proceed with caution
At least one item had no variance  when finding alpha for subject = 7. Proceed with caution
At least one item had no variance  when finding alpha for subject = 8. Proceed with caution
At least one item had no variance  when finding alpha for subject = 9. Proceed with caution
At least one item had no variance  when finding alpha for subject = 10. Proceed with caution
At least one item had no variance  when finding alpha for subject = 11. Proceed with caution
At least one item had no variance  when finding alpha for subject = 13. Proceed with caution
At least one item had no variance  when finding alpha for subject = 15. Proceed with caution
At least one item had no variance  when finding alpha for subject = 16. Proceed with caution
At least one item had no variance  when finding alpha for subject = 17. Proceed with caution
At least one item had no variance  when finding alpha for subject = 18. Proceed with caution
At least one item had no variance  when finding alpha for subject = 19. Proceed with caution
At least one item had no variance  when finding alpha for subject = 20. Proceed with caution
At least one item had no variance  when finding alpha for subject = 21. Proceed with caution
At least one item had no variance  when finding alpha for subject = 23. Proceed with caution
At least one item had no variance  when finding alpha for subject = 24. Proceed with caution
At least one item had no variance  when finding alpha for subject = 25. Proceed with caution
At least one item had no variance  when finding alpha for subject = 27. Proceed with caution
At least one item had no variance  when finding alpha for subject = 29. Proceed with caution
At least one item had no variance  when finding alpha for subject = 30. Proceed with caution
At least one item had no variance  when finding alpha for subject = 33. Proceed with caution
At least one item had no variance  when finding alpha for subject = 34. Proceed with caution
At least one item had no variance  when finding alpha for subject = 37. Proceed with caution
At least one item had no variance  when finding alpha for subject = 38. Proceed with caution
At least one item had no variance  when finding alpha for subject = 40. Proceed with caution
At least one item had no variance  when finding alpha for subject = 41. Proceed with caution
At least one item had no variance  when finding alpha for subject = 42. Proceed with caution
At least one item had no variance  when finding alpha for subject = 43. Proceed with caution
At least one item had no variance  when finding alpha for subject = 44. Proceed with caution
At least one item had no variance  when finding alpha for subject = 45. Proceed with caution
At least one item had no variance  when finding alpha for subject = 47. Proceed with caution
At least one item had no variance  when finding alpha for subject = 49. Proceed with caution
At least one item had no variance  when finding alpha for subject = 51. Proceed with caution
At least one item had no variance  when finding alpha for subject = 52. Proceed with caution
At least one item had no variance  when finding alpha for subject = 53. Proceed with caution
At least one item had no variance  when finding alpha for subject = 55. Proceed with caution
At least one item had no variance  when finding alpha for subject = 56. Proceed with caution
At least one item had no variance  when finding alpha for subject = 57. Proceed with caution
At least one item had no variance  when finding alpha for subject = 58. Proceed with caution
At least one item had no variance  when finding alpha for subject = 59. Proceed with caution
At least one item had no variance  when finding alpha for subject = 60. Proceed with caution
At least one item had no variance  when finding alpha for subject = 63. Proceed with caution
At least one item had no variance  when finding alpha for subject = 64. Proceed with caution
At least one item had no variance  when finding alpha for subject = 65. Proceed with caution
At least one item had no variance  when finding alpha for subject = 66. Proceed with caution
At least one item had no variance  when finding alpha for subject = 67. Proceed with caution
At least one item had no variance  when finding alpha for subject = 69. Proceed with caution
At least one item had no variance  when finding alpha for subject = 70. Proceed with caution
At least one item had no variance  when finding alpha for subject = 71. Proceed with caution
At least one item had no variance  when finding alpha for subject = 72. Proceed with caution
At least one item had no variance  when finding alpha for subject = 73. Proceed with caution
At least one item had no variance  when finding alpha for subject = 77. Proceed with caution
At least one item had no variance  when finding alpha for subject = 78. Proceed with caution
At least one item had no variance  when finding alpha for subject = 80. Proceed with caution
At least one item had no variance  when finding alpha for subject = 81. Proceed with caution
At least one item had no variance  when finding alpha for subject = 82. Proceed with caution
At least one item had no variance  when finding alpha for subject = 84. Proceed with caution
At least one item had no variance  when finding alpha for subject = 85. Proceed with caution
At least one item had no variance  when finding alpha for subject = 86. Proceed with caution
At least one item had no variance  when finding alpha for subject = 87. Proceed with caution
At least one item had no variance  when finding alpha for subject = 89. Proceed with caution
At least one item had no variance  when finding alpha for subject = 91. Proceed with caution
At least one item had no variance  when finding alpha for subject = 93. Proceed with caution
At least one item had no variance  when finding alpha for subject = 96. Proceed with caution
At least one item had no variance  when finding alpha for subject = 98. Proceed with caution
At least one item had no variance  when finding alpha for subject = 99. Proceed with caution
At least one item had no variance  when finding alpha for subject = 103. Proceed with caution
At least one item had no variance  when finding alpha for subject = 105. Proceed with caution
At least one item had no variance  when finding alpha for subject = 106. Proceed with caution
At least one item had no variance  when finding alpha for subject = 107. Proceed with caution
At least one item had no variance  when finding alpha for subject = 110. Proceed with caution
At least one item had no variance  when finding alpha for subject = 112. Proceed with caution
At least one item had no variance  when finding alpha for subject = 113. Proceed with caution
At least one item had no variance  when finding alpha for subject = 114. Proceed with caution
At least one item had no variance  when finding alpha for subject = 115. Proceed with caution
At least one item had no variance  when finding alpha for subject = 116. Proceed with caution
At least one item had no variance  when finding alpha for subject = 118. Proceed with caution
At least one item had no variance  when finding alpha for subject = 120. Proceed with caution
At least one item had no variance  when finding alpha for subject = 121. Proceed with caution
At least one item had no variance  when finding alpha for subject = 123. Proceed with caution
At least one item had no variance  when finding alpha for subject = 125. Proceed with caution
At least one item had no variance  when finding alpha for subject = 127. Proceed with caution
At least one item had no variance  when finding alpha for subject = 128. Proceed with caution
At least one item had no variance  when finding alpha for subject = 130. Proceed with caution
At least one item had no variance  when finding alpha for subject = 131. Proceed with caution
At least one item had no variance  when finding alpha for subject = 132. Proceed with caution
At least one item had no variance  when finding alpha for subject = 134. Proceed with caution
At least one item had no variance  when finding alpha for subject = 135. Proceed with caution
Error in dimnames(x) <- dn :
length of 'dimnames' [1] not equal to array extent
In addition: There were 50 or more warnings (use warnings() to see the first 50)

I think this is due to the fact that I have NA values when it´s the afternoon assessments. But I tried to sperate the datasets (have 1 for the morning assessments and have 1 for the afternoon assessments) and calculate then, but I still get errors.
If I keep the same database, is there any possibility to tell RStudio to dismiss missing values or do you think the error has nothing to do with that?

Thank you so much for all the help!


问:
Undefined reference to 'getpass' in c
```<code>#include <stdio.h>
#include <unistd.h>
int main()
{
  char *itm;
  char *qnt;
  qnt,itm = getpass("");
  printf("%s %s ",qnt,itm);
    return 0;
}

</code>```

So if i run this code in online compiler like replit , it runs without error . But when i run it in codeblock , it throws an error stating undefined reference to 'getpass' . how to fix this ?

Title: Undefined reference to 'getpass' in c

Body:
#include <stdio.h>
#include <unistd.h>
int main()
{
  char *itm;
  char *qnt;
  qnt,itm = getpass("");
  printf("%s %s ",qnt,itm);
    return 0;
}

So if i run this code in online compiler like replit , it runs without error . But when i run it in codeblock , it throws an error stating undefined reference to 'getpass' . how to fix this ?


问:
sphinx grid table pdf output cell overflow
I have very long long grid table in terms of width that has 19 columns reaches 478 char length but only has three rows. When try to generate pdf file by sphinx output table looks ugly. The table's cell content do not fit and overflow from the cell. I added screenshot of that part of pdf file

pyproject.toml file sphinx dependencies:

sphinx                        4.5.0

sphinx-autodoc-typehints      1.19.1

sphinx-copybutton             0.4.0

sphinx-markdown-tables        0.0.15

sphinx-material               0.0.32

sphinxcontrib-applehelp       1.0.2

sphinxcontrib-devhelp         1.0.2

sphinxcontrib-htmlhelp        2.0.0

sphinxcontrib-jsmath          1.0.1

sphinxcontrib-mermaid         0.7.1

sphinxcontrib-qthelp          1.0.3

sphinxcontrib-serializinghtml 1.1.5

LateX version

pdfTeX 3.141592653-2.6-1.40.24 (TeX Live 2022)
kpathsea version 6.3.4
Copyright 2022 Han The Thanh (pdfTeX) et al.
There is NO warranty.  Redistribution of this software is
covered by the terms of both the pdfTeX copyright and
the Lesser GNU General Public License.
For more information about these matters, see the file
named COPYING and the pdfTeX source.
Primary author of pdfTeX: Han The Thanh (pdfTeX) et al.
Compiled with libpng 1.6.37; using libpng 1.6.37
Compiled with zlib 1.2.11; using zlib 1.2.11
Compiled with xpdf version 4.03


问:
set a link to an external web page on which auto redirect should take place
If the external URL is typed in the browser address bar directly, a redirection to a pdf file happens.
i.e. if you enter https://www.the-external-site.com/information/ and press enter, the page is getting loaded and immediately after that a pdf opens. You can see the url changing to the pdf (i.e. https://www.the-external-site.com/fileadmin/the-information.pdf). Normally, only the URL with the "placeholder" is known to public, because the name and version of the pdf file can change over time.

Now, if I set a Link to this external URL like  to the pdf  the first site gets loaded but the redirection to the pdf doesn't happen.

I tried to create a word file and entered the link there and clicked it. The redirection works here.

What am I missing?


问:
Computed value returns empty array
My idea is to render certain buttons inside navigation for certain user role. I have array of this buttons, and each of them has field: permission that is telling what type of permission user have to have to see this button. Then my computed value filters the array returning the buttons that permission is fulfilled with permission of logged in user that I store in vuex.

PROBLEM: When I login and the computed value should return only matching buttons it returns me empty array.

This is my array with buttons:

```<code>  public items = [
    { text: 'Strona główna', icon: 'mdi-home', path: '/', permission: [1, 2, 3, 4] },
    { text: 'Znajdź Mecz', icon: 'mdi-map-search', path: '/findGame', permission: [1, 2, 3, 4] },
    { text: 'Niższe Ligi', icon: 'mdi-soccer', path: '/leagues', permission: [1, 2, 3, 4] },
    { text: 'Dodaj Artykuł', icon: 'mdi-file-document-plus', path: '/addArticle', permission: [1] },
  ];
</code>```

As you can see each role has array of permission of which users can see this button.
I am rendering this buttons in a v-for loop:

```<code><v-list-item class="my-3" v-for="(item, i) in navBarOptions" :key="i" :to="item.path">
    <v-list-item-icon>
        <v-icon large v-text="item.icon"></v-icon>
    </v-list-item-icon>
    <v-list-item-content class="py-3">
        <v-list-item-title class="py-1 text-h6 font-weight-bold" v-text="item.text"></v-list-item-title>
    </v-list-item-content>
</v-list-item>
</code>```

And here is computed value (navBarOptions):

```<code>  get navBarOptions() {
    const userRole = user.userData?.role.id_role;
    if (userRole != null) {
console.log("Im here" + userRole);
      return this.items.filter((i) => i.permission.includes(userRole));
    } else {
      return this.items.filter((i) => i.permission.includes(4));
    }
  }
</code>```

When application starts, user is not logged in, so the naavBarOptions return buttons with permission 4 (unLogged User). Then if I login as admin, I can see in this conole.log that my role changed to 1. But in this moment even though this filter looks properly I get empty array.

PS Debuggin:
I add small console.log debugging:

```<code>if (userRole != null) {
      return (this.items = this.items.filter((i) => {
        i.permission.includes(userRole);
        console.log(i.permission);
        console.log(userRole);
        console.log(i.permission.includes(userRole));
      }));
    } else {
</code>```

DEBUG CONSOLE

Title: Computed value returns empty array

Body:
My idea is to render certain buttons inside navigation for certain user role. I have array of this buttons, and each of them has field: permission that is telling what type of permission user have to have to see this button. Then my computed value filters the array returning the buttons that permission is fulfilled with permission of logged in user that I store in vuex.

PROBLEM: When I login and the computed value should return only matching buttons it returns me empty array.

This is my array with buttons:

  public items = [
    { text: 'Strona główna', icon: 'mdi-home', path: '/', permission: [1, 2, 3, 4] },
    { text: 'Znajdź Mecz', icon: 'mdi-map-search', path: '/findGame', permission: [1, 2, 3, 4] },
    { text: 'Niższe Ligi', icon: 'mdi-soccer', path: '/leagues', permission: [1, 2, 3, 4] },
    { text: 'Dodaj Artykuł', icon: 'mdi-file-document-plus', path: '/addArticle', permission: [1] },
  ];

As you can see each role has array of permission of which users can see this button.
I am rendering this buttons in a v-for loop:

<v-list-item class="my-3" v-for="(item, i) in navBarOptions" :key="i" :to="item.path">
    <v-list-item-icon>
        <v-icon large v-text="item.icon"></v-icon>
    </v-list-item-icon>
    <v-list-item-content class="py-3">
        <v-list-item-title class="py-1 text-h6 font-weight-bold" v-text="item.text"></v-list-item-title>
    </v-list-item-content>
</v-list-item>

And here is computed value (navBarOptions):

  get navBarOptions() {
    const userRole = user.userData?.role.id_role;
    if (userRole != null) {
console.log("Im here" + userRole);
      return this.items.filter((i) => i.permission.includes(userRole));
    } else {
      return this.items.filter((i) => i.permission.includes(4));
    }
  }

When application starts, user is not logged in, so the naavBarOptions return buttons with permission 4 (unLogged User). Then if I login as admin, I can see in this conole.log that my role changed to 1. But in this moment even though this filter looks properly I get empty array.

PS Debuggin:
I add small console.log debugging:

if (userRole != null) {
      return (this.items = this.items.filter((i) => {
        i.permission.includes(userRole);
        console.log(i.permission);
        console.log(userRole);
        console.log(i.permission.includes(userRole));
      }));
    } else {

DEBUG CONSOLE


问:
DataGridView.Rows.Add has different effects inside of a For loop. Why?
I'm confident that the scoping rules of for loops aren't relevant here, so I've got no idea what is going on. I'm absolutely confident that I've isolated the problem down to this one line of code, so the context isn't needed. d is a DataGridView that is used as an input to the method that this code is found in and c is a DataGridViewCellCollection. I've taken

d.Rows.Add(DataGridViewCellCollection(c[0].Value.ToString(), c[1].Value.ToString(), c[2].Value.ToString())
```
<p>and replaced it with</p>
<pre class="lang-cs prettyprint-override"><code>for(int i = 0; i < 3; i++) d.Rows.Add(c[i].Value.ToString());
</code>```

For reasons unknown to me, these two code blocks aren't identical. What could be causing this? They appear to call the same overload of Add and I've found no insight in the debugger.

Body:
I'm confident that the scoping rules of for loops aren't relevant here, so I've got no idea what is going on. I'm absolutely confident that I've isolated the problem down to this one line of code, so the context isn't needed. d is a DataGridView that is used as an input to the method that this code is found in and c is a DataGridViewCellCollection. I've taken

d.Rows.Add(DataGridViewCellCollection(c[0].Value.ToString(), c[1].Value.ToString(), c[2].Value.ToString())

and replaced it with

for(int i = 0; i < 3; i++) d.Rows.Add(c[i].Value.ToString());

For reasons unknown to me, these two code blocks aren't identical. What could be causing this? They appear to call the same overload of Add and I've found no insight in the debugger.


问:
recursive moving average with sql
supose we have the next table:
table example

and what i need is:

frst iteration: calculate the moving average 5 days before the last day including the last day = (2+1+2+3+4)/5 = 2.4 and "save" this result, that result will be a prediction for the next day.

scnd iteration: calculate the moving average 5 days before the last, day where the last day basal cell is the value calculated in the previous iteration.  (1+2+3+4+2.4)/5 = 2.48

..

and so on.. the recursion will stop for a concrete future day for example: 2022-12-9

deseable output for future day: 2022-12-9

```<code>| date_       | art_id     | basal_sell |
| ------------| -----------|------------|
| 2022-12-01  | 1          | 2          |
| 2022-12-02  | 1          | 1          |
| 2022-12-03  | 1          | 2          |
| 2022-12-04  | 1          | 3          |
| 2022-12-05  | 1          | 4          |
| 2022-12-06  | 1          | 2.4        |
| 2022-12-07  | 1          | 2.48       |
| 2022-12-08  | 1          | 2.776      |
| 2022-12-09  | 1          | 2.9312     |
</code>```

this is the partial problem, in the real problem will be a bunch of arts_ids but i think the idea for this parcial problem will be the solution for the big problem (with some little changes).

what i think:

I thought a recursive cte where in the recursive part of the cte i have a union that will be union the temporary table with the new row that i calculated.

Something like:

with MiCte as (
  select *
  from sells

  union all
  (
    select * from MiCte
  )
  union
  (
    select dateadd(day, 1, date_), art_id, basal_sell
    from(
        select top 1 c.date_, c.art_id,
        AVG(c.basal_sell) OVER (partition by c.art_id
                              ORDER BY c.date_
                              rows BETWEEN 4 PRECEDING AND current row) basal_sell
        from MiCte c
        order by c.date_ desc
        ) as tmp
  )
) select * from MiCte
```
<p>Obviously if I contemplate having more than one art_id I have to take this into account when making top 1 (which I still couldn't think of how to solve).</p>
<ul>
<li>the example table:</li>
</ul>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE sells
    (date_ DATETIME,
     art_id int,
     basal_sell int)
;

INSERT INTO sells
    (date_, art_id , basal_sell)
VALUES ('2022-12-1', 1, 2),
       ('2022-12-2', 1, 1),
       ('2022-12-3', 1, 2),
       ('2022-12-4', 1, 3),
       ('2022-12-5', 1, 4);
</code>```

Title: recursive moving average with sql

Body:
supose we have the next table:
table example

and what i need is:

frst iteration: calculate the moving average 5 days before the last day including the last day = (2+1+2+3+4)/5 = 2.4 and "save" this result, that result will be a prediction for the next day.

scnd iteration: calculate the moving average 5 days before the last, day where the last day basal cell is the value calculated in the previous iteration.  (1+2+3+4+2.4)/5 = 2.48

..

and so on.. the recursion will stop for a concrete future day for example: 2022-12-9

deseable output for future day: 2022-12-9

| date_       | art_id     | basal_sell |
| ------------| -----------|------------|
| 2022-12-01  | 1          | 2          |
| 2022-12-02  | 1          | 1          |
| 2022-12-03  | 1          | 2          |
| 2022-12-04  | 1          | 3          |
| 2022-12-05  | 1          | 4          |
| 2022-12-06  | 1          | 2.4        |
| 2022-12-07  | 1          | 2.48       |
| 2022-12-08  | 1          | 2.776      |
| 2022-12-09  | 1          | 2.9312     |

this is the partial problem, in the real problem will be a bunch of arts_ids but i think the idea for this parcial problem will be the solution for the big problem (with some little changes).

what i think:

I thought a recursive cte where in the recursive part of the cte i have a union that will be union the temporary table with the new row that i calculated.

Something like:

with MiCte as (
  select *
  from sells

  union all
  (
    select * from MiCte
  )
  union
  (
    select dateadd(day, 1, date_), art_id, basal_sell
    from(
        select top 1 c.date_, c.art_id,
        AVG(c.basal_sell) OVER (partition by c.art_id
                              ORDER BY c.date_
                              rows BETWEEN 4 PRECEDING AND current row) basal_sell
        from MiCte c
        order by c.date_ desc
        ) as tmp
  )
) select * from MiCte

Obviously if I contemplate having more than one art_id I have to take this into account when making top 1 (which I still couldn't think of how to solve).

the example table:

CREATE TABLE sells
    (date_ DATETIME,
     art_id int,
     basal_sell int)
;

INSERT INTO sells
    (date_, art_id , basal_sell)
VALUES ('2022-12-1', 1, 2),
       ('2022-12-2', 1, 1),
       ('2022-12-3', 1, 2),
       ('2022-12-4', 1, 3),
       ('2022-12-5', 1, 4);


问:
I want the COUNTA function to not count the "0"
I am trying to add a "COUNTA" function to this formula. But I get "1" as a result when it should be 0. I guess it is counting my "0". How can I solve this issue?

```<code>=IFERROR(FILTER('Assignments Data Export 05 12'!$D:$D;
    (('Assignments Data Export 05 12'!$F:$F=$A$8)*
    ('Assignments Data Export 05 12'!$BZ:$BZ=$B10)*
    ('Assignments Data Export 05 12'!$L:$L=$C$19)*
    ('Assignments Data Export 05 12'!$BX:$BX>$C$18)));"0")
</code>```

Thank you in advance

Body:
I am trying to add a "COUNTA" function to this formula. But I get "1" as a result when it should be 0. I guess it is counting my "0". How can I solve this issue?

=IFERROR(FILTER('Assignments Data Export 05 12'!$D:$D;
    (('Assignments Data Export 05 12'!$F:$F=$A$8)*
    ('Assignments Data Export 05 12'!$BZ:$BZ=$B10)*
    ('Assignments Data Export 05 12'!$L:$L=$C$19)*
    ('Assignments Data Export 05 12'!$BX:$BX>$C$18)));"0")

Thank you in advance


问:
Pytest location issues
I have one problem with pytest. I am creating objects and I like to test these objects if they are complete or buggy. Now the thing: When I put the test script into the src-folder, it works fine. But when I want to use it in a tests folder, I get always an error, that if I like to load my object, a module is not found.

in this structure it works:

my-app/

├─ output/

├─ input/

├─ src/

│  ├─ some_package/

│  ├─ some_code.py

│  ├─ test.py

This structure gives me a ModuleNotFoundError:

my-app/

├─ output/

├─ input/

├─ src/

│  ├─ some_package/

│  ├─ some_code.py

├─ test/

│  ├─ test.py (with changed the relative paths)

I guess that pytest has some problems with using the correct path.

Title: Pytest location issues


问:
create a subarray of products with unique username (django)
I need an array of customer orders where username are unique and the order quantity should be added on. I got the result using annotate but I need an subarray with product name and respective quantity as sub array. Please check the outputs I got and outputs required below. Thanks in advance

views.py

```<code>orders = Order.objects.values('staff_id', 'staff__username', 'product__name').annotate(quantity=Sum('order_quantity')).order_by()
</code>```

models.py

```<code>class Product(models.Model):
    name = models.CharField(max_length=100, choices=PRODUCTS, null = True)
    quantity = models.PositiveIntegerField(null = True)

class Order(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
    staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    order_quantity = models.PositiveIntegerField(null=True)
</code>```

Output:

```<code>[
   {
      "staff_id":15,
      "staff__username":"John",
      "product__name":"samsung",
      "quantity":2
   },
   {
      "staff_id":15,
      "staff__username":"John",
      "product__name":"apple",
      "quantity":18
   },
   {
      "staff_id":16,
      "staff__username":"test",
      "product__name":"apple",
      "quantity":100
   }
]
</code>```

Output required

```<code>[
   {
      "staff_id":15,
      "staff__username":"John",
      "product": [
         {
            "product__name":"samsung",
            "quantity":2
         },
         {
            "product__name":"apple",
            "quantity":18
         }
      ]

   },
   {
      "staff_id":16,
      "staff__username":"test",
      "product": [
         {
            "product__name":"apple",
            "quantity":100
         }
        ]

   }
]
</code>```

Body:
I need an array of customer orders where username are unique and the order quantity should be added on. I got the result using annotate but I need an subarray with product name and respective quantity as sub array. Please check the outputs I got and outputs required below. Thanks in advance

views.py

orders = Order.objects.values('staff_id', 'staff__username', 'product__name').annotate(quantity=Sum('order_quantity')).order_by()

models.py

class Product(models.Model):
    name = models.CharField(max_length=100, choices=PRODUCTS, null = True)
    quantity = models.PositiveIntegerField(null = True)

class Order(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
    staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    order_quantity = models.PositiveIntegerField(null=True)

Output:

[
   {
      "staff_id":15,
      "staff__username":"John",
      "product__name":"samsung",
      "quantity":2
   },
   {
      "staff_id":15,
      "staff__username":"John",
      "product__name":"apple",
      "quantity":18
   },
   {
      "staff_id":16,
      "staff__username":"test",
      "product__name":"apple",
      "quantity":100
   }
]

Output required

[
   {
      "staff_id":15,
      "staff__username":"John",
      "product": [
         {
            "product__name":"samsung",
            "quantity":2
         },
         {
            "product__name":"apple",
            "quantity":18
         }
      ]

   },
   {
      "staff_id":16,
      "staff__username":"test",
      "product": [
         {
            "product__name":"apple",
            "quantity":100
         }
        ]

   }
]


问:
IndexError: list index out of range when parsing a Json
i want to get a specific item in a json

i run this code :

```<code>data1 = []
for response in resp  :
    for item in response['data']['search']['announcements']['data'] :
        data1.append(item['id'])
        data1.append(item['title'])
        data1.append(item['createdAt'])
        data1.append(item['description'])
        data1.append(item['cities'][0]['name'])
        data1.append(item['cities'][0]['region']['name'])
</code>```

i get this error  :

```<code>---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_10956\4238620074.py in <module>
      6         data1.append(item['createdAt'])
      7         data1.append(item['description'])
----> 8         data1.append(item['cities'][0]['name'])
      9         data1.append(item['cities'][0]['region']['name'])

IndexError: list index out of range
</code>```

here is how a json look like :

```<code>{
    "id": "32957722",
    "title": "Audi Q5 2022 S Line",
    "slug": "off-road-suv-audi-q5-2022-s-line-bab-ezzouar-algiers-algeria",
    "createdAt": "2022-12-07T14:30:07.000Z",
    "isFromStore": true,
    "isCommentEnabled": true,
    "hasDelivery": false,
    "deliveryType": "None",
    "description": "None",
    "status": "PUBLISHED",
    "cities": [
        {
            "id": "561",
            "name": "Bab ezzouar",
            "slug": "bab-ezzouar-561",
            "region": {
                "id": "16",
                "name": "Algiers",
                "slug": "alger-16",
                "__typename": "Region"
            },
            "__typename": "City"
        }
    ],
    "store": {
        "id": "15663",
        "name": "Apostrophe Auto 2",
        "slug": "apostrophe-auto-2",
        "imageUrl": "https://cdn.ouedkniss.com/stores/15663/Logo.jpg",
        "__typename": "Store"
    },
    "user": {
        "id": "5774328",
        "__typename": "User"
    },
    "defaultMedia": {
        "mediaUrl": "https://cdn7.ouedkniss.com/400/medias/announcements/images/R6J9yz/Z8o6WfpvfsQGgXa2gIe6eqISC4iGMp99XVHvHFBQ.jpg",
        "__typename": "AnnouncementMedia"
    },
    "price": "None",
    "pricePreview": 0,
    "priceUnit": "MILLION",
    "oldPrice": "None",
    "priceType": "None",
    "exchangeType": "None",
    "__typename": "Announcement",
    "smallDescription": [
        {
            "valueText": [
                "100km"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "Diesel"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "200CV 2L"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "Automatic"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "Grey"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "Licence"
            ],
            "__typename": "AnnouncementSpecDisplay"
        }
    ],
    "noAdsense": false
}
</code>```

Body:
i want to get a specific item in a json

i run this code :

data1 = []
for response in resp  :
    for item in response['data']['search']['announcements']['data'] :
        data1.append(item['id'])
        data1.append(item['title'])
        data1.append(item['createdAt'])
        data1.append(item['description'])
        data1.append(item['cities'][0]['name'])
        data1.append(item['cities'][0]['region']['name'])

i get this error  :

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_10956\4238620074.py in <module>
      6         data1.append(item['createdAt'])
      7         data1.append(item['description'])
----> 8         data1.append(item['cities'][0]['name'])
      9         data1.append(item['cities'][0]['region']['name'])

IndexError: list index out of range

here is how a json look like :

{
    "id": "32957722",
    "title": "Audi Q5 2022 S Line",
    "slug": "off-road-suv-audi-q5-2022-s-line-bab-ezzouar-algiers-algeria",
    "createdAt": "2022-12-07T14:30:07.000Z",
    "isFromStore": true,
    "isCommentEnabled": true,
    "hasDelivery": false,
    "deliveryType": "None",
    "description": "None",
    "status": "PUBLISHED",
    "cities": [
        {
            "id": "561",
            "name": "Bab ezzouar",
            "slug": "bab-ezzouar-561",
            "region": {
                "id": "16",
                "name": "Algiers",
                "slug": "alger-16",
                "__typename": "Region"
            },
            "__typename": "City"
        }
    ],
    "store": {
        "id": "15663",
        "name": "Apostrophe Auto 2",
        "slug": "apostrophe-auto-2",
        "imageUrl": "https://cdn.ouedkniss.com/stores/15663/Logo.jpg",
        "__typename": "Store"
    },
    "user": {
        "id": "5774328",
        "__typename": "User"
    },
    "defaultMedia": {
        "mediaUrl": "https://cdn7.ouedkniss.com/400/medias/announcements/images/R6J9yz/Z8o6WfpvfsQGgXa2gIe6eqISC4iGMp99XVHvHFBQ.jpg",
        "__typename": "AnnouncementMedia"
    },
    "price": "None",
    "pricePreview": 0,
    "priceUnit": "MILLION",
    "oldPrice": "None",
    "priceType": "None",
    "exchangeType": "None",
    "__typename": "Announcement",
    "smallDescription": [
        {
            "valueText": [
                "100km"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "Diesel"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "200CV 2L"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "Automatic"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "Grey"
            ],
            "__typename": "AnnouncementSpecDisplay"
        },
        {
            "valueText": [
                "Licence"
            ],
            "__typename": "AnnouncementSpecDisplay"
        }
    ],
    "noAdsense": false
}


问:
How/when does Python destroy objects that are cyclically referenced?
This test program seems to indicate they are not destroyed till program termination:

```<code>$ cat x.py
from time import sleep

class A:
  def __init__(self, id):
    self.id = id
    self.r = None

  def __del__(self):
    print(f"delete {self.id}")

a1 = A(1)
a1 = None
print("a")
a2 = A(2)
a3 = A(3)
a4 = A(4)
a2.r = a3
a3.r = a2
a4.r = a4
a2 = None
a3 = None
a4 = None
print("b")
sleep(10)
print("c")
sleep(10)
print("d")
sleep(10)
print("e")
$
$ python3 x.py
delete 1
a
b
c
d
e
delete 2
delete 3
delete 4
$

</code>```

There is a two-object and a one-object cycle.  The objects in neither are destroyed until program termination.

Body:
This test program seems to indicate they are not destroyed till program termination:

$ cat x.py
from time import sleep

class A:
  def __init__(self, id):
    self.id = id
    self.r = None

  def __del__(self):
    print(f"delete {self.id}")

a1 = A(1)
a1 = None
print("a")
a2 = A(2)
a3 = A(3)
a4 = A(4)
a2.r = a3
a3.r = a2
a4.r = a4
a2 = None
a3 = None
a4 = None
print("b")
sleep(10)
print("c")
sleep(10)
print("d")
sleep(10)
print("e")
$
$ python3 x.py
delete 1
a
b
c
d
e
delete 2
delete 3
delete 4
$

There is a two-object and a one-object cycle.  The objects in neither are destroyed until program termination.


问:
How to update the values given in an array when they are chosen?
I'm creating a blackjack card counting simulator in c++ and I'm starting off by making the program choose from the number of cards avaviable. I have assinged each card with a starting value of 4(execpt for 10 and clothed cards as they all have the same value) as there's 4 of each number in a complete deck. However I want these numbers to go down as a card is drawn. For example if I draw a 3 I want the value of three's to go from 4 to 3.
Thank you.
Code:

```<code>#include<iostream>
#include<time.h>
int acecard = 4;
int twocard = 4;
int threecard = 4;
int fourcard = 4;
int fivecard = 4;
int sixcard = 4;
int sevencard = 4;
int eightcard = 4;
int ninecard = 4;
int tencard = 16;
//shows how many of each card there is

int cards[10] = { acecard, twocard, threecard, fourcard, fivecard, sixcard, sevencard, eightcard, ninecard, tencard };
//stores all the card in an array
int cardpick()
{
    srand(time(NULL));
    int Ranindex = rand() % 10;
    return cards[Ranindex];//picks random card from array
}

int main()
{
    return cardpick();
}
</code>```

I tried to use if functions via something like this:

```<code>    srand(time(NULL));
    int Ranindex = rand() % 10;
    int update = cards[Ranindex];//picks random card from array
    if (update = acecard)
    {
        acecard -= 1;
    }
</code>```

However since most cards have the same starting value it would make the value go down for the card no matter what card was drawn.
Thank you.

Body:
I'm creating a blackjack card counting simulator in c++ and I'm starting off by making the program choose from the number of cards avaviable. I have assinged each card with a starting value of 4(execpt for 10 and clothed cards as they all have the same value) as there's 4 of each number in a complete deck. However I want these numbers to go down as a card is drawn. For example if I draw a 3 I want the value of three's to go from 4 to 3.
Thank you.
Code:

#include<iostream>
#include<time.h>
int acecard = 4;
int twocard = 4;
int threecard = 4;
int fourcard = 4;
int fivecard = 4;
int sixcard = 4;
int sevencard = 4;
int eightcard = 4;
int ninecard = 4;
int tencard = 16;
//shows how many of each card there is

int cards[10] = { acecard, twocard, threecard, fourcard, fivecard, sixcard, sevencard, eightcard, ninecard, tencard };
//stores all the card in an array
int cardpick()
{
    srand(time(NULL));
    int Ranindex = rand() % 10;
    return cards[Ranindex];//picks random card from array
}

int main()
{
    return cardpick();
}

I tried to use if functions via something like this:

    srand(time(NULL));
    int Ranindex = rand() % 10;
    int update = cards[Ranindex];//picks random card from array
    if (update = acecard)
    {
        acecard -= 1;
    }

However since most cards have the same starting value it would make the value go down for the card no matter what card was drawn.
Thank you.


问:
Wildfly DB connection pool fails after database server restart
Our wildfly (22) connection pool does not reconnect after a DB server restart / or a network outage.
In such a situation all the DB connections result in a

```<code>java.sql.SQLNonTransientConnectionException: (conn=96578) Connection is closed
</code>```

We have set the following validation settings:

```<code><validation>
   <check-valid-connection-sql>select 1</check-valid-connection-sql>
   <validate-on-match>false</validate-on-match>
   <background-validation>true</background-validation>
   <background-validation-millis>10000</background-validation-millis>
</validation>
</code>```

So as I understood the documentation after max. 10s all DB connections should have been renewed. However that is not the case and the DB connection pool always returns 'closed connections'. Only a wildfly server restart helps in this case.
Any idea how to fix this?

Somebody had the same problem, but no solution

Body:
Our wildfly (22) connection pool does not reconnect after a DB server restart / or a network outage.
In such a situation all the DB connections result in a

java.sql.SQLNonTransientConnectionException: (conn=96578) Connection is closed

We have set the following validation settings:

<validation>
   <check-valid-connection-sql>select 1</check-valid-connection-sql>
   <validate-on-match>false</validate-on-match>
   <background-validation>true</background-validation>
   <background-validation-millis>10000</background-validation-millis>
</validation>

So as I understood the documentation after max. 10s all DB connections should have been renewed. However that is not the case and the DB connection pool always returns 'closed connections'. Only a wildfly server restart helps in this case.
Any idea how to fix this?

Somebody had the same problem, but no solution


问:
Why am I getting LNK2019 errors in visual studio with GDCM and vcpkg
I'm pretty new to vcpkg, but it seems like a handy tool. However, it doesn't seem to help me overcome the normal-for-me linking issues as hoped/promised. I'm trying to use GDCM in a visual studio project, but get LNK2019 errors.

When installing the GDCM package with vcpkg, one of the output messages states that GDCM can only be statically linked, so I have explicitly installed gdcm:x64-windows-static

I successfully followed the example for static linking found at: https://levelup.gitconnected.com/how-to-statically-link-c-libraries-with-vcpkg-visual-studio-2019-435c2d4ace03.

Extending that example to include some GDCM functions;

```<code>int main()
{
    spdlog::info("Hello Static Linking!");

    gdcm::Reader file_reader;

    const char* filename =C:\\file_path_and_name\\of\\dicom\\file.dcm";

    file_reader.SetFileName(filename);
    if (!file_reader.Read()) {
        std::cout << filename << "doesn't look like DICOM" << '\n';
    } else {
        std::cout << "success reading" << filename << '\n';
    }

}
</code>```

leads to LNK2019 errors

```<code>Error   LNK2019 unresolved external symbol gethostname referenced in function "public: static bool __cdecl gdcm::System::GetHostName(char * const)" (?GetHostName@System@gdcm@@SA_NQEAD@Z)  DemoStaticLinking   C:\Users\...\gdcmCommon.lib(gdcmSystem.cxx.obj) 1
</code>```

What am I doing wrong? I thought/hoped vcpkg would help me overcome these kinds of issues!

Update: Looking more into the error the link errors relate to functions within gdcm itself - however no error was returned when vcpkg was building and installing the library.

I managed to get the code to run firstly by building GDCM from source and manually setting up the static libraries to link in Visual studio, including the one related to this link error (Ws2_32.lib) that GDCM then wants, and then using the automatic linking of the package in vcpkg but manually adding the link to Ws2_32.lib in VS.

To refine my question a bit... isn't the idea of vcpkg that I should have to find such libraries to link? shouldn't they be included by the package manager as a dependence?

Body:
I'm pretty new to vcpkg, but it seems like a handy tool. However, it doesn't seem to help me overcome the normal-for-me linking issues as hoped/promised. I'm trying to use GDCM in a visual studio project, but get LNK2019 errors.

When installing the GDCM package with vcpkg, one of the output messages states that GDCM can only be statically linked, so I have explicitly installed gdcm:x64-windows-static

I successfully followed the example for static linking found at: https://levelup.gitconnected.com/how-to-statically-link-c-libraries-with-vcpkg-visual-studio-2019-435c2d4ace03.

Extending that example to include some GDCM functions;

int main()
{
    spdlog::info("Hello Static Linking!");

    gdcm::Reader file_reader;

    const char* filename =C:\\file_path_and_name\\of\\dicom\\file.dcm";

    file_reader.SetFileName(filename);
    if (!file_reader.Read()) {
        std::cout << filename << "doesn't look like DICOM" << '\n';
    } else {
        std::cout << "success reading" << filename << '\n';
    }

}

leads to LNK2019 errors

Error   LNK2019 unresolved external symbol gethostname referenced in function "public: static bool __cdecl gdcm::System::GetHostName(char * const)" (?GetHostName@System@gdcm@@SA_NQEAD@Z)  DemoStaticLinking   C:\Users\...\gdcmCommon.lib(gdcmSystem.cxx.obj) 1

What am I doing wrong? I thought/hoped vcpkg would help me overcome these kinds of issues!

Update: Looking more into the error the link errors relate to functions within gdcm itself - however no error was returned when vcpkg was building and installing the library.

I managed to get the code to run firstly by building GDCM from source and manually setting up the static libraries to link in Visual studio, including the one related to this link error (Ws2_32.lib) that GDCM then wants, and then using the automatic linking of the package in vcpkg but manually adding the link to Ws2_32.lib in VS.

To refine my question a bit... isn't the idea of vcpkg that I should have to find such libraries to link? shouldn't they be included by the package manager as a dependence?


问:
Sending images using i2c
I have a question. I would like to know if it is possible to send images from one device to another using I2C communication.

Someone can help me, please?

I am actually using a camera with a WiFi module to transfer data, but I need to separate the photo capture and transmission to do it with 2 devices to reduction size of capturing device. So, I am searching how send the data saved in a SD card in one device to another device and that's the reason to asking if it is possible to send images through I2C.

Title: Sending images using i2c


问:
R plotly histogram increase bin width i.e. reduce margins between bins/ticks
How can I decrease the white space between the bins?

nbinsx  is an option but still there is some space remaining

```<code>  x1 <- rnorm(50)
  x2 <- rnorm(10)

fig <- plot_ly()

fig <- fig %>%

  add_histogram(x = ~x1, name = "X1", marker = list(color = "red")
  ) %>%

  add_histogram(x = ~x2, name = "X2", marker = list(color ="#blue")
  )
</code>```

Body:
How can I decrease the white space between the bins?

nbinsx  is an option but still there is some space remaining

  x1 <- rnorm(50)
  x2 <- rnorm(10)

fig <- plot_ly()

fig <- fig %>%

  add_histogram(x = ~x1, name = "X1", marker = list(color = "red")
  ) %>%

  add_histogram(x = ~x2, name = "X2", marker = list(color ="#blue")
  )


问:
Why does 'window.location.href' not work as expected when set as a variable outside an exported function?
Below I've shared two code snippets: the first works, the second does not. In both instances, the user clicks a share button which is supposed to copy the link to the clipboard. The first copies the current window link correctly every time. The second only copies the current window link if the window is reloaded after the first load.

Please explain why this isn't working as expected, and if there is a solution to the second code snippet, please provide it.

First code snippet

```<code>export const ShareGroup = ({ link = window.location.href, callback = () => null }) => {
  const handleCopyLink = () => {
    if ('window' in globalThis) {
      const cb = navigator.clipboard
      cb.writeText(link).then(() => alert('Link copied to clipboard'))
    }
    callback()
  }
</code>```

Second code snippet

```<code>let currentPage = ''
if ('window' in globalThis) {
  currentPage = window.location.href
}
export const ShareGroup = ({ link = currentPage, callback = () => null }) => {
  const handleCopyLink = () => {
    if ('window' in globalThis) {
      const cb = navigator.clipboard
      cb.writeText(link).then(() => alert('Link copied to clipboard'))
    }
    callback()
  }
</code>```

Interestingly in the second code snippet, if there's a console.log(${link}) within the export function, the console.log correctly displays the link that's supposed to be copied, but the actual link that's copied to the clipboard isn't correct. Really odd behavior.

Again, with the second code snippet, if the page is reloaded after the initial load then the functionality works as expected.

Body:
Below I've shared two code snippets: the first works, the second does not. In both instances, the user clicks a share button which is supposed to copy the link to the clipboard. The first copies the current window link correctly every time. The second only copies the current window link if the window is reloaded after the first load.

Please explain why this isn't working as expected, and if there is a solution to the second code snippet, please provide it.

First code snippet

export const ShareGroup = ({ link = window.location.href, callback = () => null }) => {
  const handleCopyLink = () => {
    if ('window' in globalThis) {
      const cb = navigator.clipboard
      cb.writeText(link).then(() => alert('Link copied to clipboard'))
    }
    callback()
  }

Second code snippet

let currentPage = ''
if ('window' in globalThis) {
  currentPage = window.location.href
}
export const ShareGroup = ({ link = currentPage, callback = () => null }) => {
  const handleCopyLink = () => {
    if ('window' in globalThis) {
      const cb = navigator.clipboard
      cb.writeText(link).then(() => alert('Link copied to clipboard'))
    }
    callback()
  }

Interestingly in the second code snippet, if there's a console.log(${link}) within the export function, the console.log correctly displays the link that's supposed to be copied, but the actual link that's copied to the clipboard isn't correct. Really odd behavior.

Again, with the second code snippet, if the page is reloaded after the initial load then the functionality works as expected.


问:
Can shiny display the finished output on webpage immediately, and do not wait for other unfinished outputs?
In a shiny app, all of the outputs will never appear until the last render output is finished, but what I want is to show the finished output immediately.

For example, in this app the text output, table DT1, and table DT2 will show simultaneously 10 sec after initialization. But the more effective way is to show text right away, table DT1 5 sec after, and finally table DT2.

Is it possible?

library(shiny)
library(tidyverse)
library(shinyBS)
library(DT)

genDF <- function() {
    Sys.sleep(5)
    return(iris)
}

ui <- fluidPage(
   mainPanel(
        h3('The renderPrint object will not appear until the last render object is completed'),
        bsButton("Btn", "Button"),
        verbatimTextOutput("Tx"),
        splitLayout(cellWidths = c("50%", "50%"),
          DTOutput("DT1"),
          DTOutput("DT2"))
      )
)

server <- function(input, output, session) {
  observeEvent(TRUE, {
    output$Tx <- renderPrint({ input$Btn })
    TB1 <- genDF()
    output$DT1 <- renderDT(TB1)
    TB2 <- genDF()
    output$DT2 <- renderDT(TB2)
  }, once=TRUE)
}

shinyApp(ui, server)
```
<p>I tried to move them into 3 different observeEvent blocks, but it didn't work.</p>
<pre class="lang-r prettyprint-override"><code>  observeEvent(TRUE, {
    output$Tx <- renderPrint({ input$Btn })
  }, once=TRUE)

  observeEvent(TRUE, {
    TB1 <- genDF()
    output$DT1 <- renderDT(TB1)
  }, once=TRUE)

  observeEvent(TRUE, {
    TB2 <- genDF()
    output$DT2 <- renderDT(TB2)
  }, once=TRUE)
</code>```

I tried future and promises packages, but they don't work. The outputs still appear at the last second.

Body:
In a shiny app, all of the outputs will never appear until the last render output is finished, but what I want is to show the finished output immediately.

For example, in this app the text output, table DT1, and table DT2 will show simultaneously 10 sec after initialization. But the more effective way is to show text right away, table DT1 5 sec after, and finally table DT2.

Is it possible?

library(shiny)
library(tidyverse)
library(shinyBS)
library(DT)

genDF <- function() {
    Sys.sleep(5)
    return(iris)
}

ui <- fluidPage(
   mainPanel(
        h3('The renderPrint object will not appear until the last render object is completed'),
        bsButton("Btn", "Button"),
        verbatimTextOutput("Tx"),
        splitLayout(cellWidths = c("50%", "50%"),
          DTOutput("DT1"),
          DTOutput("DT2"))
      )
)

server <- function(input, output, session) {
  observeEvent(TRUE, {
    output$Tx <- renderPrint({ input$Btn })
    TB1 <- genDF()
    output$DT1 <- renderDT(TB1)
    TB2 <- genDF()
    output$DT2 <- renderDT(TB2)
  }, once=TRUE)
}

shinyApp(ui, server)

I tried to move them into 3 different observeEvent blocks, but it didn't work.

  observeEvent(TRUE, {
    output$Tx <- renderPrint({ input$Btn })
  }, once=TRUE)

  observeEvent(TRUE, {
    TB1 <- genDF()
    output$DT1 <- renderDT(TB1)
  }, once=TRUE)

  observeEvent(TRUE, {
    TB2 <- genDF()
    output$DT2 <- renderDT(TB2)
  }, once=TRUE)

I tried future and promises packages, but they don't work. The outputs still appear at the last second.