问:
Consider defining a bean of type 'com.firstproject.shopping.model.data.PageRepository' in your configuration
I am working on springboot project. but now i am getting this error.

APPLICATION FAILED TO START

Description:

Parameter 0 of constructor in com.firstproject.shopping.Controllers.Adminpages required a bean of type 'com.firstproject.shopping.model.data.PageRepository' that could not be found.

Action:

Consider defining a bean of type 'com.firstproject.shopping.model.data.PageRepository' in your configuration.

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>2.7.7</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.firstproject</groupId>
    <artifactId>shopping</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>shopping</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>

     <dependency>
            <groupId>io.github.qsy7.java.dependencies</groupId>
            <artifactId>lombok</artifactId>
            <version>0.1.2</version>
            <type>pom</type>
        </dependency>

      <dependency>
           <groupId>org.hibernate</groupId>
           <artifactId>hibernate-core</artifactId>
           <version>5.2.2.Final</version>
     </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>8.0.0.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>```

Controller

```<code>@RestController
@RequestMapping("/admin/pages")
public class Adminpages {

    @Autowired
    PageRepository pagerepo;

    public Adminpages(PageRepository pagerepo) {

        this.pagerepo = pagerepo;

    }

    public String index(Model model) {

        List<Page> pages = pagerepo.findAll();
        model.addAttribute("pages", pages);

        return "admin/pages/index";
    }

}
</code>```

PageRepository.java

```<code>
import org.springframework.data.jpa.repository.JpaRepository;

public interface PageRepository extends JpaRepository<Page, Integer> {

    public List<Page> findAll();
}
</code>```

POJO

```<code>package com.firstproject.shopping.model.data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.stereotype.Component;

import lombok.Data;

@Entity
@Table(name="pages")
@Data
@Component
 public class Page{
    @Id
    @GeneratedValue(strategy =GenerationType.IDENTITY )
    private int id;
    private String title;
    private String slug;
    private String content;
    private int sorting;

}
</code>```

Body:
I am working on springboot project. but now i am getting this error.

APPLICATION FAILED TO START

Description:

Parameter 0 of constructor in com.firstproject.shopping.Controllers.Adminpages required a bean of type 'com.firstproject.shopping.model.data.PageRepository' that could not be found.

Action:

Consider defining a bean of type 'com.firstproject.shopping.model.data.PageRepository' in your configuration.

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>2.7.7</version>
        <relativePath/>
    </parent>
    <groupId>com.firstproject</groupId>
    <artifactId>shopping</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>shopping</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>

     <dependency>
            <groupId>io.github.qsy7.java.dependencies</groupId>
            <artifactId>lombok</artifactId>
            <version>0.1.2</version>
            <type>pom</type>
        </dependency>

      <dependency>
           <groupId>org.hibernate</groupId>
           <artifactId>hibernate-core</artifactId>
           <version>5.2.2.Final</version>
     </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>8.0.0.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>

Controller

@RestController
@RequestMapping("/admin/pages")
public class Adminpages {

    @Autowired
    PageRepository pagerepo;

    public Adminpages(PageRepository pagerepo) {

        this.pagerepo = pagerepo;

    }

    public String index(Model model) {

        List<Page> pages = pagerepo.findAll();
        model.addAttribute("pages", pages);

        return "admin/pages/index";
    }

}

PageRepository.java

import org.springframework.data.jpa.repository.JpaRepository;

public interface PageRepository extends JpaRepository<Page, Integer> {

    public List<Page> findAll();
}

POJO

package com.firstproject.shopping.model.data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.stereotype.Component;

import lombok.Data;

@Entity
@Table(name="pages")
@Data
@Component
 public class Page{
    @Id
    @GeneratedValue(strategy =GenerationType.IDENTITY )
    private int id;
    private String title;
    private String slug;
    private String content;
    private int sorting;

}


来源: stackexchange

问:
C# Visual Studio issue, data is saved in table adapter but database doesn't get updated
I am new to C#.

I have created:

Local Service-based database

DataSet for the table (users)

Table Adapter

SQL Insert queries inside the table adapter

My SQL query syntax is ok and run fine. Problem occurs when I use this bit of code:

```<code>adapter.Insert("values");
adapter.Update(DataSet);
</code>```

The first line runs ok and I can login to that user account that is inserted. But nothing comes to the database. Also, when I close the app and open it again, I cannot login to that user anymore.

Changing the database copy to "Copy Always" / "Don't copy".

"Don't copy" caused this error:

An attempt to attach an auto-named database.

I am currently using "Copy if newer"

I am not required to use any inline SQL command in my code, I have added the binding source, dataSet, table adapter from the toolBox to my form and configured the datasource of them accordingly.

ContentLicense: CC BY-SA 4.0

Body:
I am new to C#.

I have created:

Local Service-based database

DataSet for the table (users)

Table Adapter

SQL Insert queries inside the table adapter

My SQL query syntax is ok and run fine. Problem occurs when I use this bit of code:

adapter.Insert("values");
adapter.Update(DataSet);

The first line runs ok and I can login to that user account that is inserted. But nothing comes to the database. Also, when I close the app and open it again, I cannot login to that user anymore.

Changing the database copy to "Copy Always" / "Don't copy".

"Don't copy" caused this error:

An attempt to attach an auto-named database.

I am currently using "Copy if newer"

I am not required to use any inline SQL command in my code, I have added the binding source, dataSet, table adapter from the toolBox to my form and configured the datasource of them accordingly.


问:
Convert number to number between 0 to 2
I am trying to create an arc using javascript with the total count of four items. For that I need to calculate percentage of total count of each item and assign to the variables perc1,perc2,perc3,perc4. But it's total should not go beyond 2. I have generated sample arc using the dummy percentage given below.

I would get total values from database instead which should be converted and used.
For ex: if I have values like 129, 53, 111, 95. How can I get calculated percentage for the variables perc1,perc2,perc3,perc4?

```<code>var totalPercent = .75;
var padRad = 0.025;
var percToRad = function (perc) {
    return degToRad(percToDeg(perc));
};
var degToRad = function (deg) {
    return deg * Math.PI / 180;
};
var percToDeg = function (perc) {
    return perc * 360;
};

