问:
need some advice to fix an error from GAMLSS/GAMLSS.inf package in R
I was wondering how I can fix the errors for the following code (GAMLSS package): Thanks for the help in advance.

```<code>library(gamlss)
library(gamlss.inf)
library(gamlss.add)
data(lungFunction)

A<-lungFunction
gen.Family("SST", "logit")
mf1 <- gamlssInf0to1(y=slf,
                     mu.formula = ~ ga(~s(log(height), log(age))),
                     sigma.formula = ~pb(log(age)),
                     nu.formula = ~pb(log(age)),
                     tau.formula = ~pb(log(age)),
                     xi1.formula = ~pb(log(age))+ pb(log(height)),
                     family = logitSST,
                     data = A,
                     n.cyc = 100,
                     trace = TRUE)

Error in as.data.frame.default(x[[i]], optional = TRUE) :
  cannot coerce class ‘"function"’ to a data.frame
</code>```

And the error from the following code

```<code>    b4 <- gamlss(slf~ga(~s(log(height), log(age))), dat=A, family=BI)

Error in while (abs(G.dev.old - G.dev) > c.crit && iter < n.cyc) { :
  missing value where TRUE/FALSE needed
</code>```

Body:
I was wondering how I can fix the errors for the following code (GAMLSS package): Thanks for the help in advance.

library(gamlss)
library(gamlss.inf)
library(gamlss.add)
data(lungFunction)

A<-lungFunction
gen.Family("SST", "logit")
mf1 <- gamlssInf0to1(y=slf,
                     mu.formula = ~ ga(~s(log(height), log(age))),
                     sigma.formula = ~pb(log(age)),
                     nu.formula = ~pb(log(age)),
                     tau.formula = ~pb(log(age)),
                     xi1.formula = ~pb(log(age))+ pb(log(height)),
                     family = logitSST,
                     data = A,
                     n.cyc = 100,
                     trace = TRUE)

Error in as.data.frame.default(x[[i]], optional = TRUE) :
  cannot coerce class ‘"function"’ to a data.frame

And the error from the following code

    b4 <- gamlss(slf~ga(~s(log(height), log(age))), dat=A, family=BI)

Error in while (abs(G.dev.old - G.dev) > c.crit && iter < n.cyc) { :
  missing value where TRUE/FALSE needed


来源: stackexchange

问:
SAP Hybris Advanced Search field
I have a requirement to fulfill, we have a "supercategories" field in the advanced search filters of the "Product" entity. The categories are divided into 4 stages, the first stage is the root category and has the second stage categories as subcategories, the latter have the third stage categories as subcategories and the latter still have zero subcategories but have products. What I need to do is this: EG:

If a first-stage category is specified in that field:
SAP retrieves all child (second-stage) categories of the first-stage category
level specified.

For each second level category, SAP retrieves all child categories (third level) of the second             level category.

For each third-level category, it retrieves the products belonging to that category.

All this only if "supercategories" filter is present in the search filters otherwise the search should not change.

How can I override the advanced search and take that supercategories filter value and do my logic with it? Thanks a lot.

ContentLicense: CC BY-SA 4.0

Title: SAP Hybris Advanced Search field


问:
How to libpq copy into two tables concurrently in PostgreSQL?
I am listening to n different TCP streams and would like to copy the received data into n different tables after some simple post-processing. Latency is important, and using this approach sequentially I've managed to get insertions down to < 1 ms.

Using libpq from Python, I've attempted to open n different database connections with

```<code>db = ps_abst.PGconn(
    ps_impl.PQconnectdb(f"user={settings.db.user}".encode(pg_encoding)))
</code>```

from n different threading.Thread targets and simply put_copy_data(data) the post-processed data after executing the relevant copy query with db.exec_(query). ps_abst and ps_impl are imports from psycopg.

It seems, however, that this approach is incorrect as the copy operation either fails silently or I receive a warning that an ongoing copy operation is in progress. The TCP data can, on the other hand, be printed to stdout without issues.

Does anybody know where I'm messing up? Thanks a lot!

Body:
I am listening to n different TCP streams and would like to copy the received data into n different tables after some simple post-processing. Latency is important, and using this approach sequentially I've managed to get insertions down to < 1 ms.

Using libpq from Python, I've attempted to open n different database connections with

db = ps_abst.PGconn(
    ps_impl.PQconnectdb(f"user={settings.db.user}".encode(pg_encoding)))

from n different threading.Thread targets and simply put_copy_data(data) the post-processed data after executing the relevant copy query with db.exec_(query). ps_abst and ps_impl are imports from psycopg.

It seems, however, that this approach is incorrect as the copy operation either fails silently or I receive a warning that an ongoing copy operation is in progress. The TCP data can, on the other hand, be printed to stdout without issues.

Does anybody know where I'm messing up? Thanks a lot!


问:
Change playback speed in flutter video_player package
I want to change the playback speed of the video with the flutter video_player package and save it to the gallery. I changed the playback speed with the property controller.setPlaybackSpeed but I couldn't find how to get the change information of the modified video.

```<code>Slider(
  value: blur, min: 1, max: 5, onChanged: (value) {
    setState(() {
      blur = value;
      _controller.setPlaybackSpeed(blur);

    });
  },) ,
</code>```

I tried to find it with controller.dataSource and controller.value properties but I couldn't find it

Body:
I want to change the playback speed of the video with the flutter video_player package and save it to the gallery. I changed the playback speed with the property controller.setPlaybackSpeed but I couldn't find how to get the change information of the modified video.

Slider(
  value: blur, min: 1, max: 5, onChanged: (value) {
    setState(() {
      blur = value;
      _controller.setPlaybackSpeed(blur);

    });
  },) ,

I tried to find it with controller.dataSource and controller.value properties but I couldn't find it


问:
Setting a `--cfg` flag with custom target
I'd like to pass a custom --cfg flag to rustc via Cargo. Normally, I can do this by putting this in .cargo/config for a given crate:

```<code>[build]
rustflags = "--cfg procmacro2_semver_exempt"
</code>```

However, in one of my crates, I am using a custom compilation target, and that seems to break rustflags;

```<code>[build]
target = "avr-atmega32u4.json"
rustflags = "--cfg procmacro2_semver_exempt"

[unstable]
build-std = ["core"]

[env]
AVR_CPU_FREQUENCY_HZ = "16_000_000"
</code>```

In this case, the config flag is not passed to rustc. I've tried moving rustflags into a target-specific section:

```<code>[target.avr-atmega32u4.json]
rustflags = "--cfg procmacro2_semver_exempt"
</code>```

but this doesn't seem to have any effect either.

Body:
I'd like to pass a custom --cfg flag to rustc via Cargo. Normally, I can do this by putting this in .cargo/config for a given crate:

[build]
rustflags = "--cfg procmacro2_semver_exempt"

However, in one of my crates, I am using a custom compilation target, and that seems to break rustflags;

[build]
target = "avr-atmega32u4.json"
rustflags = "--cfg procmacro2_semver_exempt"

[unstable]
build-std = ["core"]

[env]
AVR_CPU_FREQUENCY_HZ = "16_000_000"

In this case, the config flag is not passed to rustc. I've tried moving rustflags into a target-specific section:

[target.avr-atmega32u4.json]
rustflags = "--cfg procmacro2_semver_exempt"

but this doesn't seem to have any effect either.


问:
Async To Sync Not sending message to group
I just want to send message to particular group via async to sync,

Here is my consumers file

```<code>import json
from channels.generic.websocket import AsyncWebsocketConsumer

class ChatRoomConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.chat_box_name = self.scope["url_route"]["kwargs"]["chat_box_name"]
        self.group_name = "chat_%s" % self.chat_box_name
        await self.channel_layer.group_add(self.group_name, self.channel_name)
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.group_name, self.channel_name)
    # This function receive messages from WebSocket.
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]
        username = text_data_json["username"]

        await self.channel_layer.group_send(
            self.group_name,
            {
                "type": "chatbox_message",
                "message": message,
                "username": username,
            },
        )
    # Receive message from room group.
    async def chatbox_message(self, event):
        message = event["message"]
        username = event["username"]
        #send message and username of sender to websocket
        await self.send(
            text_data=json.dumps(
                {
                    "message": message,
                    "username": username,
                }
            )
        )
    async def chat_message(self, event):
        message = event["message"]

        # Send message to WebSocket
        await self.send(text_data=json.dumps({"message": message}))

</code>```

And this is my code for sending message to specific group

```<code>import channels.layers
from asgiref.sync import async_to_sync
channel_layer = channels.layers.get_channel_layer()
async_to_sync(channel_layer.group_send)("chat_groupone", {"type": "chatbox_message","message":"STOP","username":"admin"})
</code>```

I don't know what i am doing wrong in this, it returns me none without any error
I am expecting by running this code, group should have recieved the message

Version-
Django- 4.0
channels - 3.0.4
python - 3.9

Body:
I just want to send message to particular group via async to sync,

Here is my consumers file

import json
from channels.generic.websocket import AsyncWebsocketConsumer

class ChatRoomConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.chat_box_name = self.scope["url_route"]["kwargs"]["chat_box_name"]
        self.group_name = "chat_%s" % self.chat_box_name
        await self.channel_layer.group_add(self.group_name, self.channel_name)
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.group_name, self.channel_name)
    # This function receive messages from WebSocket.
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]
        username = text_data_json["username"]

        await self.channel_layer.group_send(
            self.group_name,
            {
                "type": "chatbox_message",
                "message": message,
                "username": username,
            },
        )
    # Receive message from room group.
    async def chatbox_message(self, event):
        message = event["message"]
        username = event["username"]
        #send message and username of sender to websocket
        await self.send(
            text_data=json.dumps(
                {
                    "message": message,
                    "username": username,
                }
            )
        )
    async def chat_message(self, event):
        message = event["message"]

        # Send message to WebSocket
        await self.send(text_data=json.dumps({"message": message}))