//****Set up the arc generator*****
perc1 = 0.6;
perc2 = 0.4;
perc3 = 0.4;
perc4 = 0.6;
var next_start = totalPercent;

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc1 / 4);
next_start += perc1 / 4;
const arc1 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc2 / 4);
next_start += perc2 / 4;
const arc2 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc3 / 4);
next_start += perc3 / 4;
const arc3 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc4 / 4);
const arc4 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);
</code>```

Title: Convert number to number between 0 to 2

Body:
I am trying to create an arc using javascript with the total count of four items. For that I need to calculate percentage of total count of each item and assign to the variables perc1,perc2,perc3,perc4. But it's total should not go beyond 2. I have generated sample arc using the dummy percentage given below.

I would get total values from database instead which should be converted and used.
For ex: if I have values like 129, 53, 111, 95. How can I get calculated percentage for the variables perc1,perc2,perc3,perc4?

var totalPercent = .75;
var padRad = 0.025;
var percToRad = function (perc) {
    return degToRad(percToDeg(perc));
};
var degToRad = function (deg) {
    return deg * Math.PI / 180;
};
var percToDeg = function (perc) {
    return perc * 360;
};

//****Set up the arc generator*****
perc1 = 0.6;
perc2 = 0.4;
perc3 = 0.4;
perc4 = 0.6;
var next_start = totalPercent;

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc1 / 4);
next_start += perc1 / 4;
const arc1 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc2 / 4);
next_start += perc2 / 4;
const arc2 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc3 / 4);
next_start += perc3 / 4;
const arc3 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc4 / 4);
const arc4 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);


问:
How to use only https in npm (urls as dependencies)
I have a npm package with the a depndency that is shared in s3 (https://xxx.s3.eu-west-1.amazonaws.com/yyy.tgz).

So in my PACKAGE.JSON

```<code>  "dependencies": {
    "zzz": "https://xxx.s3.eu-west-1.amazonaws.com/xxx.tgz",
</code>```

I want to use this in codesanbox or jsfiddle

I always have an anwser  like "Could not fetch dependencies, please try again in a couple seconds"

When I downlaod the package using a browser and I do this in my local projet:

```<code>  "dependencies": {
    "zzz": "file: xxx.tgz",
</code>```

Every thing work well.

I noted that in npm we have only these possibilites

<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>]

<protocol> is one of git, git+ssh, git+http, git+https, or git+file.

How can i use only HTTPS ?

Body:
I have a npm package with the a depndency that is shared in s3 (https://xxx.s3.eu-west-1.amazonaws.com/yyy.tgz).

So in my PACKAGE.JSON

  "dependencies": {
    "zzz": "https://xxx.s3.eu-west-1.amazonaws.com/xxx.tgz",

I want to use this in codesanbox or jsfiddle

I always have an anwser  like "Could not fetch dependencies, please try again in a couple seconds"

When I downlaod the package using a browser and I do this in my local projet:

  "dependencies": {
    "zzz": "file: xxx.tgz",

Every thing work well.

I noted that in npm we have only these possibilites

<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>]

<protocol> is one of git, git+ssh, git+http, git+https, or git+file.

How can i use only HTTPS ?


问:
How to disable android keyboard and only show kivy keyboard?
Kivy onscreen keyboard works perfect on laptop(As you can see here), but when I package the code I encounter 2 problems. Which are:

1.Both Android keyboard and kivy keyboard pops up. How can I disable Android keyboard only?
2.I am able to disable kivy keyboard, however android keyboard covers some of my widgets. How can I customize the android keyboard i.e change its color, size and position etc.

I tried using window.softinput but it didn't really change the android keyboard position. The Android keyboard always appears from the bottom. I also tried disabling android keyboard but to no avail.

main.py

```<code>
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.config import Config
Config.set('kivy','keyboard_mode', 'dock')
from kivy.uix.textinput import TextInput
from kivy.core.window import Window

Window.keyboard_anim_args = {'d':.2,'t':'in_out_expo'}
Window.softinput_mode = 'below_target'

class CustomTextInput(TextInput):
    def __init__(self,**kwargs):
        super(CustomTextInput,self).__init__(**kwargs)
        self.setup_keyboard()

    def setup_keyboard(self):
        kb = Window.request_keyboard(self._keyboard_close, self)
        if kb.widget:
            #kb.widget.background_color = (0,0,1,1)
            #kb.widget.background = 'bg.png'
            kb.widget.key_background_color = (1,1,0,1)
            kb.widget.font_size = 25
            kb.widget.layout = 'numeric.json'

    def _keyboard_close(self):
        pass

class StartApp(Screen):
    pass

class WindowManager(ScreenManager):
    pass

class MainApp(App):
    def build(self):
        return WindowManager()

MainApp().run()

</code>```

main.kv

```<code>
<WindowManager>:
    StartApp:
        name: 'start'

<StartApp>:
    BoxLayout:
        orientation: 'vertical'
        CustomTextInput:
            #keyboard_mode: 'managed'
        Button:
            text: 'press me'
        Widget:

</code>```

Body:
Kivy onscreen keyboard works perfect on laptop(As you can see here), but when I package the code I encounter 2 problems. Which are:

1.Both Android keyboard and kivy keyboard pops up. How can I disable Android keyboard only?
2.I am able to disable kivy keyboard, however android keyboard covers some of my widgets. How can I customize the android keyboard i.e change its color, size and position etc.

I tried using window.softinput but it didn't really change the android keyboard position. The Android keyboard always appears from the bottom. I also tried disabling android keyboard but to no avail.

main.py

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.config import Config
Config.set('kivy','keyboard_mode', 'dock')
from kivy.uix.textinput import TextInput
from kivy.core.window import Window

Window.keyboard_anim_args = {'d':.2,'t':'in_out_expo'}
Window.softinput_mode = 'below_target'

class CustomTextInput(TextInput):
    def __init__(self,**kwargs):
        super(CustomTextInput,self).__init__(**kwargs)
        self.setup_keyboard()

    def setup_keyboard(self):
        kb = Window.request_keyboard(self._keyboard_close, self)
        if kb.widget:
            #kb.widget.background_color = (0,0,1,1)
            #kb.widget.background = 'bg.png'
            kb.widget.key_background_color = (1,1,0,1)
            kb.widget.font_size = 25
            kb.widget.layout = 'numeric.json'

    def _keyboard_close(self):
        pass

class StartApp(Screen):
    pass

class WindowManager(ScreenManager):
    pass

class MainApp(App):
    def build(self):
        return WindowManager()

MainApp().run()

main.kv

<WindowManager>:
    StartApp:
        name: 'start'

<StartApp>:
    BoxLayout:
        orientation: 'vertical'
        CustomTextInput:
            #keyboard_mode: 'managed'
        Button:
            text: 'press me'
        Widget:


问:
Salesforce - Enhanced domain third party cookie issue
Anybody facing issue with the new Enhanced domain implementation, I am not able to get the handle to the cookies.

Any help will be much appreciated.

Below is my scenario/steps

salesforce sets the cookie value using an LWC component.

Re-directs the page to OKTA for authentication.

OKTA after authentication re-directs to a visual force page where the JavaScript tried to read the cookie already set in the step 1.

The value reading the while reading the cookie is 'undefined'

It's all working well without Enhanced domain implementation enabled, As Jan 10 2023 is the cutoff date of mandatory implementation of Enhanced Domain on Sandboxes, we are trying to resolve this issue before the cut-off date.

```<code>function getCookie(name) {
        let cookieString = "; " + document.cookie;
        let cookies = cookieString.split("; ");
        let currentCookieVal;
        cookies.forEach(cookie => {
        let currentCookieArr = cookie.split('=__');
            if(currentCookieArr.length && currentCookieArr.length === 2) {
                if(currentCookieArr[0].includes(name)) {
                    currentCookieVal = currentCookieArr;
                }
            }
        });
        return currentCookieVal;
    }
</code>```

Thanks,
James

Body:
Anybody facing issue with the new Enhanced domain implementation, I am not able to get the handle to the cookies.

Any help will be much appreciated.

Below is my scenario/steps

salesforce sets the cookie value using an LWC component.

Re-directs the page to OKTA for authentication.

OKTA after authentication re-directs to a visual force page where the JavaScript tried to read the cookie already set in the step 1.

The value reading the while reading the cookie is 'undefined'

It's all working well without Enhanced domain implementation enabled, As Jan 10 2023 is the cutoff date of mandatory implementation of Enhanced Domain on Sandboxes, we are trying to resolve this issue before the cut-off date.

function getCookie(name) {
        let cookieString = "; " + document.cookie;
        let cookies = cookieString.split("; ");
        let currentCookieVal;
        cookies.forEach(cookie => {
        let currentCookieArr = cookie.split('=__');
            if(currentCookieArr.length && currentCookieArr.length === 2) {
                if(currentCookieArr[0].includes(name)) {
                    currentCookieVal = currentCookieArr;
                }
            }
        });
        return currentCookieVal;
    }

Thanks,
James


问:
gcc C++ force generating global object constructor calls on exotic build parameters
When global C++ objects are initialized with a constructor,
like

multilist<CONFIGBRIDGE_Total_Document_instance>
  globstat_CONFIGBRIDGE_Total_Document_multilist =
    multilist<CONFIGBRIDGE_Total_Document_instance>();
```
<p>(I know that global variables are seen as bad, but I need a list of variables of each type globally available for the user and his/her scripts.)
The constructor is called before the entry from the main function.
I handle my binary aggressively, so I attempt to compile it with parameters that remove external dependencies. I did, however, not mean to remove INTERNAL dependencies too.
My compilation line therefore looks like this:</p>
<pre class="lang-bash prettyprint-override"><code>g++ -O0 --std=c++0x -m32 lhendraw.cxx -Wl,relocatable -ffreestanding -fno-pie -fno-exceptions -fno-asynchronous-unwind-tables -S -o lhendraw.s
</code>```

The effect is that the above initialization is never executed. A member of that structure aimed to be allocated with the "malloc" command in there remains empty.

The problem is obviously that the routine that calls these initializations is completely omitted. I see no single call to the constructor function in the resulting assembly.
How can I tell gcc to hand me a second entry point to call the initialization?
Or
How can I tell gcc to process the global initializers so far that it will give me a complete list of them in a machine-readable format?

Of course I can try to remove -ffreestanding, but that would break subsequent compilation.
By the way, the linker complains that __preinit_array_start, __preinit_array_end, __init_array_start and __init_array_end are missing.
I guess that is the name of a list of caller stubs I want, but that one is not generated.
There is a small section called init_array, but it seems to contain data only.

Body:
When global C++ objects are initialized with a constructor,
like

multilist<CONFIGBRIDGE_Total_Document_instance>
  globstat_CONFIGBRIDGE_Total_Document_multilist =
    multilist<CONFIGBRIDGE_Total_Document_instance>();

(I know that global variables are seen as bad, but I need a list of variables of each type globally available for the user and his/her scripts.)
The constructor is called before the entry from the main function.
I handle my binary aggressively, so I attempt to compile it with parameters that remove external dependencies. I did, however, not mean to remove INTERNAL dependencies too.
My compilation line therefore looks like this:

g++ -O0 --std=c++0x -m32 lhendraw.cxx -Wl,relocatable -ffreestanding -fno-pie -fno-exceptions -fno-asynchronous-unwind-tables -S -o lhendraw.s

The effect is that the above initialization is never executed. A member of that structure aimed to be allocated with the "malloc" command in there remains empty.

The problem is obviously that the routine that calls these initializations is completely omitted. I see no single call to the constructor function in the resulting assembly.
How can I tell gcc to hand me a second entry point to call the initialization?
Or
How can I tell gcc to process the global initializers so far that it will give me a complete list of them in a machine-readable format?

Of course I can try to remove -ffreestanding, but that would break subsequent compilation.
By the way, the linker complains that __preinit_array_start, __preinit_array_end, __init_array_start and __init_array_end are missing.
I guess that is the name of a list of caller stubs I want, but that one is not generated.
There is a small section called init_array, but it seems to contain data only.


问:
serverless cli package can't resolve nx monorepo imports
I have many apps consuming many libraries in a monorepo, and everything works except the $ sls package command.

It breaks because it can't resolve the imports I define in tsconfig's.

This is my structure:

```<code>- tsconfig.base.json
- apps
  - serverless
    - tsconfig.json
  - app2
    - tsconfig.json
- libs
  - lib1
    - tsconfig.json
  - lib2
    - tsconfig.json
</code>```
```<code>// tsconfig.base.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "noPropertyAccessFromIndexSignature": false,
    "resolveJsonModule": true,
    "rootDir": ".",
    "esModuleInterop": true,
    "sourceMap": true,
    "noImplicitReturns": false,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "lib": ["es2017", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "paths": {
      "~/*": ["./*"],
      "@nx/lib1": ["../../../libs/lib1/src/index.ts"],
      "@nx/lib2": ["../../../libs/lib2/src/index.ts"]
    },
    "types": ["node", "jest"]
  },
  "exclude": ["node_modules", "tmp"]
}

</code>```
```<code>// apps/serverless/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "baseUrl": "src"
  },
  "files": [],
  "include": [],
  "references": [
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.spec.json"
    }
  ]
}

</code>```
```<code>// apps/serverless/tsconfig.app.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "../../dist/out-tsc",
    "module": "commonjs",
    "types": ["node"]
  },
  "exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"],
  "include": ["**/*.ts"]
}

</code>```

like I said everything works, except $ sls package which produces many errors like:

```<code>✘ [ERROR] Could not resolve "@nx/constants"
You can mark the path "@nx/constants" as external to exclude it from the bundle, which will remove this error.
</code>```

any ideas what I'm missing here?

Body:
I have many apps consuming many libraries in a monorepo, and everything works except the $ sls package command.

It breaks because it can't resolve the imports I define in tsconfig's.

This is my structure:

- tsconfig.base.json
- apps
  - serverless
    - tsconfig.json
  - app2
    - tsconfig.json
- libs
  - lib1
    - tsconfig.json
  - lib2
    - tsconfig.json

// tsconfig.base.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "noPropertyAccessFromIndexSignature": false,
    "resolveJsonModule": true,
    "rootDir": ".",
    "esModuleInterop": true,
    "sourceMap": true,
    "noImplicitReturns": false,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "lib": ["es2017", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "paths": {
      "~/*": ["./*"],
      "@nx/lib1": ["../../../libs/lib1/src/index.ts"],
      "@nx/lib2": ["../../../libs/lib2/src/index.ts"]
    },
    "types": ["node", "jest"]
  },
  "exclude": ["node_modules", "tmp"]
}

// apps/serverless/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "baseUrl": "src"
  },
  "files": [],
  "include": [],
  "references": [
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.spec.json"
    }
  ]
}

// apps/serverless/tsconfig.app.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "../../dist/out-tsc",
    "module": "commonjs",
    "types": ["node"]
  },
  "exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"],
  "include": ["**/*.ts"]
}

like I said everything works, except $ sls package which produces many errors like:

✘ [ERROR] Could not resolve "@nx/constants"
You can mark the path "@nx/constants" as external to exclude it from the bundle, which will remove this error.

any ideas what I'm missing here?


问:
Cython not faster than Python
I'm testing the performance of Python vs Cython for web scraping using while loop. Sadly I don't se any improvement.

Here is my Python code:

```<code>from bs4 import BeautifulSoup
import requests
import time
from multiprocessing import cpu_count, pool

def funct():
    i=0
    url = 'https://www.tocnaura.si/'
    tic = time.perf_counter()
    s = requests.session()

    while i<=100:
        result = s.get(url)
        doc = BeautifulSoup(result.text, "html.parser")
        tag = doc.find('script').string
        string = tag[29:48].replace(',', ':')
        print(string, flush=True)
        i+=1

    toc = time.perf_counter()
    print(f'End in {toc - tic:0.4f} sec', flush=True)
</code>```

And here is my Cython code:

```<code>from bs4 import BeautifulSoup
import requests
import time
from multiprocessing import cpu_count, pool

cdef int i
cdef str url, doc, tag, string, s, result
cdef float tic, toc

def funct():
    i=0
    url = 'https://www.tocnaura.si/'
    tic = time.perf_counter()
    s = requests.session()

    while i<=100:
        result = s.get(url)
        doc = BeautifulSoup(result.text, "html.parser")
        tag = doc.find('script').string
        string = tag[29:48].replace(',', ':')
        print(string)
        i+=1

    toc = time.perf_counter()
    print(f'End in {toc - tic:0.4f} sec')
</code>```

Now I use the script for test the Python and Cython code:

```<code>import Time1
import Time2
import time

start1 = time.time()
Time1.funct()
stop1 = time.time()
print(stop1 - start1)

start2 = time.time()
Time2.funct()
stop2 = time.time()
print(stop2 - start2)
</code>```

And my output is:

```<code>15,58 sec for Cyton
15,54 sec for Python
</code>```

What am I doing wrong here?

I was expecting about 100x times better performance using Cython

Title: Cython not faster than Python

Body:
I'm testing the performance of Python vs Cython for web scraping using while loop. Sadly I don't se any improvement.

Here is my Python code:

from bs4 import BeautifulSoup
import requests
import time
from multiprocessing import cpu_count, pool

def funct():
    i=0
    url = 'https://www.tocnaura.si/'
    tic = time.perf_counter()
    s = requests.session()

    while i<=100:
        result = s.get(url)
        doc = BeautifulSoup(result.text, "html.parser")
        tag = doc.find('script').string
        string = tag[29:48].replace(',', ':')
        print(string, flush=True)
        i+=1

    toc = time.perf_counter()
    print(f'End in {toc - tic:0.4f} sec', flush=True)

And here is my Cython code:

from bs4 import BeautifulSoup
import requests
import time
from multiprocessing import cpu_count, pool

cdef int i
cdef str url, doc, tag, string, s, result
cdef float tic, toc

def funct():
    i=0
    url = 'https://www.tocnaura.si/'
    tic = time.perf_counter()
    s = requests.session()

    while i<=100:
        result = s.get(url)
        doc = BeautifulSoup(result.text, "html.parser")
        tag = doc.find('script').string
        string = tag[29:48].replace(',', ':')
        print(string)
        i+=1

    toc = time.perf_counter()
    print(f'End in {toc - tic:0.4f} sec')

Now I use the script for test the Python and Cython code:

import Time1
import Time2
import time

start1 = time.time()
Time1.funct()
stop1 = time.time()
print(stop1 - start1)

start2 = time.time()
Time2.funct()
stop2 = time.time()
print(stop2 - start2)

And my output is:

15,58 sec for Cyton
15,54 sec for Python

What am I doing wrong here?

I was expecting about 100x times better performance using Cython


问:
Stripe payment failing after trial period
I'm attempting to create a monthly subscription with free 7 day trial, but after the trial period the payment fails.

EDIT: It appears to fail because the customer has no default payment method, so despite the payment method being attached to customer, it is not set to default. I can not figure out how to set it to default payment method.

I am setting ConfirmCardSetup in frontend javascript, which I believe is tying the card to the customer. And I am creating the customer, and starting the subscription/trial in my backend django view.

I have found this in Stripe documentation:

"To use this PaymentMethod as the default for invoice or subscription
payments, set invoice_settings.default_payment_method, on the Customer
to the PaymentMethod’s ID."

but I am unsure how to get the Payment Method ID from front end, and use it to update the customer.

Here is my subscription create view:

```<code>class SubscriptionCreateView(View, SubscriptionCancellationMixin,
                         CustomerMixin, StripeReferenceMixin, FetchCouponMixin):

"""View to Create subscription and sync with stripe"""
def post(self, request, *args, **kwargs):
    context = {}
    subscription_payload = {}
    price_id = request.POST.get('price_id')
    coupon_id = request.POST.get('coupon_id')
    customer = self.fetch_customer(request.user)

    #Retrieve stripe coupon id or None
    if coupon_id != '':
        stripe_coupon_id, is_valid = self.is_coupon_valid(coupon_id)
        #Set payload to create a subscription
        subscription_payload['coupon'] = stripe_coupon_id
        #Send invalid coupon response
        if not is_valid:
            context['invalid_coupon'] = True
            response = JsonResponse(context)
            response.status_code = 400
            return response

    if not customer:
        customer = self.stripe.Customer.create(
                email=request.user.email
        )
    try:
        now = int(time.time())
        # Cancel the previous subscription.
        self.cancel_subscription(customer)
        #Create a new subscription
        subscription_payload.update({
            'customer':customer.id,
            'items':  [{
                    'price': price_id,
                },
                ],
            'trial_end': now +30,

        },
            )

        #create a setup intent
        setup_intent = self.stripe.SetupIntent.create(
             payment_method_types=["card"],

             customer=customer.id,
        )
        subscription = self.stripe.Subscription.create(**subscription_payload)

        # Sync the Stripe API return data to the database,
        # this way we don't need to wait for a webhook-triggered sync
        Subscription.sync_from_stripe_data(subscription)
        request.session['created_subscription_id'] = subscription.get('id')

        # Note we're sending the Subscription's
        # latest invoice and client secret
        # to the front end to confirm the payment
        context['subscriptionId'] = subscription.id
        context['clientSecret'] = setup_intent['client_secret']

    except Exception as e:
        response = JsonResponse({})
        response.status_code = 400
        return response

    return JsonResponse(context)
</code>```

And here's the relevant javascript!

```<code>var stripe = Stripe($('#public-key').val());
var elements = stripe.elements();
var style = {
   base: {
     color: "#32325d",
     }
   };

var card = elements.create("card", { style: style });
card.mount("#card-element");

//Capture modal payment button click
$(document).on('click', '#submit-payment-btn', function (e) {
e.preventDefault();
//Send an ajax call to backend to create a subscription
$(this).prop('disabled', true);
let spinnerHtml = '<div class="spinner-border text-light"></div>';
let origButtonHtml = $(this).html();
$(this).html(spinnerHtml);

$.ajax({
url: $(this).data('create-sub-url'),
type: 'POST',
data: {
  csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val(),
  'price_id': $(this).data('price-id'),
  'coupon_id': $("#coupon_id").val()
},
success: function (result) {
  if(!result.clientSecret)
  {
      console.log("result not okay")
      window.location.href = '/'
  }
  else{

    $('#client-secret').val(result.clientSecret);
    // Confirm payment intent.
    console.log('set up confirmed');
    stripe.confirmCardSetup(result.clientSecret, {
      payment_method: {
        card: card,
        billing_details: {
          name: $('#cardholder-name').val(),
        },
      }
    }).then((result) => {
      if (result.error) {
        alert('Payment failed:'. result.error.message);
      } else {
        window.location.href = '/'

      }
    });
  }

},
error: function (result){
  $('#submit-payment-btn').html(origButtonHtml);
  if(result.responseJSON.invalid_coupon)
  {
    if($(".coupon-error").length == 0)
      $('.coupon-div').append('<p class="coupon-error text-center" style="color:red">Invalid coupon code</p>')
  }
  else{
    $('#payment-modal').modal('hide');
    alert('Something Went Wrong!')
  }
 }
 }
 );
 })