And this is my code for sending message to specific group

import channels.layers
from asgiref.sync import async_to_sync
channel_layer = channels.layers.get_channel_layer()
async_to_sync(channel_layer.group_send)("chat_groupone", {"type": "chatbox_message","message":"STOP","username":"admin"})

I don't know what i am doing wrong in this, it returns me none without any error
I am expecting by running this code, group should have recieved the message

Version-
Django- 4.0
channels - 3.0.4
python - 3.9


问:
How to resolve "Whitelabel Error Page . There was an unexpected error (type=Not Found, status=404)."
I have a simple project to run on tomcat server, Here it goes

pom.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.apprikart</groupId>
    <artifactId>Temp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Temp</name>
    <description>Tempraury</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
            <version>10.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Here is my main class

```<code>package com.apprikart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TempApplication {

    public static void main(String[] args) {
        SpringApplication.run(TempApplication.class, args);
    }

}
</code>```

Controller class

```<code>    package com.apprikart.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    public class AppContrl {

        @RequestMapping("/")
        public String fun() {
            System.out.println("enter");
            return "home.jsp";
        }
   }
</code>```

application.properties

```<code>spring.mvc.view.prefix=/webapp/
</code>```

Console:

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
[32m :: Spring Boot :: [39m              [2m (v3.0.1)[0;39m

[2m2023-01-02T17:06:59.336+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mcom.apprikart.TempApplication           [0;39m [2m:[0;39m Starting TempApplication using Java 17.0.4.1 with PID 7336 (C:\Users\HI\Documents\workspace-spring-tool-suite-4-4.16.1.RELEASE\Temp\target\classes started by HI in C:\Users\HI\Documents\workspace-spring-tool-suite-4-4.16.1.RELEASE\Temp)
[2m2023-01-02T17:06:59.342+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mcom.apprikart.TempApplication           [0;39m [2m:[0;39m No active profile set, falling back to 1 default profile: "default"
[2m2023-01-02T17:07:00.262+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mtrationDelegate$BeanPostProcessorChecker[0;39m [2m:[0;39m Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [org.springframework.ws.config.annotation.DelegatingWsConfiguration$$SpringCGLIB$$0] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[2m2023-01-02T17:07:00.326+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36m.w.s.a.s.AnnotationActionEndpointMapping[0;39m [2m:[0;39m Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
[2m2023-01-02T17:07:00.650+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat initialized with port(s): 8080 (http)
[2m2023-01-02T17:07:00.668+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.apache.catalina.core.StandardService  [0;39m [2m:[0;39m Starting service [Tomcat]
[2m2023-01-02T17:07:00.668+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.apache.catalina.core.StandardEngine   [0;39m [2m:[0;39m Starting Servlet engine: [Apache Tomcat/10.1.4]
[2m2023-01-02T17:07:00.930+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.apache.jasper.servlet.TldScanner    [0;39m [2m:[0;39m At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
[2m2023-01-02T17:07:00.941+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/]      [0;39m [2m:[0;39m Initializing Spring embedded WebApplicationContext
[2m2023-01-02T17:07:00.942+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mw.s.c.ServletWebServerApplicationContext[0;39m [2m:[0;39m Root WebApplicationContext: initialization completed in 1493 ms
[2m2023-01-02T17:07:01.442+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat started on port(s): 8080 (http) with context path ''
[2m2023-01-02T17:07:01.456+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mcom.apprikart.TempApplication           [0;39m [2m:[0;39m Started TempApplication in 2.802 seconds (process running for 4.043)
[2m2023-01-02T17:07:06.866+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/]      [0;39m [2m:[0;39m Initializing Spring DispatcherServlet 'dispatcherServlet'
[2m2023-01-02T17:07:06.866+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.s.web.servlet.DispatcherServlet       [0;39m [2m:[0;39m Initializing Servlet 'dispatcherServlet'
[2m2023-01-02T17:07:06.867+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.s.web.servlet.DispatcherServlet       [0;39m [2m:[0;39m Completed initialization in 1 ms
enter
</code>```

Hierarchy
enter image description here

Please help me resolve the issue, I'm unable to trace where I'm going wrong.
I have tried almost everything suggested in the internet

Body:
I have a simple project to run on tomcat server, Here it goes

pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/>
    </parent>
    <groupId>com.apprikart</groupId>
    <artifactId>Temp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Temp</name>
    <description>Tempraury</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
            <version>10.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Here is my main class

package com.apprikart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TempApplication {

    public static void main(String[] args) {
        SpringApplication.run(TempApplication.class, args);
    }

}

Controller class

    package com.apprikart.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    public class AppContrl {

        @RequestMapping("/")
        public String fun() {
            System.out.println("enter");
            return "home.jsp";
        }
   }

application.properties

spring.mvc.view.prefix=/webapp/

Console:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
[32m :: Spring Boot :: [39m              [2m (v3.0.1)[0;39m

[2m2023-01-02T17:06:59.336+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mcom.apprikart.TempApplication           [0;39m [2m:[0;39m Starting TempApplication using Java 17.0.4.1 with PID 7336 (C:\Users\HI\Documents\workspace-spring-tool-suite-4-4.16.1.RELEASE\Temp\target\classes started by HI in C:\Users\HI\Documents\workspace-spring-tool-suite-4-4.16.1.RELEASE\Temp)
[2m2023-01-02T17:06:59.342+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mcom.apprikart.TempApplication           [0;39m [2m:[0;39m No active profile set, falling back to 1 default profile: "default"
[2m2023-01-02T17:07:00.262+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mtrationDelegate$BeanPostProcessorChecker[0;39m [2m:[0;39m Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [org.springframework.ws.config.annotation.DelegatingWsConfiguration$$SpringCGLIB$$0] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[2m2023-01-02T17:07:00.326+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36m.w.s.a.s.AnnotationActionEndpointMapping[0;39m [2m:[0;39m Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
[2m2023-01-02T17:07:00.650+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat initialized with port(s): 8080 (http)
[2m2023-01-02T17:07:00.668+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.apache.catalina.core.StandardService  [0;39m [2m:[0;39m Starting service [Tomcat]
[2m2023-01-02T17:07:00.668+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.apache.catalina.core.StandardEngine   [0;39m [2m:[0;39m Starting Servlet engine: [Apache Tomcat/10.1.4]
[2m2023-01-02T17:07:00.930+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.apache.jasper.servlet.TldScanner    [0;39m [2m:[0;39m At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
[2m2023-01-02T17:07:00.941+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/]      [0;39m [2m:[0;39m Initializing Spring embedded WebApplicationContext
[2m2023-01-02T17:07:00.942+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mw.s.c.ServletWebServerApplicationContext[0;39m [2m:[0;39m Root WebApplicationContext: initialization completed in 1493 ms
[2m2023-01-02T17:07:01.442+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat started on port(s): 8080 (http) with context path ''
[2m2023-01-02T17:07:01.456+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[           main][0;39m [36mcom.apprikart.TempApplication           [0;39m [2m:[0;39m Started TempApplication in 2.802 seconds (process running for 4.043)
[2m2023-01-02T17:07:06.866+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/]      [0;39m [2m:[0;39m Initializing Spring DispatcherServlet 'dispatcherServlet'
[2m2023-01-02T17:07:06.866+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.s.web.servlet.DispatcherServlet       [0;39m [2m:[0;39m Initializing Servlet 'dispatcherServlet'
[2m2023-01-02T17:07:06.867+05:30[0;39m [32m INFO[0;39m [35m7336[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.s.web.servlet.DispatcherServlet       [0;39m [2m:[0;39m Completed initialization in 1 ms
enter

Hierarchy
enter image description here

Please help me resolve the issue, I'm unable to trace where I'm going wrong.
I have tried almost everything suggested in the internet


问:
Merge PDF File Using itextsharp and byte Array From Database
I am creating one PDF from iTextSharp, and I have 4 PDF files stored in the database in Binary Format.
I have to merge these files into a single PDF.
My final PDF only contains PDFs from the database and also 1st PDF from the database gets repeated. Following is my code:

```<code>Byte[] bytesdoc = null;
Byte[] bytesdoc1 = null;
Sdetails FileExt = new Sdetails();
bytesdoc = FileExt.creatPDFProfile(lblApplicationno.Text);

Tuple<int, DataTable> _GetFile = GetFile(lblApplicationno.Text);

if ( int.Parse(_GetFile.Item1.ToString())==1)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("DocumenrFile", typeof(byte[]));
    byte[] imageByte = null;
    imageByte = bytesdoc;

    DataRow drNew = dt.NewRow();
    drNew["DocumenrFile"] = imageByte;

    dt.Rows.Add(drNew);
    for (int j = 0; j < _GetFile.Item2.Rows.Count; j++)
    {
        bytesdoc = Combine(_GetFile.Item2.Rows[j]["DocumenrFile"] as byte[]);

        //dt.Rows.Add(drNew.ItemArray);
    }
    // bytesdoc1 = Combine();
    DataTable dtClubNotings = dt;

    //DataTable dtClubNotings = _GetFile.Item2;
    if (dtClubNotings.Rows.Count > 0)
    {
        System.IO.MemoryStream m = new System.IO.MemoryStream();
        iTextSharp.text.Document doc = new iTextSharp.text.Document();
        doc.AddTitle(lblApplicationno.Text);
        PdfCopy pdf = new PdfCopy(doc, m);
        doc.Open();
        PdfReader reader;
        for (int i = 0; i < dtClubNotings.Rows.Count; i++)
        {
            reader = new PdfReader(dtClubNotings.Rows[i]["DocumenrFile"] as byte[]);
            int noofPages = reader.NumberOfPages;
            for (int j = 1; j <= noofPages; j++)
            {
                PdfImportedPage importedPage = pdf.GetImportedPage(reader, j);
                pdf.AddPage(importedPage);
            }
        }
        doc.Close();
        byte[] result;

        result = m.ToArray();
        byte[] _byte2 = (byte[])result;
        Response.Buffer = true;
        Response.AppendHeader("Content-Disposition", "attachment; filename=Profile_Print.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(bytesdoc.ToArray());
        Response.Flush();
    }

}

// Get Database File

Tuple<int, DataTable> GetFile(string _AppNo)
{
    int returnval = 0;
    DataTable _ds = new DataTable();
    SqlConnection _cn = _obj.SqlconnectionHousing();
    _cn.Open();
    SqlCommand _cmd = new SqlCommand(@"select DocumenrFile from tblApplicationDocument where applicationNo=@applicationNo and DocumentId<>'001'", _cn);
    _cmd.Parameters.AddWithValue("@applicationNo", _AppNo);
    SqlDataAdapter da = new SqlDataAdapter(_cmd);
    da.Fill(_ds);
    if (_ds.Rows.Count > 0)
    {
        returnval = 1;
    }
    da.Dispose();
    _ds.Dispose();
    _cmd.Dispose();
    _cn.Close();
    _cn.Dispose();
    return new Tuple<int, DataTable>(returnval,_ds);
}
</code>```

I am creating one PDF from iTextSharp, and I have 4 PDF file stored in the database in Binary Format.
I have to merge these file into single PDF.
My final PDF only contains PDFs from database and also 1st PDF from database gets repeated.

Body:
I am creating one PDF from iTextSharp, and I have 4 PDF files stored in the database in Binary Format.
I have to merge these files into a single PDF.
My final PDF only contains PDFs from the database and also 1st PDF from the database gets repeated. Following is my code:

Byte[] bytesdoc = null;
Byte[] bytesdoc1 = null;
Sdetails FileExt = new Sdetails();
bytesdoc = FileExt.creatPDFProfile(lblApplicationno.Text);

Tuple<int, DataTable> _GetFile = GetFile(lblApplicationno.Text);

if ( int.Parse(_GetFile.Item1.ToString())==1)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("DocumenrFile", typeof(byte[]));
    byte[] imageByte = null;
    imageByte = bytesdoc;

    DataRow drNew = dt.NewRow();
    drNew["DocumenrFile"] = imageByte;

    dt.Rows.Add(drNew);
    for (int j = 0; j < _GetFile.Item2.Rows.Count; j++)
    {
        bytesdoc = Combine(_GetFile.Item2.Rows[j]["DocumenrFile"] as byte[]);

        //dt.Rows.Add(drNew.ItemArray);
    }
    // bytesdoc1 = Combine();
    DataTable dtClubNotings = dt;

    //DataTable dtClubNotings = _GetFile.Item2;
    if (dtClubNotings.Rows.Count > 0)
    {
        System.IO.MemoryStream m = new System.IO.MemoryStream();
        iTextSharp.text.Document doc = new iTextSharp.text.Document();
        doc.AddTitle(lblApplicationno.Text);
        PdfCopy pdf = new PdfCopy(doc, m);
        doc.Open();
        PdfReader reader;
        for (int i = 0; i < dtClubNotings.Rows.Count; i++)
        {
            reader = new PdfReader(dtClubNotings.Rows[i]["DocumenrFile"] as byte[]);
            int noofPages = reader.NumberOfPages;
            for (int j = 1; j <= noofPages; j++)
            {
                PdfImportedPage importedPage = pdf.GetImportedPage(reader, j);
                pdf.AddPage(importedPage);
            }
        }
        doc.Close();
        byte[] result;

        result = m.ToArray();
        byte[] _byte2 = (byte[])result;
        Response.Buffer = true;
        Response.AppendHeader("Content-Disposition", "attachment; filename=Profile_Print.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(bytesdoc.ToArray());
        Response.Flush();
    }

}

// Get Database File

Tuple<int, DataTable> GetFile(string _AppNo)
{
    int returnval = 0;
    DataTable _ds = new DataTable();
    SqlConnection _cn = _obj.SqlconnectionHousing();
    _cn.Open();
    SqlCommand _cmd = new SqlCommand(@"select DocumenrFile from tblApplicationDocument where applicationNo=@applicationNo and DocumentId<>'001'", _cn);
    _cmd.Parameters.AddWithValue("@applicationNo", _AppNo);
    SqlDataAdapter da = new SqlDataAdapter(_cmd);
    da.Fill(_ds);
    if (_ds.Rows.Count > 0)
    {
        returnval = 1;
    }
    da.Dispose();
    _ds.Dispose();
    _cmd.Dispose();
    _cn.Close();
    _cn.Dispose();
    return new Tuple<int, DataTable>(returnval,_ds);
}

I am creating one PDF from iTextSharp, and I have 4 PDF file stored in the database in Binary Format.
I have to merge these file into single PDF.
My final PDF only contains PDFs from database and also 1st PDF from database gets repeated.


问:
Junit for KafkaProducer from kafka-clients in Java
We are using org.apache.kafka.clients.producer.KafkaProducer from kafka-clients-1.0.0 for producing messages to broker.

Now, we need to write junit test case for this producer to send messages to mock kafka cluster

org.apache.kafka.clients.producer.MockProducer is there, but unable to use since both (KafkaProducer and MockProducer are impl of Producer)

Note: We need to spin up mock Kafka broker to execute junit test case.

Note2: We need to initialize KakfaProducer with mock brokers and send messages to queue


问:
Skip Crop or Add Custom Footer in antd-img-crop
Is it possible in anyways to either add a skip option in ImageCrop or add customFooter and add different buttons in there?

```<code><ImgCrop
  aspect={1 / 1}
  ref={this.imageCropper}
  shape="rect"
  modalTitle="Crop Artwork"
>
  <Upload
    name="avatar"
    listType="picture-card"
    className="art-uploader"
    showUploadList={false}
    customRequest={this.onArtImageChange.bind(this, item.id)}
    id={"image-" + item.id}
    style={{ width: "250px", height: "250px" }}
  ></Upload>
</ImgCrop>;
</code>```

A modal opens on image select, so I need to add skip option in that, I tried beforeCrop prop but setting it true will simply not open the pop up and thus no further actions can be performed. I also tried adding customFooter by using customFooter as mentioned in antd Modals, but it didn't work.

Body:
Is it possible in anyways to either add a skip option in ImageCrop or add customFooter and add different buttons in there?

<ImgCrop
  aspect={1 / 1}
  ref={this.imageCropper}
  shape="rect"
  modalTitle="Crop Artwork"
>
  <Upload
    name="avatar"
    listType="picture-card"
    className="art-uploader"
    showUploadList={false}
    customRequest={this.onArtImageChange.bind(this, item.id)}
    id={"image-" + item.id}
    style={{ width: "250px", height: "250px" }}
  ></Upload>
</ImgCrop>;

A modal opens on image select, so I need to add skip option in that, I tried beforeCrop prop but setting it true will simply not open the pop up and thus no further actions can be performed. I also tried adding customFooter by using customFooter as mentioned in antd Modals, but it didn't work.


问:
How to create a zone with specific IAM permissions in Cloud DNS
I'm getting an error trying to set DNS zone permissions. I'm following official instruction for a feature released in GA on Dec 5th 2022 "Cloud DNS per resource IAM permissions". I'm trying to resolve issue described in this post. Unfortunately I always get You don't have permission to edit the permissions of the selected resource despite of the fact my account seem to have suitable roles.

What I did was:

assign "DNS Administrator" role to my account in IAM (see: my IAM roles)

create a public managed zone in Cloud DNS

tick the check-box for the zone and click on "Permissions" button at the top

Result is this permissions warning.
Still I believe my account is granted "DNS Administrator" role as suggested in the official instruction.

Is this something related to IAM roles/permissions or Cloud DNS issue?

Edit: do not know how to get it working with DNS roles but when assigned Owner role I was able to edit DNS zone permissions.


问:
No plugin found for prefix 'deploy' in the current project and in the plugin groups
I am trying to upload an artifact which is not built by Maven. I am running the following cmd:

```<code>@mvn deploy:deploy-file -Dfile=C:\Users\XX\myArtifact.zip -Dname=myArtifact -DartifactId=ServerBinaries -DgroupId=org.myArtifact -Dversion=1.0.0 -Dpackaging=zip -DrepositoryId=xxxx -Durl=http://xxxx/repository/thirdparty -DgeneratePom=true
</code>```

And ending up getting an error:

No plugin found for prefix 'deploy' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (C:\Users\XXXX.m2\repository), central (https://repo.maven.apache.org/maven2)] -> [Help 1]

Which is preceded by a bunch of warnings (all are similar):

[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-clean-plugin:2.5: Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.4/maven-install-plugin-2.4.pom

My maven version:

```<code>mvn --version
Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d)
Maven home: C:\Repo\Build\apache-maven-3.8.1\bin\..
Java version: 1.8.0_341, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk1.8.0_341\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
</code>```

Why is maven not being able download the plugins?
How can I upload a file?

Body:
I am trying to upload an artifact which is not built by Maven. I am running the following cmd:

@mvn deploy:deploy-file -Dfile=C:\Users\XX\myArtifact.zip -Dname=myArtifact -DartifactId=ServerBinaries -DgroupId=org.myArtifact -Dversion=1.0.0 -Dpackaging=zip -DrepositoryId=xxxx -Durl=http://xxxx/repository/thirdparty -DgeneratePom=true

And ending up getting an error:

No plugin found for prefix 'deploy' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (C:\Users\XXXX.m2\repository), central (https://repo.maven.apache.org/maven2)] -> [Help 1]

Which is preceded by a bunch of warnings (all are similar):

[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-clean-plugin:2.5: Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.4/maven-install-plugin-2.4.pom

My maven version:

mvn --version
Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d)
Maven home: C:\Repo\Build\apache-maven-3.8.1\bin\..
Java version: 1.8.0_341, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk1.8.0_341\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

Why is maven not being able download the plugins?
How can I upload a file?


问:
Loading text file in Jupyter notebook
enter image description here
enter image description here

I tried loading a notepad textfile in my jupyter notebook but it has not been successful. I tried including the file path but all to no avail. Please can someone help me out. Thank you

Title: Loading text file in Jupyter notebook


问:
Vis Network: Node Customization
My requirement is to show on nodes as in the image.

I got the colors, icons everything except the alert badge kind of notation on top of nodes.

Can anyone help me with the approach I have to take ??

Click here for an image of my requirement

Title: Vis Network: Node Customization


问:
HERE API - Matrix routing yields "These credentials do not authorize access"
If I try to use the Matrix Routing service, I get the following error message:

```<code>  "error": "Forbidden",
  "error_description": "These credentials do not authorize access"
</code>```

I created a free Here developer account to use the Matrix Routing service. When I go to my Subscription & Billing Overview and look at my products in the Subscription, I see that "Matrix Routing" is included in my plan. However, when I go to Services in the Launcher and select my project, the "Matrix Routing" service is no longer suggested. As a result, when I make the following request in Python:

```<code>import requests,json

url = f'https://matrix.router.hereapi.com/v8/matrix?apiKey={MY_API_KEY}&async=false'
headers = {'Content-Type': 'application/json'}

payload = {
    "origins": [
        { "lat": 37.76, "lng": -122.42 },
        { "lat": 40.63, "lng": -74.09 },
        { "lat": 30.26, "lng": -97.74 }
    ],
    "regionDefinition": {
        "type": "world"
    },
    "matrixAttributes": ["distances"]
}

r = requests.post(url, headers=headers, data=json.dumps(payload))

print(json.dumps(r.json(), indent=2))
</code>```

the error message:

```<code>  "error": "Forbidden",
  "error_description": "These credentials do not authorize access"
</code>```

Where can I activate that I can use matrix routing?

Body:
If I try to use the Matrix Routing service, I get the following error message:

  "error": "Forbidden",
  "error_description": "These credentials do not authorize access"

I created a free Here developer account to use the Matrix Routing service. When I go to my Subscription & Billing Overview and look at my products in the Subscription, I see that "Matrix Routing" is included in my plan. However, when I go to Services in the Launcher and select my project, the "Matrix Routing" service is no longer suggested. As a result, when I make the following request in Python:

import requests,json

url = f'https://matrix.router.hereapi.com/v8/matrix?apiKey={MY_API_KEY}&async=false'
headers = {'Content-Type': 'application/json'}

payload = {
    "origins": [
        { "lat": 37.76, "lng": -122.42 },
        { "lat": 40.63, "lng": -74.09 },
        { "lat": 30.26, "lng": -97.74 }
    ],
    "regionDefinition": {
        "type": "world"
    },
    "matrixAttributes": ["distances"]
}

r = requests.post(url, headers=headers, data=json.dumps(payload))

print(json.dumps(r.json(), indent=2))

the error message:

  "error": "Forbidden",
  "error_description": "These credentials do not authorize access"

Where can I activate that I can use matrix routing?


问:
jest with react useState is not Override
I have the following to
useState hooks:

```<code>const [file, setFile] = useState(null);
const [isLoading, setIsLoading] = useState(false);
</code>```

this is my test:

```<code>
  test('Happy path', async () => {
    jest
      .spyOn(React, 'useState')
      .mockImplementationOnce(() => [true, () => null])
      .mockImplementationOnce(() => [false, () => null]);
    render(<NarcUploadWindow {...mockPropsSuccess} />);
    const sendButton = await waitFor(() => screen.findByText(`Send`));
    fireEvent.click(sendButton);
    expect(mockPropsSuccess.showSuccessToasterMessage).toHaveBeenCalled();
  });

</code>```

problem is the file field remains null and the isLoading also doesn't change if I try to set it to true, I have also tried:

```<code>import * as React from 'react';
...
const [file, setFile] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(false);
</code>```

basically all four of combinations the import and the useState

however the problem remains the same,
I saw this post:
enzyme react useState

but I don't want to use enzyme so the majority of the solutions are not valid without using it

any help on how can I change the initial state of the hooks using jest?

Body:
I have the following to
useState hooks:

const [file, setFile] = useState(null);
const [isLoading, setIsLoading] = useState(false);

this is my test:

  test('Happy path', async () => {
    jest
      .spyOn(React, 'useState')
      .mockImplementationOnce(() => [true, () => null])
      .mockImplementationOnce(() => [false, () => null]);
    render(<NarcUploadWindow {...mockPropsSuccess} />);
    const sendButton = await waitFor(() => screen.findByText(`Send`));
    fireEvent.click(sendButton);
    expect(mockPropsSuccess.showSuccessToasterMessage).toHaveBeenCalled();
  });

problem is the file field remains null and the isLoading also doesn't change if I try to set it to true, I have also tried:

import * as React from 'react';
...
const [file, setFile] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(false);

basically all four of combinations the import and the useState

however the problem remains the same,
I saw this post:
enzyme react useState

but I don't want to use enzyme so the majority of the solutions are not valid without using it

any help on how can I change the initial state of the hooks using jest?


问:
TLS comunnication with OpenSSL RSA certificates supported but ECC not
Can someone help me ? I have simple program written in c using OpenSSL library, which implements network communication on the localhost[client-server communicatiom] with TLS method. When i use RSA certificates it works fine, but when i use ECC certificates i will get error:

Client side: 28310000:error:0A000086:SSL routines:tls_post_process_server_certificate:certificate verify failed:ssl\statem\statem_clnt.c:1888:

Server side: 244D0000:error:0A000418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca:ssl\record\rec_layer_s3.c:1584:SSL alert number 48

where could be the problem ? I use OpenSSL version 3.0.7

I tried enable algorithms using function SSL_CTX_set1_groups_list() but not works


问:
react router dont work if trying access other page direct by the URL
I have been experiencing an issue in which the page redirection in my app does not work as intended when I publish it on a hosting platform, such as firebase hosting. Specifically, I have noticed that when I test the app locally during development, I am able to navigate between pages using both the <Link> elements and by directly changing the path in the URL. However, when I build the app and publish it, the page redirection only works when using the <Link> elements and not when attempting to change the path in the URL. This results in an error message stating that no page was found.

the router logic that I made:

```<code>const router = createBrowserRouter([
    {
        path: "/",
        element: <Home />,
    },
    {
        path: "/contacts",
        element: <Contacts />,
    },
]);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <RouterProvider router={router} />
    </React.StrictMode>
);
</code>```

the firebase.json:

```<code>{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}
</code>```

I don't know if these informations are enough, if there is something more that I can provide just tell-me.

Body:
I have been experiencing an issue in which the page redirection in my app does not work as intended when I publish it on a hosting platform, such as firebase hosting. Specifically, I have noticed that when I test the app locally during development, I am able to navigate between pages using both the <Link> elements and by directly changing the path in the URL. However, when I build the app and publish it, the page redirection only works when using the <Link> elements and not when attempting to change the path in the URL. This results in an error message stating that no page was found.

the router logic that I made:

const router = createBrowserRouter([
    {
        path: "/",
        element: <Home />,
    },
    {
        path: "/contacts",
        element: <Contacts />,
    },
]);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <RouterProvider router={router} />
    </React.StrictMode>
);

the firebase.json:

{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

I don't know if these informations are enough, if there is something more that I can provide just tell-me.


问:
Deploying Laravel Project on Hostinger
I have a laravel project it works fine on my local machine but when I deployed it on Hostinger Shared Hosting and moved public files to project folder in public_html and put other project files in framework folder next to public files everythings works fine except accessing storage files using asset()

```<code><img src="{{asset('storage/members-imgs/'. $member->image)}}" class="img-fluid" alt="{{$member->first_name . ' ' . $member->last_name}}" height="350" >
</code>```

I tried to keep public folder that contains storage folder (link to storage/app/public) in framework folder, but nothing changed, also tried to move storage folder (link to storage/app/public) to laravel project root next to index.php but nothing changed.

Title: Deploying Laravel Project on Hostinger

Body:
I have a laravel project it works fine on my local machine but when I deployed it on Hostinger Shared Hosting and moved public files to project folder in public_html and put other project files in framework folder next to public files everythings works fine except accessing storage files using asset()

image)}}" class="img-fluid" alt="{{$member->first_name . ' ' . $member->last_name}}" height="350" >

I tried to keep public folder that contains storage folder (link to storage/app/public) in framework folder, but nothing changed, also tried to move storage folder (link to storage/app/public) to laravel project root next to index.php but nothing changed.


问:
It is possible to add Google Analitics cookies without scirpt?
it's possible that somethink is setting google analitics _ga and _gid cookies without script in code in my app ?

I am starting work in old project Angular + .Net and this cookies are randomly set but I can't found any code to do this. I have not working with google analitics yet.

The only think that I found it was Content Security Policy allow to :

"Content-Security-Policy": ...; script-src 'self' https://www.googletagmanager.com ; ... ; connect-src 'self' https://api.someDomain.com wss://api.someDomain.com https://analytics.google.com ;...

It's possible that this is a source of this cookies ? I know that others app under the same domain are using google analitics.


问:
Facing issue after converting code from JavaScript to CoffeeScript, Code is not working nor displaying any Error?
```<code>  counters = document.querySelectorAll('.counter')
  counters.forEach (counter) ->
  incrementButton = counter.querySelector('.plus')
  decrementButton = counter.querySelector('.minus')
  countElement = counter.querySelector('.count')
  incrementButton.addEventListener 'click', ->
    # Increment the count
    count = parseInt(countElement.textContent, 10)
    count++
    countElement.textContent = count
    return
  decrementButton.addEventListener 'click', ->
    # Decrement the count
    count = parseInt(countElement.textContent, 10)
    if count > 0
      count--
      countElement.textContent = count
    # count--;
    countElement.textContent = count
    return
  return
</code>```

I am using Qunanity Operator for increment and decrement, it is working fine in javascript but after converting it to Coffescript it is not working and not displaying any error in console

Body:
  counters = document.querySelectorAll('.counter')
  counters.forEach (counter) ->
  incrementButton = counter.querySelector('.plus')
  decrementButton = counter.querySelector('.minus')
  countElement = counter.querySelector('.count')
  incrementButton.addEventListener 'click', ->
    # Increment the count
    count = parseInt(countElement.textContent, 10)
    count++
    countElement.textContent = count
    return
  decrementButton.addEventListener 'click', ->
    # Decrement the count
    count = parseInt(countElement.textContent, 10)
    if count > 0
      count--
      countElement.textContent = count
    # count--;
    countElement.textContent = count
    return
  return

I am using Qunanity Operator for increment and decrement, it is working fine in javascript but after converting it to Coffescript it is not working and not displaying any error in console


问:
How to remove other animation frame at the bottom of an animation in HTML canvas?
I am fairly new to programming with HTML and programming in general so I have no idea what went wrong here..

I was following a video by Coding With Adam (link: https://www.youtube.com/watch?v=yTlmOpW6kOc) up until the point where he teaches how to animate the character (around 18:35), which means that I have almost the same code as him. However, when I try to test my animation, there is always a frame for the idle animation at the back (see gif for reference).

idle frame behind my walking animation

This is my Player.js:

```<code>import PlayerStates from './PlayerStates.js';
import SpriteAnimation from "./SpriteAnimation.js"

export default class Player{
    constructor(){
        this.state = PlayerStates.idle;
        this.#createAnimations();
    }

    draw(ctx){
        const image = this.rightAnimation.getImage();
        const x = 17;
        const y = 16;
        ctx.drawImage(image,x,y);
    }

    #createAnimations(){
        this.idleAnimation = new SpriteAnimation(
            "head_idle (?).png",
            1,
            1,
            PlayerStates.idle
        );
        this.rightAnimation = new SpriteAnimation(
            "head_right (?).png",
            8,
            4,
            PlayerStates.right
        );
    }
}
</code>```

And this is my SpriteAnimation.js

```<code>import img from "./img.js";

export default class SpriteAnimation {
    images = [];
    constructor(fileNameTemplate, numberOfImages, timerCount, state){
        for(let i=1; i <=numberOfImages; i++) {
            const image = img(fileNameTemplate.replace("?", i));
            this.images.push(image);
        }
        this.timerCount = timerCount;
        this.timerCountDefault = this.timerCount;
        this.imageIndex = 0;
        this.state = state;
    }

    isFor(state){
        return this.state === state;
    }

    reset(){
        this.imageIndex = 0;
    }

    getImage(){
        this.#setImageIndex();
        return this.images[this.imageIndex];
    }

    #setImageIndex(){
        this.timerCount--;
        if(this.timerCount == 0){
            this.timerCount = this.timerCountDefault;
            this.imageIndex++;
            if (this.imageIndex >= this.images.length){
                this.imageIndex = 0;
            }
        }
    }
}
</code>```

Any help is appreciated, thank you!

Body:
I am fairly new to programming with HTML and programming in general so I have no idea what went wrong here..

I was following a video by Coding With Adam (link: https://www.youtube.com/watch?v=yTlmOpW6kOc) up until the point where he teaches how to animate the character (around 18:35), which means that I have almost the same code as him. However, when I try to test my animation, there is always a frame for the idle animation at the back (see gif for reference).

idle frame behind my walking animation

This is my Player.js:

import PlayerStates from './PlayerStates.js';
import SpriteAnimation from "./SpriteAnimation.js"

export default class Player{
    constructor(){
        this.state = PlayerStates.idle;
        this.#createAnimations();
    }

    draw(ctx){
        const image = this.rightAnimation.getImage();
        const x = 17;
        const y = 16;
        ctx.drawImage(image,x,y);
    }

    #createAnimations(){
        this.idleAnimation = new SpriteAnimation(
            "head_idle (?).png",
            1,
            1,
            PlayerStates.idle
        );
        this.rightAnimation = new SpriteAnimation(
            "head_right (?).png",
            8,
            4,
            PlayerStates.right
        );
    }
}

And this is my SpriteAnimation.js

import img from "./img.js";

export default class SpriteAnimation {
    images = [];
    constructor(fileNameTemplate, numberOfImages, timerCount, state){
        for(let i=1; i <=numberOfImages; i++) {
            const image = img(fileNameTemplate.replace("?", i));
            this.images.push(image);
        }
        this.timerCount = timerCount;
        this.timerCountDefault = this.timerCount;
        this.imageIndex = 0;
        this.state = state;
    }

    isFor(state){
        return this.state === state;
    }

    reset(){
        this.imageIndex = 0;
    }

    getImage(){
        this.#setImageIndex();
        return this.images[this.imageIndex];
    }

    #setImageIndex(){
        this.timerCount--;
        if(this.timerCount == 0){
            this.timerCount = this.timerCountDefault;
            this.imageIndex++;
            if (this.imageIndex >= this.images.length){
                this.imageIndex = 0;
            }
        }
    }
}

Any help is appreciated, thank you!


问:
ASP.NET Net 7.0 I cannot run the debugger while "watch"
This is mine:

https://imgur.com/gallery/NC5sA1i

When I run the debugger, the dotnet watch is running, but it's in the Terminal process, not the debugger process. On the red arrow, you can see the VSCode never finishes booting the debugger.

this is the launch.json file

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "watch",
            "launchSettingsProfile": "https",
            "program": "${workspaceFolder}/website-app/bin/Debug/net7.0/website-app.dll",
            "args": [],
            "cwd": "${workspaceFolder}/website-app",
            "stopAtEntry": false,
            "serverReadyAction": {
                "action": "openExternally",
                "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceFolder}/Views"
            }
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach"
        }
    ]
}
</code>```

and this is the tasks.json file:

```<code>{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/website-app/website-app.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "publish",
            "command": "dotnet",
            "type": "process",
            "args": [
                "publish",
                "${workspaceFolder}/website-app/website-app.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "watch",
            "command": "dotnet",
            "type": "process",
            "args": [
                "watch",
                "run",
                "--project",
                "${workspaceFolder}/website-app/website-app.csproj"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}
</code>```

I'm following this tutorial:

https://youtu.be/fuBi4d7k1-M?t=1327

at 22:07, he just change the preLaunchTask: build to preLaunchTask: watch

I tried exactly what he did, but I can't figure out why my debugger is not working.

Tried on macOS and Windows, same result.

Please help.

Thanks in advance

Body:
This is mine:

https://imgur.com/gallery/NC5sA1i

When I run the debugger, the dotnet watch is running, but it's in the Terminal process, not the debugger process. On the red arrow, you can see the VSCode never finishes booting the debugger.

this is the launch.json file

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "watch",
            "launchSettingsProfile": "https",
            "program": "${workspaceFolder}/website-app/bin/Debug/net7.0/website-app.dll",
            "args": [],
            "cwd": "${workspaceFolder}/website-app",
            "stopAtEntry": false,
            "serverReadyAction": {
                "action": "openExternally",
                "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceFolder}/Views"
            }
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach"
        }
    ]
}

and this is the tasks.json file:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/website-app/website-app.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "publish",
            "command": "dotnet",
            "type": "process",
            "args": [
                "publish",
                "${workspaceFolder}/website-app/website-app.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "watch",
            "command": "dotnet",
            "type": "process",
            "args": [
                "watch",
                "run",
                "--project",
                "${workspaceFolder}/website-app/website-app.csproj"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}

I'm following this tutorial:

https://youtu.be/fuBi4d7k1-M?t=1327

at 22:07, he just change the preLaunchTask: build to preLaunchTask: watch

I tried exactly what he did, but I can't figure out why my debugger is not working.

Tried on macOS and Windows, same result.

Please help.

Thanks in advance


问:
NLTK remove random words produces 'TypeError: expected string or bytes-like object'
I'm trying to remove random words from text in a column with nltk.
Here is my code:

```<code>import pandas as pd
import nltk
import nltknltk.download('punkt')
from nltk.tokenize import word_tokenize

df = pd.read_excel("Output_Summarization/OUTPUT_ocr_OPENAIGOOD.xlsx", usecols=["Open_AI_Text"])

for index, row in df.iterrows():

words = word_tokenize(row["Open_AI_Text"])

word_to_remove = random.choice(words)

new_text = row["Open_AI_Text"].replace(word_to_remove, "")

df.at[index, "Open_AI_Text"] = new_text

df.to_excel("Texte_Trou.xlsx", index=False)
</code>```

Next I have an error :

TypeError
Traceback (most recent call last)<ipython-input-51-3cb2fde32407> in <module>11
for index, row in df.iterrows():12
   # tokeniser le texte de la ligne en mots individuels13
   words = word_tokenize(row["Open_AI_Text"])1415
   # choisir un mot au hasard à enlever

/usr/local/lib/python3.6/site-packages/nltk/tokenize/init.py in
 word_tokenize(text, language, preserve_line)126
     :type preserver_line: bool127
     """128
     sentences = [text] if preserve_line else sent_tokenize(text, language)129
     return [token for sent in sentences130
             for token in _treebank_word_tokenizer.tokenize(sent)]

/usr/local/lib/python3.6/site-packages/nltk/tokenize/init.py in
 sent_tokenize(text, language)93
     """94     tokenizer = load('tokenizers/punkt/{0}.pickle'.format(language))95
     return tokenizer.tokenize(text)9697 # Standard word tokenizer.

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 tokenize(self, text, realign_boundaries)1235
         Given a text, returns a list of the sentences in that text.1236
         """1237
         return list(self.sentences_from_text(text, realign_boundaries))12381239
     def debug_decisions(self, text):

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 sentences_from_text(self, text, realign_boundaries)1283
         follows the period.1284
         """1285
         return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]12861287
     def _slices_from_text(self, text):

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 span_tokenize(self, text, realign_boundaries)1274
         if realign_boundaries:1275
             slices = self._realign_boundaries(text, slices)1276
         return [(sl.start, sl.stop) for sl in slices]12771278
     def sentences_from_text(self, text, realign_boundaries=True):

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 <listcomp>(.0)1274
         if realign_boundaries:1275
             slices = self._realign_boundaries(text, slices)1276
         return [(sl.start, sl.stop) for sl in slices]12771278
     def sentences_from_text(self, text, realign_boundaries=True):

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in _realign_boundaries(self, text, slices)1314
         """1315         realign = 01316
         for sl1, sl2 in _pair_iter(slices):1317
             sl1 = slice(sl1.start + realign, sl1.stop)1318
             if not sl2:

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 _pair_iter(it)310
     """311     it = iter(it)312
     prev = next(it)313
     for el in it:314
         yield (prev, el)

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 _slices_from_text(self, text)1287
     def _slices_from_text(self, text):1288
         last_break = 01289
         for match in self._lang_vars.period_context_re().finditer(text):1290
             context = match.group() + match.group('after_tok')1291
             if self.text_contains_sentbreak(context):

TypeError: expected string or bytes-like object
```

I tried to replace my variable with a list but this didn't work, how can I solve this issue?

Body:
I'm trying to remove random words from text in a column with nltk.
Here is my code:

import pandas as pd
import nltk
import nltknltk.download('punkt')
from nltk.tokenize import word_tokenize

df = pd.read_excel("Output_Summarization/OUTPUT_ocr_OPENAIGOOD.xlsx", usecols=["Open_AI_Text"])

for index, row in df.iterrows():

words = word_tokenize(row["Open_AI_Text"])

word_to_remove = random.choice(words)

new_text = row["Open_AI_Text"].replace(word_to_remove, "")

df.at[index, "Open_AI_Text"] = new_text

df.to_excel("Texte_Trou.xlsx", index=False)

Next I have an error :

TypeError
Traceback (most recent call last)<ipython-input-51-3cb2fde32407> in <module>11
for index, row in df.iterrows():12
   # tokeniser le texte de la ligne en mots individuels13
   words = word_tokenize(row["Open_AI_Text"])1415
   # choisir un mot au hasard à enlever

/usr/local/lib/python3.6/site-packages/nltk/tokenize/init.py in
 word_tokenize(text, language, preserve_line)126
     :type preserver_line: bool127
     """128
     sentences = [text] if preserve_line else sent_tokenize(text, language)129
     return [token for sent in sentences130
             for token in _treebank_word_tokenizer.tokenize(sent)]

/usr/local/lib/python3.6/site-packages/nltk/tokenize/init.py in
 sent_tokenize(text, language)93
     """94     tokenizer = load('tokenizers/punkt/{0}.pickle'.format(language))95
     return tokenizer.tokenize(text)9697 # Standard word tokenizer.

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 tokenize(self, text, realign_boundaries)1235
         Given a text, returns a list of the sentences in that text.1236
         """1237
         return list(self.sentences_from_text(text, realign_boundaries))12381239
     def debug_decisions(self, text):

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 sentences_from_text(self, text, realign_boundaries)1283
         follows the period.1284
         """1285
         return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]12861287
     def _slices_from_text(self, text):

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 span_tokenize(self, text, realign_boundaries)1274
         if realign_boundaries:1275
             slices = self._realign_boundaries(text, slices)1276
         return [(sl.start, sl.stop) for sl in slices]12771278
     def sentences_from_text(self, text, realign_boundaries=True):

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 <listcomp>(.0)1274
         if realign_boundaries:1275
             slices = self._realign_boundaries(text, slices)1276
         return [(sl.start, sl.stop) for sl in slices]12771278
     def sentences_from_text(self, text, realign_boundaries=True):

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in _realign_boundaries(self, text, slices)1314
         """1315         realign = 01316
         for sl1, sl2 in _pair_iter(slices):1317
             sl1 = slice(sl1.start + realign, sl1.stop)1318
             if not sl2:

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 _pair_iter(it)310
     """311     it = iter(it)312
     prev = next(it)313
     for el in it:314
         yield (prev, el)

/usr/local/lib/python3.6/site-packages/nltk/tokenize/punkt.py in
 _slices_from_text(self, text)1287
     def _slices_from_text(self, text):1288
         last_break = 01289
         for match in self._lang_vars.period_context_re().finditer(text):1290
             context = match.group() + match.group('after_tok')1291
             if self.text_contains_sentbreak(context):

TypeError: expected string or bytes-like object

I tried to replace my variable with a list but this didn't work, how can I solve this issue?


问:
External api call in php working fine but giving error in Jquery
I have the following code for external api call in php that works fine however when I do this with jquery it gives CORS policy error .

```<code>$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: ' . $token,'Accept: application/json'));
curl_setopt($curl, CURLOPT_URL, 'http://api.evalu-8.com/employee/readall');//?active=true
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

$result = curl_exec($curl);
curl_close($curl);
</code>```

However when I do the same in jquery it gives error : "Access to XMLHttpRequest at "" from origin "" has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status"

```<code>$.ajax({
url:'http://api.evalu-8.com/employee/readall',
crossDomain:true,
type: 'GET',
headers: {
  'Access-Control-Allow-Origin': '*',
  'Content-Type':'application/json'
},
beforeSend: function (xhr) {
  xhr.setRequestHeader('Authorization: Bearer ', 'token');
},
success:function(response){
}
});
</code>```

Body:
I have the following code for external api call in php that works fine however when I do this with jquery it gives CORS policy error .

$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: ' . $token,'Accept: application/json'));
curl_setopt($curl, CURLOPT_URL, 'http://api.evalu-8.com/employee/readall');//?active=true
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

$result = curl_exec($curl);
curl_close($curl);

However when I do the same in jquery it gives error : "Access to XMLHttpRequest at "" from origin "" has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status"

$.ajax({
url:'http://api.evalu-8.com/employee/readall',
crossDomain:true,
type: 'GET',
headers: {
  'Access-Control-Allow-Origin': '*',
  'Content-Type':'application/json'
},
beforeSend: function (xhr) {
  xhr.setRequestHeader('Authorization: Bearer ', 'token');
},
success:function(response){
}
});


问:
cmake + visual studio - select minor toolset version
I have a project for which I generate a visual studio solution using cmake. That project links against a library built by a specific compiler version, which I cannot change / update! Therefore I need to compile my project with the same compiler version.

There are ways to setup the minor toolset version using CMake, however none of those that I have found are working like Id want them to.
The problem is: I can generate my vs solution and have cmake select the correct toolset version. However when I build the project with Visual Studio the compiler version does not match the version selected by cmake. I presume this is due to the fact, that Visual Studio does not care about CMakes build "ideas" and does not easily allow a minor toolset selection.

The only solution I have found so far is described in this link: https://devblogs.microsoft.com/cppblog/side-by-side-minor-version-msvc-toolsets-in-visual-studio-2019/
In Short you can (manually) edit every *.vcxproj File and override the toolset version with an import like so
<Import Project="$(SolutionDir)\Microsoft.VCToolsVersion.14.20.props" />. I wish to do this via the CMakeLists.txt or an argument, when generating the solution. I have tried:

Specifying the exact toolset version via the "-T" argument like so: -T v142,version=14.28.16.9 />

Modifying a "vcvarsall.bat" to pass the correct toolset version by appending "-vcvars_ver=14.28". This makes Cmake select the correct compiler.

For boths methods VS does not care. The only way I found working is modifying the *.vcxproj by hand. Otherwise VS always picks the newest minor version of the selected toolset (in my case v142).


问:
Donut chart with custom tooltip using Chartist in React
I am creating a donut chart using Chartist but unable to add a custom tooltip with resize slice on the mouse hover event. Chartist "Draw" method is rerender on changing the position of mouse on hover of the chart
I pasted my code as below:

```<code>/* eslint-disable no-unused-vars */
import React, {useState} from 'react'
import PropTypes from 'prop-types'
import ChartistGraph from 'react-chartist'
import Chartist from 'chartist'
import styles from './MyChart.scss'
import {formatNumber} from '../../../../utils/formatter'
import MyChartInfo from './MyChartInfo'

function MyChart ({ dataSeries, getDetailsTable }) {
  const [changePercent, setChangePercent] = useState(0)
  const [showToolTip, setShowToolTip] = useState(false)
  const [myChartInfoDetails, setMyChartInfoDetails] = useState({sectorName: '', changePercent: ''})
  const [toolTipPosition, setToolTipPosition] = useState({})

  function setToolTip () {
    const PopOverData = [myChartInfoDetails.sectorName || '', `% Return: ${myChartInfoDetails.changePercent || ''}`, '(Click to view top & worst performing equities)']
    return (<MyChartInfo dataTable={PopOverData} style={toolTipPosition} />)
  }
  let pieOptions = {
    width: '520px',
    height: '520px',
    donut: true,
    donutWidth: 150,
    donutSolid: false,
    startAngle: 270,
    showLabel: true,
    chartPadding: 60,
    labelOffset: 105,
    labelDirection: 'explode',
    labelInterpolationFnc: function (value) {
      return value
    }
  }
  let pieData = {
    series: dataSeries && dataSeries.length > 0 ? dataSeries.map(item => Math.abs(item.value)) : [100],
    labels: dataSeries && dataSeries.length > 0 ? dataSeries.map(item => item.name.concat('<br>', formatNumber(item.value, {precision: 2, negSign: true, posSign: true}))) : ['']
  }
  // eslint-disable-next-line no-unused-vars
  const listner = {
    created: (chart) => {
      const chartPie = document.querySelectorAll('.ct-chart-donut .ct-slice-donut')
      chartPie && chartPie.forEach((pie) => {
        pie.addEventListener('mouseenter', (e) => {
          e.stopPropagation()
          pie.setAttribute('style', 'stroke-width: 170px;')
          console.log('hover aa  ', changePercent, Math.abs(pie.getAttribute('ct:value')))
          setChangePercent(Math.abs(pie.getAttribute('ct:value')))
          let topPosition = e.layerY + 30
          let leftPosition = e.layerX + 30
          setToolTipPosition({top: topPosition, left: leftPosition})
          const myChartData = dataSeries.find(sector => Math.abs(sector.value) === Math.abs(pie.getAttribute('ct:value')))
          setSectorDetails({sectorName: myChartData.name, changePercent: myChartData.value})
          setShowToolTip(true)
        })
        pie.addEventListener('mouseleave', (e) => {
          pie.setAttribute('style', 'stroke-width: 150px;')
          setShowToolTip(false)
        })
        pie.addEventListener('click', (e) => {
          const Id = dataSeries.find(sector => Math.abs(sector.value) === Math.abs(pie.getAttribute('ct:value'))).id.toString()
          console.log('click ', Id, pie.getAttribute('ct:value'))
          getDetailsTable(Id)
        })
      })
    },
    draw: (data) => {
      // console.log('data', data)
      if (data.type === 'slice') {
        // Get the total path length in order to use for dash array animation
        var pathLength = data.element._node.getTotalLength()

        // Set a dasharray that matches the path length as prerequisite to animate dashoffset
        data.element.attr({
          'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
        })
        let noOfNonZeros = dataSeries.length > 0 && dataSeries.filter(e => e.value > 0).length
        // Create animation definition while also assigning an ID to the animation for later sync usage
        var animationDefinition = {
          'stroke-dashoffset': {
            id: 'anim' + data.index,
            dur: 1,
            from: -pathLength + 'px',
            to: noOfNonZeros > 1 ? '2px' : '0px',
            easing: Chartist.Svg.Easing.easeOutQuint,
            // We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
            fill: 'freeze'
          }
        }

        // If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
        if (data.index !== 0) {
          animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end'
        }

        // We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
        data.element.attr({
          'stroke-dashoffset': -pathLength + 'px'
        })

        // We can't use guided mode as the animations need to rely on setting begin manually
        // See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
        data.element.animate(animationDefinition, false)
        if (dataSeries.length === 0) {
          data.element._node.setAttribute('data-value', 'no-composition')
        }
      }
      if (data.type === 'label') {
        let textHtml = ['<p>', data.text, '</p>'].join('')
        let multilineText = Chartist.Svg('svg').foreignObject(
          textHtml,
          {
            style: 'overflow: visible;',
            x: data.x - 30,
            y: data.y - 30,
            width: 90,
            height: 30
          },
          'ct-label'
        )
        data.element.replace(multilineText)
      }
    }
  }
  return (
    <div data-testid='gPieChart' id='performance_chart'>
      {<ChartistGraph
        data={pieData}
        options={pieOptions}
        type='Pie'
        style={{ width: '100%', height: '100%' }}
        className={styles.MyChart}
        listener={listner}
      />
      }
      {showToolTip && setToolTip()}
    </div>
  )
}
MyChart.propTypes = {
  dataSeries: PropTypes.array,
  getDetailsTable: PropTypes.func
}

export default MyChart
</code>```

Output

I want to add a custom tooltip with resize slice functionality on mouse hover event

Body:
I am creating a donut chart using Chartist but unable to add a custom tooltip with resize slice on the mouse hover event. Chartist "Draw" method is rerender on changing the position of mouse on hover of the chart
I pasted my code as below:

/* eslint-disable no-unused-vars */
import React, {useState} from 'react'
import PropTypes from 'prop-types'
import ChartistGraph from 'react-chartist'
import Chartist from 'chartist'
import styles from './MyChart.scss'
import {formatNumber} from '../../../../utils/formatter'
import MyChartInfo from './MyChartInfo'

function MyChart ({ dataSeries, getDetailsTable }) {
  const [changePercent, setChangePercent] = useState(0)
  const [showToolTip, setShowToolTip] = useState(false)
  const [myChartInfoDetails, setMyChartInfoDetails] = useState({sectorName: '', changePercent: ''})
  const [toolTipPosition, setToolTipPosition] = useState({})

  function setToolTip () {
    const PopOverData = [myChartInfoDetails.sectorName || '', `% Return: ${myChartInfoDetails.changePercent || ''}`, '(Click to view top & worst performing equities)']
    return (<MyChartInfo dataTable={PopOverData} style={toolTipPosition} />)
  }
  let pieOptions = {
    width: '520px',
    height: '520px',
    donut: true,
    donutWidth: 150,
    donutSolid: false,
    startAngle: 270,
    showLabel: true,
    chartPadding: 60,
    labelOffset: 105,
    labelDirection: 'explode',
    labelInterpolationFnc: function (value) {
      return value
    }
  }
  let pieData = {
    series: dataSeries && dataSeries.length > 0 ? dataSeries.map(item => Math.abs(item.value)) : [100],
    labels: dataSeries && dataSeries.length > 0 ? dataSeries.map(item => item.name.concat('
', formatNumber(item.value, {precision: 2, negSign: true, posSign: true}))) : ['']
  }
  // eslint-disable-next-line no-unused-vars
  const listner = {
    created: (chart) => {
      const chartPie = document.querySelectorAll('.ct-chart-donut .ct-slice-donut')
      chartPie && chartPie.forEach((pie) => {
        pie.addEventListener('mouseenter', (e) => {
          e.stopPropagation()
          pie.setAttribute('style', 'stroke-width: 170px;')
          console.log('hover aa  ', changePercent, Math.abs(pie.getAttribute('ct:value')))
          setChangePercent(Math.abs(pie.getAttribute('ct:value')))
          let topPosition = e.layerY + 30
          let leftPosition = e.layerX + 30
          setToolTipPosition({top: topPosition, left: leftPosition})
          const myChartData = dataSeries.find(sector => Math.abs(sector.value) === Math.abs(pie.getAttribute('ct:value')))
          setSectorDetails({sectorName: myChartData.name, changePercent: myChartData.value})
          setShowToolTip(true)
        })
        pie.addEventListener('mouseleave', (e) => {
          pie.setAttribute('style', 'stroke-width: 150px;')
          setShowToolTip(false)
        })
        pie.addEventListener('click', (e) => {
          const Id = dataSeries.find(sector => Math.abs(sector.value) === Math.abs(pie.getAttribute('ct:value'))).id.toString()
          console.log('click ', Id, pie.getAttribute('ct:value'))
          getDetailsTable(Id)
        })
      })
    },
    draw: (data) => {
      // console.log('data', data)
      if (data.type === 'slice') {
        // Get the total path length in order to use for dash array animation
        var pathLength = data.element._node.getTotalLength()

        // Set a dasharray that matches the path length as prerequisite to animate dashoffset
        data.element.attr({
          'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
        })
        let noOfNonZeros = dataSeries.length > 0 && dataSeries.filter(e => e.value > 0).length
        // Create animation definition while also assigning an ID to the animation for later sync usage
        var animationDefinition = {
          'stroke-dashoffset': {
            id: 'anim' + data.index,
            dur: 1,
            from: -pathLength + 'px',
            to: noOfNonZeros > 1 ? '2px' : '0px',
            easing: Chartist.Svg.Easing.easeOutQuint,
            // We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
            fill: 'freeze'
          }
        }

        // If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
        if (data.index !== 0) {
          animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end'
        }

        // We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
        data.element.attr({
          'stroke-dashoffset': -pathLength + 'px'
        })

        // We can't use guided mode as the animations need to rely on setting begin manually
        // See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
        data.element.animate(animationDefinition, false)
        if (dataSeries.length === 0) {
          data.element._node.setAttribute('data-value', 'no-composition')
        }
      }
      if (data.type === 'label') {
        let textHtml = ['
', data.text, '
'].join('')
        let multilineText = Chartist.Svg('svg').foreignObject(
          textHtml,
          {
            style: 'overflow: visible;',
            x: data.x - 30,
            y: data.y - 30,
            width: 90,
            height: 30
          },
          'ct-label'
        )
        data.element.replace(multilineText)
      }
    }
  }
  return (

      {<ChartistGraph
        data={pieData}
        options={pieOptions}
        type='Pie'
        style={{ width: '100%', height: '100%' }}
        className={styles.MyChart}
        listener={listner}
      />
      }
      {showToolTip && setToolTip()}

  )
}
MyChart.propTypes = {
  dataSeries: PropTypes.array,
  getDetailsTable: PropTypes.func
}

export default MyChart

Output

I want to add a custom tooltip with resize slice functionality on mouse hover event


问:
R: How to check how my R-Programm terminated?
I have written some software in R that performs a job every night, triggered by a cron event.
Now I want the software to send out a notification based upon the exit status of the software.
There are thee possible states the software can be in after it finishes:

No Error occurred.

A error occurred, but it was caught by a tryCatch.

A error occurred and it was not caught, the software terminated unexpectedly.

For me the first two cases are summaries as "no error" and the last one as "error".

Then I have identified two different modes that change the way errorhandling in R works.

Whether we are in an interactive R-Session or not.

Whether the traceback(x) value is set to x=NULL or an integer, in this example x=1.

To test the behavior of R in all these different scenarios I came up with a small MWE and a table to show my results.
You'll find the MWE below.
In this table you can see that there are several cases (e.g. Non-Interactive and x=1) where you have not enough information to discriminate the three different stages from one another.

How can I reliably determine from the on.exit()-Function how my R-Program terminated?

Or how can I reliably determine from the on.exit()-Function if my R-Program had an error?

interactive
traceback(x)
test
No Error
uncaught Error
caught Error

TRUE
1
nchar(geterrmessage())==0
TRUE
FALSE
FALSE

TRUE
1
is.null(.traceback())
FALSE
FALSE
FALSE

TRUE
NULL
nchar(geterrmessage())==0
TRUE
FALSE
FALSE

TRUE
NULL
is.null(.traceback())
TRUE
FALSE
TRUE

FALSE
1
nchar(geterrmessage())==0
TRUE
FALSE
FALSE

FALSE
1
is.null(.traceback())
FALSE
FALSE
FALSE

FALSE
NULL
nchar(geterrmessage())==0
TRUE
FALSE
FALSE

FALSE
NULL
is.null(.traceback())
TRUE
TRUE
TRUE

```<code>test <- function(error, trace) {
  on.exit(
    {
      print(nchar(geterrmessage()) == 0)
      print(is.null(.traceback(trace)))
    },
    add = TRUE,
    after = TRUE
  )

  if (error == "c") {
    result <- tryCatch({
      "1" + 1
    }, warning = function(w) {
      print(w)
    }, error = function(e) {
      print(e)
    }, finally = {
      print("finally")
    })
  } else if (error == "u") {
    "1" + 1
  } else if (error == "n") {
    1 + 1
  } else {
    print("BAD")
  }
}

.rs.restartR()
options(error = NULL)
test(error = "n", trace=NULL)

.rs.restartR()
options(error = NULL)
test(error = "u", trace=NULL)

.rs.restartR()
options(error = NULL)
test(error = "c", trace=NULL)

#########

.rs.restartR()
options(error = NULL)
test(error = "n", trace=1)

.rs.restartR()
options(error = NULL)
test(error = "u", trace=1)

.rs.restartR()
options(error = NULL)
test(error = "c", trace=1)
</code>```

Body:
I have written some software in R that performs a job every night, triggered by a cron event.
Now I want the software to send out a notification based upon the exit status of the software.
There are thee possible states the software can be in after it finishes:

No Error occurred.

A error occurred, but it was caught by a tryCatch.

A error occurred and it was not caught, the software terminated unexpectedly.

For me the first two cases are summaries as "no error" and the last one as "error".

Then I have identified two different modes that change the way errorhandling in R works.

Whether we are in an interactive R-Session or not.

Whether the traceback(x) value is set to x=NULL or an integer, in this example x=1.

To test the behavior of R in all these different scenarios I came up with a small MWE and a table to show my results.
You'll find the MWE below.
In this table you can see that there are several cases (e.g. Non-Interactive and x=1) where you have not enough information to discriminate the three different stages from one another.

How can I reliably determine from the on.exit()-Function how my R-Program terminated?

Or how can I reliably determine from the on.exit()-Function if my R-Program had an error?

interactive
traceback(x)
test
No Error
uncaught Error
caught Error

TRUE
1
nchar(geterrmessage())==0
TRUE
FALSE
FALSE

TRUE
1
is.null(.traceback())
FALSE
FALSE
FALSE

TRUE
NULL
nchar(geterrmessage())==0
TRUE
FALSE
FALSE

TRUE
NULL
is.null(.traceback())
TRUE
FALSE
TRUE

FALSE
1
nchar(geterrmessage())==0
TRUE
FALSE
FALSE

FALSE
1
is.null(.traceback())
FALSE
FALSE
FALSE

FALSE
NULL
nchar(geterrmessage())==0
TRUE
FALSE
FALSE

FALSE
NULL
is.null(.traceback())
TRUE
TRUE
TRUE

test <- function(error, trace) {
  on.exit(
    {
      print(nchar(geterrmessage()) == 0)
      print(is.null(.traceback(trace)))
    },
    add = TRUE,
    after = TRUE
  )

  if (error == "c") {
    result <- tryCatch({
      "1" + 1
    }, warning = function(w) {
      print(w)
    }, error = function(e) {
      print(e)
    }, finally = {
      print("finally")
    })
  } else if (error == "u") {
    "1" + 1
  } else if (error == "n") {
    1 + 1
  } else {
    print("BAD")
  }
}

.rs.restartR()
options(error = NULL)
test(error = "n", trace=NULL)

.rs.restartR()
options(error = NULL)
test(error = "u", trace=NULL)

.rs.restartR()
options(error = NULL)
test(error = "c", trace=NULL)

#########

.rs.restartR()
options(error = NULL)
test(error = "n", trace=1)

.rs.restartR()
options(error = NULL)
test(error = "u", trace=1)

.rs.restartR()
options(error = NULL)
test(error = "c", trace=1)


问:
How to run .exe file and .bat files (depended directory files) using python desktop automation
I have a VBscript which is written in C++ language .exe file and .bat files. When I clicked on .exe file (depended on .bat files and .dll ..etc.) files are running. I want to run alone .exe file using Python desktop automation(subprocess, OS, PyAutoGui, PywinAuto...ect.,). I have run it but getting errors like "No directory found"</p>
```<code>import time
from subprocess import Popen, PIPE

process = Popen(["filepath .exe 1"], shell=True,stderr=PIPE, encoding='utf8').communicate(input="1\n")
# os.system('filepath .exe') or
scriptdir = os.path.dirname('filepath .exe')
batchfile = os.path.join(scriptdir,'file.bat')
batchfile1 = os.path.join(scriptdir,'file.bat')
time.sleep(5)
</code>```

Body:
I have a VBscript which is written in C++ language .exe file and .bat files. When I clicked on .exe file (depended on .bat files and .dll ..etc.) files are running. I want to run alone .exe file using Python desktop automation(subprocess, OS, PyAutoGui, PywinAuto...ect.,). I have run it but getting errors like "No directory found"

import time
from subprocess import Popen, PIPE

process = Popen(["filepath .exe 1"], shell=True,stderr=PIPE, encoding='utf8').communicate(input="1\n")
# os.system('filepath .exe') or
scriptdir = os.path.dirname('filepath .exe')
batchfile = os.path.join(scriptdir,'file.bat')
batchfile1 = os.path.join(scriptdir,'file.bat')
time.sleep(5)


问:
Re- assigning custom variable inside script tag in a .hbs - node project
I am trying to re assign a variable using script tag inside an .hbs file and using that variable to pass via url. here is my hbs file code and helpers method.

I have tried the below code.

```<code>
{{setVar "size" "S"}}
 {{@root.size}}

***<script>
    function check(t){
        var id = t.id;
        const d = String(document.getElementById(id).value);
        {{{ setVar "size" d }}}
        alert(d+" "+id);
    }
</script>***
{{size}}

 <a href="/cart/add-to-cart/{{this._id}}/***{{@root.size}}***" class="btn btn-raised btn-success pull-right">

</code>```

and my helpers in app.js

```<code>var hbs = expressHbs.create({
  defaultLayout: 'layout',
  extname: '.hbs',
  helpers: {
    calculation: function(value){
      return value*5;
    },
    select: function(selected, options){
      return options.fn(this).replace(
        new RegExp(' value=\"' + selected + '\"'),
        '$& selected="selected"');
    },
    setVar: function(varName, varValue, options){
      if (!options.data.root) {
        options.data.root = {};
    }
    options.data.root[varName] = varValue;
    },
    json: function(content){
      // if (content != '')
        return JSON.stringify(content);
    }
  }
});
</code>```

Body:
I am trying to re assign a variable using script tag inside an .hbs file and using that variable to pass via url. here is my hbs file code and helpers method.

I have tried the below code.

{{setVar "size" "S"}}
 {{@root.size}}

******
{{size}}

and my helpers in app.js

var hbs = expressHbs.create({
  defaultLayout: 'layout',
  extname: '.hbs',
  helpers: {
    calculation: function(value){
      return value*5;
    },
    select: function(selected, options){
      return options.fn(this).replace(
        new RegExp(' value=\"' + selected + '\"'),
        '$& selected="selected"');
    },
    setVar: function(varName, varValue, options){
      if (!options.data.root) {
        options.data.root = {};
    }
    options.data.root[varName] = varValue;
    },
    json: function(content){
      // if (content != '')
        return JSON.stringify(content);
    }
  }
});


问:
How do you push a block of text in C to make space and write in a file using low level I/O?
So I have to write in  a file that already has text in it , using Low Level I/O, but I have to write in the middle of that text so I need to push that text and make space, same strategy for deletion, but I don't have an idea on how to do it . The functions I should use are :

```<code>ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const char *buf, size_t count);
int close( int handle );
int open(const char *pathname, int flags, mode_t mode);
off_t lseek(int fildes, off_t offset, int whence);
</code>```

Thank you.

Body:
So I have to write in  a file that already has text in it , using Low Level I/O, but I have to write in the middle of that text so I need to push that text and make space, same strategy for deletion, but I don't have an idea on how to do it . The functions I should use are :

ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const char *buf, size_t count);
int close( int handle );
int open(const char *pathname, int flags, mode_t mode);
off_t lseek(int fildes, off_t offset, int whence);

Thank you.


问:
Why Rxjava3 Observable on main thread miss sometimes while in doze mode?
I am using rxjava3 observable in foreground service to sync data after every 3 minutes but this observer miss sometime when phone in doze mode</p>
```<code> disposable = Observable.interval(1, 3 * 60 * 1000, TimeUnit.MILLISECONDS)
        .subscribeOn(Schedulers.io()).observeOn(
            AndroidSchedulers.mainThread()
        ).subscribe {
            Log.d(TAG, "Observe Called")
            appendLog("Observe Called on ${formatDate(System.currentTimeMillis().toString())}")
        }
</code>```

Body:
I am using rxjava3 observable in foreground service to sync data after every 3 minutes but this observer miss sometime when phone in doze mode

 disposable = Observable.interval(1, 3 * 60 * 1000, TimeUnit.MILLISECONDS)
        .subscribeOn(Schedulers.io()).observeOn(
            AndroidSchedulers.mainThread()
        ).subscribe {
            Log.d(TAG, "Observe Called")
            appendLog("Observe Called on ${formatDate(System.currentTimeMillis().toString())}")
        }