</code>```

Thanks for any help or point in the right direction! I've been trying to solve this for hours!

Body:
I'm attempting to create a monthly subscription with free 7 day trial, but after the trial period the payment fails.

EDIT: It appears to fail because the customer has no default payment method, so despite the payment method being attached to customer, it is not set to default. I can not figure out how to set it to default payment method.

I am setting ConfirmCardSetup in frontend javascript, which I believe is tying the card to the customer. And I am creating the customer, and starting the subscription/trial in my backend django view.

I have found this in Stripe documentation:

"To use this PaymentMethod as the default for invoice or subscription
payments, set invoice_settings.default_payment_method, on the Customer
to the PaymentMethod’s ID."

but I am unsure how to get the Payment Method ID from front end, and use it to update the customer.

Here is my subscription create view:

class SubscriptionCreateView(View, SubscriptionCancellationMixin,
                         CustomerMixin, StripeReferenceMixin, FetchCouponMixin):

"""View to Create subscription and sync with stripe"""
def post(self, request, *args, **kwargs):
    context = {}
    subscription_payload = {}
    price_id = request.POST.get('price_id')
    coupon_id = request.POST.get('coupon_id')
    customer = self.fetch_customer(request.user)

    #Retrieve stripe coupon id or None
    if coupon_id != '':
        stripe_coupon_id, is_valid = self.is_coupon_valid(coupon_id)
        #Set payload to create a subscription
        subscription_payload['coupon'] = stripe_coupon_id
        #Send invalid coupon response
        if not is_valid:
            context['invalid_coupon'] = True
            response = JsonResponse(context)
            response.status_code = 400
            return response

    if not customer:
        customer = self.stripe.Customer.create(
                email=request.user.email
        )
    try:
        now = int(time.time())
        # Cancel the previous subscription.
        self.cancel_subscription(customer)
        #Create a new subscription
        subscription_payload.update({
            'customer':customer.id,
            'items':  [{
                    'price': price_id,
                },
                ],
            'trial_end': now +30,

        },
            )

        #create a setup intent
        setup_intent = self.stripe.SetupIntent.create(
             payment_method_types=["card"],

             customer=customer.id,
        )
        subscription = self.stripe.Subscription.create(**subscription_payload)

        # Sync the Stripe API return data to the database,
        # this way we don't need to wait for a webhook-triggered sync
        Subscription.sync_from_stripe_data(subscription)
        request.session['created_subscription_id'] = subscription.get('id')

        # Note we're sending the Subscription's
        # latest invoice and client secret
        # to the front end to confirm the payment
        context['subscriptionId'] = subscription.id
        context['clientSecret'] = setup_intent['client_secret']

    except Exception as e:
        response = JsonResponse({})
        response.status_code = 400
        return response

    return JsonResponse(context)

And here's the relevant javascript!

var stripe = Stripe($('#public-key').val());
var elements = stripe.elements();
var style = {
   base: {
     color: "#32325d",
     }
   };

var card = elements.create("card", { style: style });
card.mount("#card-element");

//Capture modal payment button click
$(document).on('click', '#submit-payment-btn', function (e) {
e.preventDefault();
//Send an ajax call to backend to create a subscription
$(this).prop('disabled', true);
let spinnerHtml = '

';
let origButtonHtml = $(this).html();
$(this).html(spinnerHtml);

$.ajax({
url: $(this).data('create-sub-url'),
type: 'POST',
data: {
  csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val(),
  'price_id': $(this).data('price-id'),
  'coupon_id': $("#coupon_id").val()
},
success: function (result) {
  if(!result.clientSecret)
  {
      console.log("result not okay")
      window.location.href = '/'
  }
  else{

    $('#client-secret').val(result.clientSecret);
    // Confirm payment intent.
    console.log('set up confirmed');
    stripe.confirmCardSetup(result.clientSecret, {
      payment_method: {
        card: card,
        billing_details: {
          name: $('#cardholder-name').val(),
        },
      }
    }).then((result) => {
      if (result.error) {
        alert('Payment failed:'. result.error.message);
      } else {
        window.location.href = '/'

      }
    });
  }

},
error: function (result){
  $('#submit-payment-btn').html(origButtonHtml);
  if(result.responseJSON.invalid_coupon)
  {
    if($(".coupon-error").length == 0)
      $('.coupon-div').append('
Invalid coupon code
')
  }
  else{
    $('#payment-modal').modal('hide');
    alert('Something Went Wrong!')
  }
 }
 }
 );
 })

Thanks for any help or point in the right direction! I've been trying to solve this for hours!


问:
Flutter setState is not reloading page
I am building a Flutter app that allows users to create locations and then have those locations uploaded to a database and shown to other users on a map. I have gotten the database and displaying of locations to work properly, but I want the map, a Google Map, to dynamically reload after the user has created a location and is returned to the map screen.

Right now, I am using Firebase Realtime Database to listen for changes and trying to update the map accordingly after the user has clicked on the button to create a new location. Here is the code for that:

```<code>Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => const LocationCreation()),
                    ).then((valuef) {
                      locationsRef.onValue.listen((DatabaseEvent event) {
                        final data = event.snapshot.value;
                        if (event.snapshot.value != null) {
                          allMarkers = {};
                          final map = data as Map<dynamic, dynamic>;
                          map.forEach((key, value){
                            print(value['name']);
                            allLocations.add(value);
                            // Code to create a Marker object called marker
                              }
                            );
                            setState(() {
                                allMarkers.add(marker);
                            });
                          });
                        }
                      });
</code>```

I know this code is reached, because the print statement is being called and the correct names are being printed out, including the name of the newly created location. However, the map screen is not being updated with the new locations and their markers.

The Google Map is being built in the build function as so:

```<code>GoogleMap(
            scrollGesturesEnabled: true,
            onMapCreated: (onCreated),
            initialCameraPosition: CameraPosition(
              target: _center,
              zoom: 11.0,
            ),
            markers: allMarkers,
          ),
</code>```

And here is the onCreated function:

```<code>print('here again');
    mapController = controller;
    final snapshot = await locationsRef.get();
    final map = snapshot.value as Map<dynamic, dynamic>;
    setState(() {
      allMarkers.clear();
      map.forEach((key, value) {
        allLocations.add(value);
        //Code to make a Marker called marker
        allMarkers.add(marker);
      });
    });
</code>```

The print statement is called once upon initial building of the app, but is not called again after a new location has been created and the user is returned to the map screen.

allMarkers is not being initialized within the build function, which I found was a common problem for others.

Each time I try to make a new location, the database will store the new location and the print statement within the listen for new database event will be called, but it seems that Flutter does not detect a change to allMarkers. I have also tried allMarker.clear(), but the problem is the same. I have also tried to move the call to setState(), but nothing has worked.

Title: Flutter setState is not reloading page

Body:
I am building a Flutter app that allows users to create locations and then have those locations uploaded to a database and shown to other users on a map. I have gotten the database and displaying of locations to work properly, but I want the map, a Google Map, to dynamically reload after the user has created a location and is returned to the map screen.

Right now, I am using Firebase Realtime Database to listen for changes and trying to update the map accordingly after the user has clicked on the button to create a new location. Here is the code for that:

Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => const LocationCreation()),
                    ).then((valuef) {
                      locationsRef.onValue.listen((DatabaseEvent event) {
                        final data = event.snapshot.value;
                        if (event.snapshot.value != null) {
                          allMarkers = {};
                          final map = data as Map<dynamic, dynamic>;
                          map.forEach((key, value){
                            print(value['name']);
                            allLocations.add(value);
                            // Code to create a Marker object called marker
                              }
                            );
                            setState(() {
                                allMarkers.add(marker);
                            });
                          });
                        }
                      });

I know this code is reached, because the print statement is being called and the correct names are being printed out, including the name of the newly created location. However, the map screen is not being updated with the new locations and their markers.

The Google Map is being built in the build function as so:

GoogleMap(
            scrollGesturesEnabled: true,
            onMapCreated: (onCreated),
            initialCameraPosition: CameraPosition(
              target: _center,
              zoom: 11.0,
            ),
            markers: allMarkers,
          ),

And here is the onCreated function:

print('here again');
    mapController = controller;
    final snapshot = await locationsRef.get();
    final map = snapshot.value as Map<dynamic, dynamic>;
    setState(() {
      allMarkers.clear();
      map.forEach((key, value) {
        allLocations.add(value);
        //Code to make a Marker called marker
        allMarkers.add(marker);
      });
    });

The print statement is called once upon initial building of the app, but is not called again after a new location has been created and the user is returned to the map screen.

allMarkers is not being initialized within the build function, which I found was a common problem for others.

Each time I try to make a new location, the database will store the new location and the print statement within the listen for new database event will be called, but it seems that Flutter does not detect a change to allMarkers. I have also tried allMarker.clear(), but the problem is the same. I have also tried to move the call to setState(), but nothing has worked.


问:
How to pass self response data with selfHandleResponse in Http Proxy NextJS
I am using http-proxy to forward all requests in NextJS, I want to handle the self response data with selfHandleResponse option. Specifically, I want to do something like set a some data to cookie, etc...) in Next.js API Routes, but if I set selfHandleResponse to true, none of the webOutgoing passes are called, that resulted in my request never being responded. What should I do? Please help me, I have researched but no hope :(

My code below:

```<code>const handleProxyInit = (proxy) => {
    proxy.on('proxyRes', (proxyRes, req, res) => {
        let body = [];

        proxyRes.on('data', function (chunk) {
            body.push(chunk);
        });
        proxyRes.on('end', function () {
            body = Buffer.concat(body).toString('utf8');
            // what should I do here?
        });
    });
};

httpProxyMiddleware(req, res, {
    ...,
    selfHandleResponse: true,
    changeOrigin: true,
    onProxyInit: handleProxyInit,
});
</code>```

Body:
I am using http-proxy to forward all requests in NextJS, I want to handle the self response data with selfHandleResponse option. Specifically, I want to do something like set a some data to cookie, etc...) in Next.js API Routes, but if I set selfHandleResponse to true, none of the webOutgoing passes are called, that resulted in my request never being responded. What should I do? Please help me, I have researched but no hope :(

My code below:

const handleProxyInit = (proxy) => {
    proxy.on('proxyRes', (proxyRes, req, res) => {
        let body = [];

        proxyRes.on('data', function (chunk) {
            body.push(chunk);
        });
        proxyRes.on('end', function () {
            body = Buffer.concat(body).toString('utf8');
            // what should I do here?
        });
    });
};

httpProxyMiddleware(req, res, {
    ...,
    selfHandleResponse: true,
    changeOrigin: true,
    onProxyInit: handleProxyInit,
});


问:
Migrating from CRA to ViteJS, deployment issue with server URL
Currently moving a work project from Create React App to ViteJS. I was a noob when I started working on this project, so I did what I was thought and started with CRA. Let the attacks begin.

In my CRA project I had an env variable called REACT_APP_SERVER_URL, which is self explanatory, but it just links to localhost:8000 on my local machine and to https://exampleserver.com when deployed. It's used for fetching data on the frontend. To get projects you hit https://exampleserver.com/api/projects

When I moved the project to Vite, I changed the env variable to VITE_SERVER_URL. It's all cool and it works amazing on my local machine.

Let's say client url is https://viteclient.com.

Now comes deployment... App crashes on load. I check the console, and good thong I forgot a console.log in on of the fetch functions to tell me what was the issue. I'm getting a 404 from the server. The app made a request to:
https://viteclient.com/exampleserver.com/api/projects

What happened there?? Is VITE_SERVER_URL a saved name for Vite env variables? if so, I can't find anything online about that. It didn't do that in CRA, it doesn't do that in my local machine. Does anyone have any idea what happened? And/or how to fix it.

I tried looking if anyone has a similar issue, but I can't seem to find any other developers having these issues.


问:
How to include space in decrypting a sentence with space using polybius square cipher?
```<code> char[][] matrix = {
                  {'A', 'B', 'C', 'D', 'E'},
                  {'F', 'G', 'H', 'I', 'K'},
                  {'L', 'M', 'N', 'O', 'P'},
                  {'Q', 'R', 'S', 'T', 'U'},
                  {'V', 'W', 'X', 'Y', 'Z'}
                };

</code>```
```<code>
System.out.println("DECIPHER");
sc.nextLine();

System.out.println("ENTER CIPHERTEXT:  ");
ctext = sc.nextLine();
String deciphered = decipher(ctext, matrix);
System.out.println(deciphered);

public static String decipher(String ctext, char[][] matrix) {
            StringBuilder deciphered = new StringBuilder();
            for (int i = 0; i < ctext.length(); i += 2) {
              int row = Character.getNumericValue(ctext.charAt(i)) - 1;
              int col = Character.getNumericValue(ctext.charAt(i + 1)) - 1;
              deciphered.append(matrix[row][col]);
            }
            return deciphered.toString();
     }
</code>```

When encrypting a plaintext, the result is good and it includes the space. On the other hand, when decrypting a ciphertext, the result shows with an error about its index which tells that its out of bounds.

This is the error that it showed

```<code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -2 ou
t of bounds for length 5
    at CASESTUDY_FINALS.POLYBIUS_SQUARE.decipher(POLYBIUS_SQUARE.java:111)
</code>```

I'm expecting that it would also include the space. Can you help me look for the error and help me fix it by including the space in decrypting it using Polybius Square Cipher using Java. Thank you

Body:
 char[][] matrix = {
                  {'A', 'B', 'C', 'D', 'E'},
                  {'F', 'G', 'H', 'I', 'K'},
                  {'L', 'M', 'N', 'O', 'P'},
                  {'Q', 'R', 'S', 'T', 'U'},
                  {'V', 'W', 'X', 'Y', 'Z'}
                };

System.out.println("DECIPHER");
sc.nextLine();

System.out.println("ENTER CIPHERTEXT:  ");
ctext = sc.nextLine();
String deciphered = decipher(ctext, matrix);
System.out.println(deciphered);

public static String decipher(String ctext, char[][] matrix) {
            StringBuilder deciphered = new StringBuilder();
            for (int i = 0; i < ctext.length(); i += 2) {
              int row = Character.getNumericValue(ctext.charAt(i)) - 1;
              int col = Character.getNumericValue(ctext.charAt(i + 1)) - 1;
              deciphered.append(matrix[row][col]);
            }
            return deciphered.toString();
     }

When encrypting a plaintext, the result is good and it includes the space. On the other hand, when decrypting a ciphertext, the result shows with an error about its index which tells that its out of bounds.

This is the error that it showed

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -2 ou
t of bounds for length 5
    at CASESTUDY_FINALS.POLYBIUS_SQUARE.decipher(POLYBIUS_SQUARE.java:111)

I'm expecting that it would also include the space. Can you help me look for the error and help me fix it by including the space in decrypting it using Polybius Square Cipher using Java. Thank you


问:
How to pre-position sankey nodes in plotly?
I started using plotly to draw sankey charts.
I want to display a multi year series with birth and death year by year.

The current code looks like:
`

```<code>import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ["v11","v21","v31","v41","out21","out31","out41","in21","in31","in41", "v12", "v22"],
      color = "blue"
    ),
    link = dict(
      source = [0, 7, 0, 1, 8, 1, 2, 9, 2, 10], #
      target = [1, 1, 4, 2, 2, 5, 3, 3, 6,11],
      value = [1000, 100, 100, 1000, 150, 50, 1000, 120, 80, 800]
  ))])

fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()
</code>```

`

which produces something like:
Sankey

All birth nodes are attached to the left side and the out nodes to the right side.
It should however look like this:

Sankey manually rearranged

Is there a way to pin the x-axis?
Or any d3 example, which does the trick?

Thanks for any hint,
Carl

PS: With the following question I got one step further [https://stackoverflow.com/questions/61152889/plotly-how-to-set-node-positions-in-a-sankey-diagram].
The look like this now:

```<code>import plotly.graph_objects as go

unique_list = ["c0_v_2021","c0_v_2022","c0_v_2023","c0_v_2024","c0_o_2022","c0_o_2023","c0_o_2024","c0_i_2022","c0_i_2023","c0_i_2024"]
title_list = ["Vol 2021","Vol 2022","Vol 2023","Vol 2024","Out 2022","Out 2023","Out 2024","In 2022","In 2023","In 2024"]
sources = [0, 7, 0, 1, 8, 1, 2, 9, 2]
targets = [1, 1, 4, 2, 2, 5, 3, 3, 6]
values = [1000, 100, 100, 1000, 150, 50, 1000, 120, 80]

## correction based on type
def my_corr(node_corr, steps):
    x_corr = []
    y_corr = []
    for ftype in node_corr:
        xcorr = 0
        ycorr = 0
        if ftype == 'i':
            xcorr = - steps/3
            ycorr = -0.2

        x_corr.append(xcorr)
        y_corr.append(ycorr)

    return x_corr   , y_corr
def my_nodify (node_names):
    # node_names = unique_list.copy()
    # unique name endings
    ## get year
    ends = sorted(list(set([e[-4:] for e in node_names])))
    ## get type
    corr = (list(([e[-6] for e in node_names])))
    min, max = ends[0], ends[-1]
    #intervals
    steps = 1/((int(max)-int(min)))
    x_corr, y_corr = my_corr(corr, steps)

    # x-values for each unique name ending for input as node position
    nodes_x = {}
    xVal = 0
    for e in ends:
        nodes_x[str(e)] = xVal
        xVal += steps
    #x and y values in list form
    x_values = [nodes_x[n[-4:]] for n in node_names]
    ## apply x adjustments
    x_values_c = [x_values[i] + x_corr[i] for i in range(len(x_corr))]
    y_values = []
    y_val = 0
    for n in node_names:
        y_values.append(y_val)
        y_val+=.001
    y_values.append(y_val)
    ## apply y adjustments
    y_values_c = [y_values[i] + y_corr[i] for i in range(len(y_corr))]
#    y_values_c = y_values
    return x_values_c, y_values_c
nodified = my_nodify(unique_list)
# plotly setup
fig = go.Figure(data=[go.Sankey(
      arrangement='snap',
#      arrangement='perpendicular',
      node = dict(
      pad = 5,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = title_list,
      color = "blue",
      x=nodified[0],      y=nodified[1]

    ),
    link = dict(
      source = sources,
      target = targets,
      value = values
  ))])

fig.update_layout(
    hovermode = 'x',
    title="Some Flow",
    font=dict(size = 10, color = 'white'),
    plot_bgcolor='black',
    paper_bgcolor='black'
)
fig.show()
</code>```

and produces almost what I want although the In-nodes overlapp and the sorting of link is inconsistent.

How can I influence this behaviour?

Body:
I started using plotly to draw sankey charts.
I want to display a multi year series with birth and death year by year.

The current code looks like:
`

import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ["v11","v21","v31","v41","out21","out31","out41","in21","in31","in41", "v12", "v22"],
      color = "blue"
    ),
    link = dict(
      source = [0, 7, 0, 1, 8, 1, 2, 9, 2, 10], #
      target = [1, 1, 4, 2, 2, 5, 3, 3, 6,11],
      value = [1000, 100, 100, 1000, 150, 50, 1000, 120, 80, 800]
  ))])

fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()

`

which produces something like:
Sankey

All birth nodes are attached to the left side and the out nodes to the right side.
It should however look like this:

Sankey manually rearranged

Is there a way to pin the x-axis?
Or any d3 example, which does the trick?

Thanks for any hint,
Carl

PS: With the following question I got one step further [https://stackoverflow.com/questions/61152889/plotly-how-to-set-node-positions-in-a-sankey-diagram].
The look like this now:

import plotly.graph_objects as go

unique_list = ["c0_v_2021","c0_v_2022","c0_v_2023","c0_v_2024","c0_o_2022","c0_o_2023","c0_o_2024","c0_i_2022","c0_i_2023","c0_i_2024"]
title_list = ["Vol 2021","Vol 2022","Vol 2023","Vol 2024","Out 2022","Out 2023","Out 2024","In 2022","In 2023","In 2024"]
sources = [0, 7, 0, 1, 8, 1, 2, 9, 2]
targets = [1, 1, 4, 2, 2, 5, 3, 3, 6]
values = [1000, 100, 100, 1000, 150, 50, 1000, 120, 80]

## correction based on type
def my_corr(node_corr, steps):
    x_corr = []
    y_corr = []
    for ftype in node_corr:
        xcorr = 0
        ycorr = 0
        if ftype == 'i':
            xcorr = - steps/3
            ycorr = -0.2

        x_corr.append(xcorr)
        y_corr.append(ycorr)

    return x_corr   , y_corr
def my_nodify (node_names):
    # node_names = unique_list.copy()
    # unique name endings
    ## get year
    ends = sorted(list(set([e[-4:] for e in node_names])))
    ## get type
    corr = (list(([e[-6] for e in node_names])))
    min, max = ends[0], ends[-1]
    #intervals
    steps = 1/((int(max)-int(min)))
    x_corr, y_corr = my_corr(corr, steps)

    # x-values for each unique name ending for input as node position
    nodes_x = {}
    xVal = 0
    for e in ends:
        nodes_x[str(e)] = xVal
        xVal += steps
    #x and y values in list form
    x_values = [nodes_x[n[-4:]] for n in node_names]
    ## apply x adjustments
    x_values_c = [x_values[i] + x_corr[i] for i in range(len(x_corr))]
    y_values = []
    y_val = 0
    for n in node_names:
        y_values.append(y_val)
        y_val+=.001
    y_values.append(y_val)
    ## apply y adjustments
    y_values_c = [y_values[i] + y_corr[i] for i in range(len(y_corr))]
#    y_values_c = y_values
    return x_values_c, y_values_c
nodified = my_nodify(unique_list)
# plotly setup
fig = go.Figure(data=[go.Sankey(
      arrangement='snap',
#      arrangement='perpendicular',
      node = dict(
      pad = 5,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = title_list,
      color = "blue",
      x=nodified[0],      y=nodified[1]

    ),
    link = dict(
      source = sources,
      target = targets,
      value = values
  ))])

fig.update_layout(
    hovermode = 'x',
    title="Some Flow",
    font=dict(size = 10, color = 'white'),
    plot_bgcolor='black',
    paper_bgcolor='black'
)
fig.show()

and produces almost what I want although the In-nodes overlapp and the sorting of link is inconsistent.

How can I influence this behaviour?


问:
How to test mongoose methods using sinon fakes?
I have the following arrangement of tests using sinon, mocha and chai:

type ModelObject = {
    name: string;
    model: typeof Categoria | typeof Articulo | typeof Usuario;
    fakeMultiple: () => object[];
    fakeOne: (id?: string) => object;
}

const models: ModelObject[] = [
    {
        name: 'categorias',
        model: Categoria,
        fakeMultiple: () => fakeMultiple({ creator: oneCategoria }),
        fakeOne: oneCategoria
    },
    {
        name: 'articulos',
        model: Articulo,
        fakeMultiple: () => fakeMultiple({ creator: oneArticulo }),
        fakeOne: oneArticulo
    },
    {
        name: 'usuarios',
        model: Usuario,
        fakeMultiple: () => fakeMultiple({ creator: oneUsuario }),
        fakeOne: oneUsuario
    }
];

const randomModel = models[Math.floor(Math.random() * models.length)];

describe(`v1/${randomModel.name}`, function () {

    this.afterEach(function () {
        sinon.restore();
    });

    context.only("When requesting information from an endpoint, this should take the Model of the requested endpoint and query the database for all the elements of that model", function () {
        it.only(`Should return a list of elements of ${randomModel.name} model`, function (done) {
            const fakes = randomModel.fakeMultiple();

            const findFake = sinon.fake.resolves({ [randomModel.name]: fakes });

            sinon.replace(randomModel.model, 'find', findFake);

            chai.request(app)
                .get(`/api/v1/${randomModel.name}`)
                .end(
                    (err, res) => {
                        expect(res).to.have.status(200);
                        expect(res.body.data).to.be.an('object');
                        expect(res.body.data).to.have.property(randomModel.name);
                        expect(res.body.data[randomModel.name]).to.have.lengthOf(fakes.length);
                        expect(findFake.calledOnce).to.be.true;
                        done();
                    }
                )
        });
}}
```
<p>I use this to test an endpoint that arbitrary returns information about a given model. In my controllers, I'm using a dynamic middleware to determine which model is going to be queried, for example, if the route consumed is "api/v1/categorias", it will query for Categorias model. If the route consumed is "api/v1/articulos", it will query for Articulos model, and so on.</p>
<p>To make the query, i use the following service:</p>
<pre class="lang-js prettyprint-override"><code>import { Articulo } from '../models/articulo';
import { Usuario } from '../models/usuario';
import { Categoria } from '../models/categoria';
import logger from '../config/logging';
import { Model } from 'mongoose';

const determineModel = (model: string): Model<any> => {
    switch (model) {
        case 'articulos':
            return Articulo;
        case 'usuarios':
            return Usuario;
        case 'categorias':
            return Categoria;
        default:
            throw new Error(`Model ${model} not found`);
    }
};

export const getInformation = async (schema: string, page: number, limit: number) => {
    try {
        const model = determineModel(schema);
        const data = await model.find().skip((page - 1) * limit).limit(limit);

        const dataLength = await model.find().countDocuments();

        return {
            data,
            total: dataLength,
        };

    } catch (err) {
        logger.error(err);
        console.log(err);
        throw err;
    }

};
</code>```

The problem here lies when running my tests, it seems that is unable to run the .skip() and .limit() methods for my model.find()

```<code>error: model.find(...).skip is not a function
TypeError: model.find(...).skip is not a function
</code>```

I think that I need to fake those methods, because when running the same test without skip and limit, it works as a charm. My problem lies in the fact that I don't know how to fake those, or to see if my guess is correct.

As a note, I have default params for the variables page and limit (1 and 15 respectively) so I'm not passing empty values to the methods.

Body:
I have the following arrangement of tests using sinon, mocha and chai:

type ModelObject = {
    name: string;
    model: typeof Categoria | typeof Articulo | typeof Usuario;
    fakeMultiple: () => object[];
    fakeOne: (id?: string) => object;
}

const models: ModelObject[] = [
    {
        name: 'categorias',
        model: Categoria,
        fakeMultiple: () => fakeMultiple({ creator: oneCategoria }),
        fakeOne: oneCategoria
    },
    {
        name: 'articulos',
        model: Articulo,
        fakeMultiple: () => fakeMultiple({ creator: oneArticulo }),
        fakeOne: oneArticulo
    },
    {
        name: 'usuarios',
        model: Usuario,
        fakeMultiple: () => fakeMultiple({ creator: oneUsuario }),
        fakeOne: oneUsuario
    }
];

const randomModel = models[Math.floor(Math.random() * models.length)];

describe(`v1/${randomModel.name}`, function () {

    this.afterEach(function () {
        sinon.restore();
    });

    context.only("When requesting information from an endpoint, this should take the Model of the requested endpoint and query the database for all the elements of that model", function () {
        it.only(`Should return a list of elements of ${randomModel.name} model`, function (done) {
            const fakes = randomModel.fakeMultiple();

            const findFake = sinon.fake.resolves({ [randomModel.name]: fakes });

            sinon.replace(randomModel.model, 'find', findFake);

            chai.request(app)
                .get(`/api/v1/${randomModel.name}`)
                .end(
                    (err, res) => {
                        expect(res).to.have.status(200);
                        expect(res.body.data).to.be.an('object');
                        expect(res.body.data).to.have.property(randomModel.name);
                        expect(res.body.data[randomModel.name]).to.have.lengthOf(fakes.length);
                        expect(findFake.calledOnce).to.be.true;
                        done();
                    }
                )
        });
}}

I use this to test an endpoint that arbitrary returns information about a given model. In my controllers, I'm using a dynamic middleware to determine which model is going to be queried, for example, if the route consumed is "api/v1/categorias", it will query for Categorias model. If the route consumed is "api/v1/articulos", it will query for Articulos model, and so on.

To make the query, i use the following service:

import { Articulo } from '../models/articulo';
import { Usuario } from '../models/usuario';
import { Categoria } from '../models/categoria';
import logger from '../config/logging';
import { Model } from 'mongoose';

const determineModel = (model: string): Model<any> => {
    switch (model) {
        case 'articulos':
            return Articulo;
        case 'usuarios':
            return Usuario;
        case 'categorias':
            return Categoria;
        default:
            throw new Error(`Model ${model} not found`);
    }
};

export const getInformation = async (schema: string, page: number, limit: number) => {
    try {
        const model = determineModel(schema);
        const data = await model.find().skip((page - 1) * limit).limit(limit);

        const dataLength = await model.find().countDocuments();

        return {
            data,
            total: dataLength,
        };

    } catch (err) {
        logger.error(err);
        console.log(err);
        throw err;
    }

};

The problem here lies when running my tests, it seems that is unable to run the .skip() and .limit() methods for my model.find()

error: model.find(...).skip is not a function
TypeError: model.find(...).skip is not a function

I think that I need to fake those methods, because when running the same test without skip and limit, it works as a charm. My problem lies in the fact that I don't know how to fake those, or to see if my guess is correct.

As a note, I have default params for the variables page and limit (1 and 15 respectively) so I'm not passing empty values to the methods.


问:
Using multiparty, but can't resolve 'fs' in path\to\node_modules\multiparty
Some piece in my project
When I use {const multiparty = require('connect-multiparty')}, the error occurs in the directory of multiparty.
And the segment of code is as following picture:
The code piece of the node_module\multiparty

I have tried all of the ways in stackoverflow about this topic, but I can't make this error gone. If anyone met this issue before, thanks so much due to the incoming deadline of course work


问:
Doctrine count groupe By
I have this query:

```<code>$sqlRequete = $bdd -> query("SELECT idJeu, COUNT(*) FROM documents_lignes GROUP BY idJeu ORDER BY count(*) DESC LIMIT 20");

</code>```

How can I do this with Doctrine in a Symfony project ?
I have a table named documents_lignes with one jointure: boite (IdJeu)

Thank you

I have try this:

```<code>    public function findBoitesGroupeBy(){

        return $this->createQueryBuilder('dl')
            ->select('dl.boite, COUNT(dl.boite)')
            ->innerJoin('dl.boite', 'b')
            ->groupBy('b.id')
            ->getQuery()
            ->getArrayResult();
    }
</code>```

But the result is not correct

Title: Doctrine count groupe By

Body:
I have this query:

$sqlRequete = $bdd -> query("SELECT idJeu, COUNT(*) FROM documents_lignes GROUP BY idJeu ORDER BY count(*) DESC LIMIT 20");

How can I do this with Doctrine in a Symfony project ?
I have a table named documents_lignes with one jointure: boite (IdJeu)

Thank you

I have try this:

    public function findBoitesGroupeBy(){

        return $this->createQueryBuilder('dl')
            ->select('dl.boite, COUNT(dl.boite)')
            ->innerJoin('dl.boite', 'b')
            ->groupBy('b.id')
            ->getQuery()
            ->getArrayResult();
    }

But the result is not correct


问:
Originator doesn't have entitlement - ImageWriteToSavedPhotosAlbum
I am trying to save the image from a URL from my server:

```<code>let urlString = "http://someValidUrlToAnImage.png"
let url = URL(string: urlString )

DispatchQueue.global().async {
    if let data = try? Data(contentsOf: url!) {
        if let image = UIImage(data: data) {
            DispatchQueue.main.async {
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                print( "Image saved !!!!" )
            }
        }
    }
}
</code>```

It was working fine before, but now I am getting this error:

Error acquiring assertion: <Error Domain=RBSServiceErrorDomain Code=1 "(originator doesn't have entitlement com.apple.runningboard.assertions.webkit AND originator doesn't have entitlement com.apple.multitasking.systemappassertions)" UserInfo={NSLocalizedFailureReason=(originator doesn't have entitlement com.apple.runningboard.assertions.webkit AND originator doesn't have entitlement com.apple.multitasking.systemappassertions)}>

I am testing it via Xcode and USB cable.
I have added all the entitlements to Xcode's plist and to the AppStoreConnect site.

What could be causing this error?

Body:
I am trying to save the image from a URL from my server:

let urlString = "http://someValidUrlToAnImage.png"
let url = URL(string: urlString )

DispatchQueue.global().async {
    if let data = try? Data(contentsOf: url!) {
        if let image = UIImage(data: data) {
            DispatchQueue.main.async {
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                print( "Image saved !!!!" )
            }
        }
    }
}

It was working fine before, but now I am getting this error:

Error acquiring assertion: <Error Domain=RBSServiceErrorDomain Code=1 "(originator doesn't have entitlement com.apple.runningboard.assertions.webkit AND originator doesn't have entitlement com.apple.multitasking.systemappassertions)" UserInfo={NSLocalizedFailureReason=(originator doesn't have entitlement com.apple.runningboard.assertions.webkit AND originator doesn't have entitlement com.apple.multitasking.systemappassertions)}>

I am testing it via Xcode and USB cable.
I have added all the entitlements to Xcode's plist and to the AppStoreConnect site.

What could be causing this error?


问:
virtuozzo nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
I am deploying a docker image to virtuozzo application plateform, the image is setting up nginx with port 80, however the docker containers in virtuozzo somehow use port 80 by default

So, I am getting an error in the run.log which doesn't stop from showing, it looks something like this:

```<code>nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
cron: can't lock /var/run/crond.pid, otherpid may be 140: Resource temporarily unavailable
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()
2022/12/26 17:28:22 [emerg] 673#673: still could not bind()
2022/12/26 17:28:19 [emerg] 657#657: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:19 [emerg] 657#657: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:19 [emerg] 657#657: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:19 [emerg] 657#657: still could not bind()
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: still could not bind()
cron: can't lock /var/run/crond.pid, otherpid may be 140: Resource temporarily unavailable
</code>```

It's possible I am doing something wrong on my own, but I have no idea, I would appreciate your help

Body:
I am deploying a docker image to virtuozzo application plateform, the image is setting up nginx with port 80, however the docker containers in virtuozzo somehow use port 80 by default

So, I am getting an error in the run.log which doesn't stop from showing, it looks something like this:

nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
cron: can't lock /var/run/crond.pid, otherpid may be 140: Resource temporarily unavailable
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()
2022/12/26 17:28:22 [emerg] 673#673: still could not bind()
2022/12/26 17:28:19 [emerg] 657#657: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:19 [emerg] 657#657: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:19 [emerg] 657#657: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:19 [emerg] 657#657: still could not bind()
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: bind() to 0.0.0.0:80 failed (98: Address already in use)
2022/12/26 17:28:22 [emerg] 673#673: still could not bind()
cron: can't lock /var/run/crond.pid, otherpid may be 140: Resource temporarily unavailable

It's possible I am doing something wrong on my own, but I have no idea, I would appreciate your help


问:
How to access backend microservice (http) from a frontend microservice (https via aws alb) in kubernetes (eks)?
Here's the context about resources in my EKS cluster:

Backend microservice exposed via service running on port 80

Frontend microservice exposed via service running on port 80

Frontend service calls backend service using the fqdn http://backend-service.backend.svc.cluster.local for REST API calls.

Additionally, I have also an ingress object that created an application load balancer for frontend microservice.

The load balancer has ACM SSL certificate attached.

https://my-website.com sends the traffic to the frontend service which in turn calls the HTTP backend microservice for REST API calls.

But I'm getting the following error:

```<code>The page at https://my-website.com was loaded over HTTPS but requested an insecure XMLHttpRequest endpoint http://backend-service.backend.svc.cluster.local
</code>```

How do I fix this error? I don't want to expose my backend service to the outside world with a load balancer or anything.

Edit:

My frontend is written in React.js

My backend is a node.js express app

Body:
Here's the context about resources in my EKS cluster:

Backend microservice exposed via service running on port 80

Frontend microservice exposed via service running on port 80

Frontend service calls backend service using the fqdn http://backend-service.backend.svc.cluster.local for REST API calls.

Additionally, I have also an ingress object that created an application load balancer for frontend microservice.

The load balancer has ACM SSL certificate attached.

https://my-website.com sends the traffic to the frontend service which in turn calls the HTTP backend microservice for REST API calls.

But I'm getting the following error:

The page at https://my-website.com was loaded over HTTPS but requested an insecure XMLHttpRequest endpoint http://backend-service.backend.svc.cluster.local

How do I fix this error? I don't want to expose my backend service to the outside world with a load balancer or anything.

Edit:

My frontend is written in React.js

My backend is a node.js express app


问:
Grpc Testing on MacOS with protobuf-net.Grpc.AspNetCore
I'm having a hard time trying to figure out how to appropriately test Grpc with Authentication/Authorization on MacOS.

System.ArgumentException: CallCredentials can't be composed with InsecureCredentials. CallCredentials must be used with secure channel credentials like SslCredentials.

I'm unable to test locally using SSL as it appears its not supported with HTTP2 on MacOS.

```<code>options.ListenAnyIP(8080);
options.ListenAnyIP(8585, listenOptions =>
{
    listenOptions.Protocols = HttpProtocols.Http2;
});
</code>```

And here is how the channel is created

```<code>private async Task<GrpcChannel> CreateAuthenticatedChannel()
{
    var token = await ApiClient.GetTokenAsync();
    var credentials = CallCredentials.FromInterceptor((context, metadata) =>
    {
        metadata.Add("Authorization", $"Bearer {token}");
        return Task.CompletedTask;
    });

    var channel = GrpcChannel.ForAddress("http://localhost:8585", new GrpcChannelOptions
    {
        Credentials = ChannelCredentials.Create(ChannelCredentials.Insecure, credentials),
        UnsafeUseInsecureChannelCallCredentials = true
    });
    return channel;
}
</code>```

If I attempt to switch the HTTP2 port to SSL on MacOS, I get the following error

HTTP/2 over TLS is not supported on macOS due to missing ALPN support.

Body:
I'm having a hard time trying to figure out how to appropriately test Grpc with Authentication/Authorization on MacOS.

System.ArgumentException: CallCredentials can't be composed with InsecureCredentials. CallCredentials must be used with secure channel credentials like SslCredentials.

I'm unable to test locally using SSL as it appears its not supported with HTTP2 on MacOS.

options.ListenAnyIP(8080);
options.ListenAnyIP(8585, listenOptions =>
{
    listenOptions.Protocols = HttpProtocols.Http2;
});

And here is how the channel is created

private async Task<GrpcChannel> CreateAuthenticatedChannel()
{
    var token = await ApiClient.GetTokenAsync();
    var credentials = CallCredentials.FromInterceptor((context, metadata) =>
    {
        metadata.Add("Authorization", $"Bearer {token}");
        return Task.CompletedTask;
    });

    var channel = GrpcChannel.ForAddress("http://localhost:8585", new GrpcChannelOptions
    {
        Credentials = ChannelCredentials.Create(ChannelCredentials.Insecure, credentials),
        UnsafeUseInsecureChannelCallCredentials = true
    });
    return channel;
}

If I attempt to switch the HTTP2 port to SSL on MacOS, I get the following error

HTTP/2 over TLS is not supported on macOS due to missing ALPN support.


问:
Will WinRT be usable in Desktop Apps (no Metro style)?

Possible Duplicate:

  WinRT and build-in Windows 8 Apps

I've watched almost all BUILD session videos, but one question never got asked/answered:
Will I be able to use the WinRT classes in common 'Desktop mode' applications (no Metro style)?

ContentLicense: CC BY-SA 3.0


问:
Wikidata SPARQL filter properties by id
I have the following sparql:

```<code>#Cats
SELECT ?item ?itemLabel ?prop
WHERE
{
  ?item ?prop wd:Q7206.
  filter not exists {?prop **FILTER** wdt:P921 }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
# Helps get the label in your language, if not, then en language
}
</code>```

I want to return relations excluding P921. What should I enter instead of FILTER?

Title: Wikidata SPARQL filter properties by id

Body:
I have the following sparql:

#Cats
SELECT ?item ?itemLabel ?prop
WHERE
{
  ?item ?prop wd:Q7206.
  filter not exists {?prop **FILTER** wdt:P921 }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
# Helps get the label in your language, if not, then en language
}

I want to return relations excluding P921. What should I enter instead of FILTER?


问:
Streaming Updates from websocket api with redux-toolkit
I am new to redux-toolkit query and also new to websocket APIs, and I am trying to get a stream of data from a websocket API and store it in a redux store.

I have read the documentation for createApi and useQuery, but I am still having difficulty understanding this part.

Here is the message structure that the websocket API gets:

```<code>{
"message_type": "xxx",
"payload": {
    "event_id": "sr:match:xxxxxx"
}
</code>```

}

is this code should do the work?

```<code>import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query";

export const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: "/" }),
  reducerPath: "api",
  tagTypes: ["Message"],
  endpoints: (build) => ({
    streamMessages: build.query({
      queryFn: () => ({ data: [] }),
      async onCacheEntryAdded(arg, { updateCachedData, cacheEntryRemoved }) {
        const ws = new WebSocket("ws://localhost:8080/ws");
        ws.addEventListener("open", () => {
          ws.addEventListener("message", (event) => {
            updateCachedData((draft) => {
              draft.push(event);
            });
          });
        });

        await cacheEntryRemoved;
        ws.close();
      },
    }),
  }),
});

export const { useStreamMessagesQuery } = api;

</code>```

and if it is, how can i use it? when i try using useStreamMessagesQuery in some components its undefined and not a function.
Thank you.

Body:
I am new to redux-toolkit query and also new to websocket APIs, and I am trying to get a stream of data from a websocket API and store it in a redux store.

I have read the documentation for createApi and useQuery, but I am still having difficulty understanding this part.

Here is the message structure that the websocket API gets:

{
"message_type": "xxx",
"payload": {
    "event_id": "sr:match:xxxxxx"
}

}

is this code should do the work?

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query";

export const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: "/" }),
  reducerPath: "api",
  tagTypes: ["Message"],
  endpoints: (build) => ({
    streamMessages: build.query({
      queryFn: () => ({ data: [] }),
      async onCacheEntryAdded(arg, { updateCachedData, cacheEntryRemoved }) {
        const ws = new WebSocket("ws://localhost:8080/ws");
        ws.addEventListener("open", () => {
          ws.addEventListener("message", (event) => {
            updateCachedData((draft) => {
              draft.push(event);
            });
          });
        });

        await cacheEntryRemoved;
        ws.close();
      },
    }),
  }),
});

export const { useStreamMessagesQuery } = api;

and if it is, how can i use it? when i try using useStreamMessagesQuery in some components its undefined and not a function.
Thank you.


问:
Can't add "list:xxxxxxxxxxx" StreamRule to StreamingClient of Twitter API v2
I can't add "list:XXXXXXXXXX" to my rules (I can add other rules though and they work).
What I'm missing?

```<code>import tweepy

class TweetPrinter(tweepy.StreamingClient):
    def on_tweet(self, tweet):
        print(tweet)
printer = TweetPrinter(bearer_token)
printer.add_rules(tweepy.StreamRule("list:XXXXXXXXXX"))
printer.filter()
</code>```

After executing this code instead of creating a StreamRule with an id, I got this (checking the list of the rules with printer.get_rules():

Response(data=None, includes={}, errors=[], meta={'sent': '2022-12-27T00:23:44.073Z', 'result_count': 0})

I'm using Tweepy 4.12 and Twitter API v2.

Body:
I can't add "list:XXXXXXXXXX" to my rules (I can add other rules though and they work).
What I'm missing?

import tweepy

class TweetPrinter(tweepy.StreamingClient):
    def on_tweet(self, tweet):
        print(tweet)
printer = TweetPrinter(bearer_token)
printer.add_rules(tweepy.StreamRule("list:XXXXXXXXXX"))
printer.filter()

After executing this code instead of creating a StreamRule with an id, I got this (checking the list of the rules with printer.get_rules():

Response(data=None, includes={}, errors=[], meta={'sent': '2022-12-27T00:23:44.073Z', 'result_count': 0})

I'm using Tweepy 4.12 and Twitter API v2.


问:
How to authenticate a user to AWS cognito with pyscript?
I want to authenticate a user to AWS cognito from within pyscript.
In python, one would use the python boto3 module. In pyscript however, I have to make the calls to AWS running in async mode, and I have to await the answer. boto3 doesn't support asyncio calls.

I found the python aioboto3 module.
Unfortunatly, pyscript reports that it's unable to install the package:
PY1001): Unable to install package(s) 'aioboto3'. Reason: Can't find a pure Python 3 Wheel for package(s) 'aioboto3'
Same error (for another package) is mentioned in
Couldn't find a pure Python 3 wheel for 'tensorflow'. You can use `micropip.install(..., keep_going=True)` to get a list of all packages

Anybody an idea how I can interface with AWS from pyscript?


问:
Cant format and insert data from input into the database
I have a simple form like this:

```<code> <form action="#" th:action="@{/api/transaction/saveTransaction}" th:object="${transaction}" method="POST">
    <input type="text" th:field="*{amount}" placeholder="Enter a amount" class="form-control mb-4 col-4">

    <input type="text" th:field="*{note}" placeholder="Enter a note" class="form-control mb-4 col-4">
    <input type="date" th:field="*{date}" class="form-control mb-4 col-4">

    <button type="submit" class="btn btn-info col-2"> Save Wallet</button>
</form>
</code>```

As you can see I have field to pick a date here:

```<code><input type="date" th:field="*{date}" class="form-control mb-4 col-4">
</code>```

But I'm getting this error:

```<code>errors<EOL>Field error in object 'transaction' on field 'date': rejected value [2022-12-14]; codes [typeMismatch.transaction.date,typeMismatch.date,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [transaction.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat @javax.persistence.Column java.util.Date] for value '2022-12-14'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-12-14]]]
</code>```

This is how that field look in entity:

```<code>@DateTimeFormat(pattern = "mm-DD-yyyy")
@Column(name = "date")
private Date date;
</code>```

I tried already to find something that can help me to solve this but without any success, I tried to change format but nothing has changed, still error.

Also to mention, I tried with both sql.Date and util.Date

Body:
I have a simple form like this:

 <form action="#" th:action="@{/api/transaction/saveTransaction}" th:object="${transaction}" method="POST">
    <input type="text" th:field="*{amount}" placeholder="Enter a amount" class="form-control mb-4 col-4">

    <input type="text" th:field="*{note}" placeholder="Enter a note" class="form-control mb-4 col-4">
    <input type="date" th:field="*{date}" class="form-control mb-4 col-4">

    <button type="submit" class="btn btn-info col-2"> Save Wallet</button>
</form>

As you can see I have field to pick a date here:

<input type="date" th:field="*{date}" class="form-control mb-4 col-4">

But I'm getting this error:

errors<EOL>Field error in object 'transaction' on field 'date': rejected value [2022-12-14]; codes [typeMismatch.transaction.date,typeMismatch.date,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [transaction.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat @javax.persistence.Column java.util.Date] for value '2022-12-14'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-12-14]]]

This is how that field look in entity:

@DateTimeFormat(pattern = "mm-DD-yyyy")
@Column(name = "date")
private Date date;

I tried already to find something that can help me to solve this but without any success, I tried to change format but nothing has changed, still error.

Also to mention, I tried with both sql.Date and util.Date


问:
How convert miladi date to shamsi
I am looking for a solution in Python that I can use to convert the miladi date into shamsi using mathematical calculations

I looked for this on the internet, but there was only year conversion, and I used this code:

```<code>from datetime import datetime
def persian_time():
    data = {'hour': datetime.now().hour,'min':datetime.now().minute,'year':datetime.now().year,'month':datetime.now().month,'day':datetime.now().day}
    if data['month'] <= 3 and data['day'] <= 21:
        result = 622
    elif data['month'] <= 4 and data['day'] >= 22:
        result = 621
    return data['year'] - result

</code>```

I did, but it only showed the year

Title: How convert miladi date to shamsi

Body:
I am looking for a solution in Python that I can use to convert the miladi date into shamsi using mathematical calculations

I looked for this on the internet, but there was only year conversion, and I used this code:

from datetime import datetime
def persian_time():
    data = {'hour': datetime.now().hour,'min':datetime.now().minute,'year':datetime.now().year,'month':datetime.now().month,'day':datetime.now().day}
    if data['month'] <= 3 and data['day'] <= 21:
        result = 622
    elif data['month'] <= 4 and data['day'] >= 22:
        result = 621
    return data['year'] - result

I did, but it only showed the year


问:
Can't delete strikethrough file
I couldn't delete the underlined file in any way.
I'm typing git rm --cached index.html from terminal and I want to unfollow index.html. But after typing the code in terminal, it is unfollowed but also the strikethrough index.html file appears. How can I destroy this strikethrough index.html file?

I wrote the code rm --cached index.html in the terminal, but two index.html files appeared in the source control section. One of the existing index.html file is strikethrough and the other is normal. How can the underlined file be destroyed?

Title: Can't delete strikethrough file