问:
Running an asyncoio socket server and client on the same process for tests
I wrote a socket server and client package with asyncio that happens to be a single module with two classes Server and Client. The intention is to have the code check if the specified port is in use on the same device, and if so, it will choose the use the Client class instead of the Server class. I am doing this to enable local testing between client and server for a larger goal.

I wrote my unit test with pytest and I can get it to pass if I run the server in its own process first, then run the client in another process.

However, I want to test both server and client together in the same process using pytest. The test never completes this way, however.

Am I running into an issue with asyncio here? Or is it an issue with pytest? Or is it something I am doing wrong in my code?

WebSockets.websocket

import asyncio

class Server:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.server = None
        self.connections = {}

    async def start(self):
        self.server = server = await asyncio.start_server(self.handle_client, self.host, self.port)
        addr = server.sockets[0].getsockname()
        print(f'Serving on {addr}')
        async with server:
            await server.serve_forever()

    async def handle_client(self, reader, writer):
        addr = writer.get_extra_info('peername')
        print(f'New connection from {addr}')
        self.connections[addr] = writer
        try:
            while not reader.at_eof():
                data = await reader.read(100)
                message = data.decode()
                if message:
                    print(f'Received {message!r} from {addr}')
                    await self.send(message, addr)
        finally:
            del self.connections[addr]
            writer.close()

    async def send(self, message, addr):
        writer = self.connections.get(addr)
        if not writer:
            return
        writer.write(message.encode())
        await writer.drain()

    async def recv(self, addr):
        reader, _ = await asyncio.open_connection(addr[0], addr[1])
        data = await reader.read(100)
        return data.decode()

    async def stop(self):
        await self.server.close()

class Client:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.reader = None
        self.writer = None

    async def connect(self):
        self.reader, self.writer = await asyncio.open_connection(self.host, self.port)

    async def send(self, message):
        self.writer.write(message.encode())

    async def recv(self):
        data = await self.reader.read(100)
        return data.decode()

    async def close(self):
        self.writer.close()

```
<p><strong>Test</strong></p>
<pre class="lang-py prettyprint-override"><code>import socket
import asyncio
from WebSockets.websocket import Server, Client
import pytest

def check_port(address, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((address, port))
        s.close()
        return "server"
    except OSError:
        return "client"

async def serve():
    server = Server('localhost', 8910)
    await server.start()

async def client_connect():
    client = Client('localhost', 8910)
    await client.connect()
    await client.send("Hello world!")

    message = await client.recv()
    if message:
        print(f"Received {message!r} from server")
        assert message == "Hello world!"
        await client.close()

@pytest.mark.asyncio
async def test_sockets():
    if check_port("localhost", 8910) == "server":
        await serve()
        # for reference on how to use in non pytest module
        # loop = asyncio.new_event_loop()
        # loop.run_until_complete(serve())
        # loop.close()
    else:
        await client_connect()
        # for reference on how to use in non pytest module
        # loop = asyncio.new_event_loop()
        # loop.run_until_complete(client_connect())
        # loop.close()

</code>```

Body:
I wrote a socket server and client package with asyncio that happens to be a single module with two classes Server and Client. The intention is to have the code check if the specified port is in use on the same device, and if so, it will choose the use the Client class instead of the Server class. I am doing this to enable local testing between client and server for a larger goal.

I wrote my unit test with pytest and I can get it to pass if I run the server in its own process first, then run the client in another process.

However, I want to test both server and client together in the same process using pytest. The test never completes this way, however.

Am I running into an issue with asyncio here? Or is it an issue with pytest? Or is it something I am doing wrong in my code?

WebSockets.websocket

import asyncio

class Server:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.server = None
        self.connections = {}

    async def start(self):
        self.server = server = await asyncio.start_server(self.handle_client, self.host, self.port)
        addr = server.sockets[0].getsockname()
        print(f'Serving on {addr}')
        async with server:
            await server.serve_forever()

    async def handle_client(self, reader, writer):
        addr = writer.get_extra_info('peername')
        print(f'New connection from {addr}')
        self.connections[addr] = writer
        try:
            while not reader.at_eof():
                data = await reader.read(100)
                message = data.decode()
                if message:
                    print(f'Received {message!r} from {addr}')
                    await self.send(message, addr)
        finally:
            del self.connections[addr]
            writer.close()

    async def send(self, message, addr):
        writer = self.connections.get(addr)
        if not writer:
            return
        writer.write(message.encode())
        await writer.drain()

    async def recv(self, addr):
        reader, _ = await asyncio.open_connection(addr[0], addr[1])
        data = await reader.read(100)
        return data.decode()

    async def stop(self):
        await self.server.close()

class Client:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.reader = None
        self.writer = None

    async def connect(self):
        self.reader, self.writer = await asyncio.open_connection(self.host, self.port)

    async def send(self, message):
        self.writer.write(message.encode())

    async def recv(self):
        data = await self.reader.read(100)
        return data.decode()

    async def close(self):
        self.writer.close()

Test

import socket
import asyncio
from WebSockets.websocket import Server, Client
import pytest

def check_port(address, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((address, port))
        s.close()
        return "server"
    except OSError:
        return "client"

async def serve():
    server = Server('localhost', 8910)
    await server.start()

async def client_connect():
    client = Client('localhost', 8910)
    await client.connect()
    await client.send("Hello world!")

    message = await client.recv()
    if message:
        print(f"Received {message!r} from server")
        assert message == "Hello world!"
        await client.close()

@pytest.mark.asyncio
async def test_sockets():
    if check_port("localhost", 8910) == "server":
        await serve()
        # for reference on how to use in non pytest module
        # loop = asyncio.new_event_loop()
        # loop.run_until_complete(serve())
        # loop.close()
    else:
        await client_connect()
        # for reference on how to use in non pytest module
        # loop = asyncio.new_event_loop()
        # loop.run_until_complete(client_connect())
        # loop.close()


来源: stackexchange

问:
How to add Objects into an array using push method
I want to add an object when I click Add to Cart Button. I want to add cartItems when clicked and want all the cart items into the cart one by one when I click addToCart button. But I don't want to use spread operator for that. I did try push method, but now I am tired of trying. Please let me know what I am doing wrong. I am new in programming.

CART REDUCER -

```<code>import { actionTypes } from "../../types/actionTypes";

const cartiState = {
  addToCart: [],
};

export const cartReducer = (state = cartiState, action) => {
  switch (action.type) {
    case actionTypes.ADD_TO_CART:
      // const singleObject = action.payload; //{...} getting single object on addtocart click
      let x = state.addToCart.push(action.payload);
      return {
        ...state,
        // addToCart: [...state.addToCart, { ...singleObject }],
        addToCart: x,
      };
    default:
      return state;
  }
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to add an object when I click Add to Cart Button. I want to add cartItems when clicked and want all the cart items into the cart one by one when I click addToCart button. But I don't want to use spread operator for that. I did try push method, but now I am tired of trying. Please let me know what I am doing wrong. I am new in programming.

CART REDUCER -

import { actionTypes } from "../../types/actionTypes";

const cartiState = {
  addToCart: [],
};

export const cartReducer = (state = cartiState, action) => {
  switch (action.type) {
    case actionTypes.ADD_TO_CART:
      // const singleObject = action.payload; //{...} getting single object on addtocart click
      let x = state.addToCart.push(action.payload);
      return {
        ...state,
        // addToCart: [...state.addToCart, { ...singleObject }],
        addToCart: x,
      };
    default:
      return state;
  }
};


问:
generic list collection c# html implementation
I'm working on a Razor Page and I need to implemtent my CreateDto in the HTML side.

I have already done it with a Enum class but now with the gernic list I don't know how.

```<code>            <div class="form-group">
                <label asp-for="Crt.Job" class="control-label"></label>
                <select asp-for="Crt.Job"
                        class="form-control"
                        asp-items="Html.GetEnumSelectList<Jobtitler>()">
                    <option>Select type ...</option>
                </select>
                <span asp-validation-for="Crt.Job" class="text-danger"></span>
            </div>
</code>```

the line " Html.GetEnumSlectList() " is where I tried to implement
my prop = public list from the class called dto

```<code>            <div class="form-group">
                <label asp-for="Crt.Job" class="control-label"></label>
                <select asp-for="Crt.Job"
                             class="form-control"
        `I TRIED THIS`              asp-items="Html.GetEnumSelectList<Projekt>()">
                    <option>Select type ...</option>
                </select>
                <span asp-validation-for="Crt.Job" class="text-danger"></span>
            </div>
</code>```
```<code>BUT THAT WILL NOT WORK
</code>```

Body:
I'm working on a Razor Page and I need to implemtent my CreateDto in the HTML side.

I have already done it with a Enum class but now with the gernic list I don't know how.

                <select asp-for="Crt.Job"
                        class="form-control"
                        asp-items="Html.GetEnumSelectList<Jobtitler>()">
                    <option>Select type ...</option>
                </select>

the line " Html.GetEnumSlectList() " is where I tried to implement
my prop = public list from the class called dto

                <select asp-for="Crt.Job"
                             class="form-control"
        `I TRIED THIS`              asp-items="Html.GetEnumSelectList<Projekt>()">
                    <option>Select type ...</option>
                </select>

BUT THAT WILL NOT WORK


问:
How do perform a graph query and join?
I apologize for the title, I don't exactly know how to word it. But essentially, this is a graph-type query but I know RavenDB's graph functionality will be going away so this probably needs to be solved with Javascript.

Here is the scenario:

I have a bunch of documents of different types, call them A, B, C, D. Each of these particular types of documents have some common properties. The one that I'm interested in right now is "Owner". The owner field is an ID which points to one of two other document types; it can be a Group or a User.

The Group document has a 'Members' field which contains an ID which either points to a User or another Group. Something like this

It's worth noting that the documents in play have custom IDs that begin with their entity type. For example Users and Groups begin with user: and group: respectively. Example IDs look like this: user:john@castleblack.com or group:the-nights-watch. This comes into play later.

What I want to be able to do is the following type of query:
"Given that I have either a group id or a user id, return all documents of type a, b, or c where the group/user id is equal to or is a descendant of the document's owner."

In other words, I need to be able to return all documents that are owned by a particular user or group either explicitly or implicitly through a hierarchy.

I've considered solving this a couple different ways with no luck. Here are the two approaches I've tried:

Using a function within a query

With Dejan's help in an email thread, I was able to devise a function that would walk it's way down the ownership graph. What this attempted to do was build a flat array of IDs which represented explicit and implicit owners (i.e. root + descendants):

declare function hierarchy(doc, owners){
    owners = owners || [];
    while(doc != null) {
        let ownerId = id(doc)
        if(ownerId.startsWith('user:')) {
            owners.push(ownerId);
        } else if(ownerId.startsWith('group:')) {
            owners.push(ownerId);
            doc.Members.forEach(m => {
                let owner = load(m, 'Users') || load(m, 'Groups');
                owners = hierarchy(owner, owners);
            });
        }
    }

    return owners;
}
```
<p>I had two issues with this. 1. I don't actually know how to use this in a query lol. I tried to use it as part of the where clause but apparently that's not allowed:</p>
```from @all_docs as d
where hierarchy(d) = 'group:my-group-d'

// error: method hierarchy not allowed
```
<p>Or if I tried anything in the select statement, I got an error that I have exceeded the number of allowed statements.</p>
<h2>As a custom index</h2>
<p>I tried the same idea through a custom index. Essentially, I tried to create an index that would produce an array of IDs using roughly the same function above, so that I could just query where my id was in that array</p>
<pre class="lang-js prettyprint-override"><code>map('@all_docs', function(doc) {

    function hierarchy(n, graph) {
        while(n != null) {
            let ownerId = id(n);
            if(ownerId.startsWith('user:')) {
                graph.push(ownerId);

                return graph;

            } else if(ownerId.startsWith('group:')){
                graph.push(ownerId);
                n.Members.forEach(g => {
                    let owner = load(g, 'Groups') || load(g, 'Users');
                    hierarchy(owner, graph);
                });

                return graph;
            }
        }
    }

    function distinct(value, index, self){ return self.indexOf(value) === index; }

    let ownerGraph = []
    if(doc.Owner) {
        let owner = load(doc.Owner, 'Groups') || load(doc.Owner, 'Users');
        ownerGraph = hierarchy(owner, ownerGraph).filter(distinct);
    }

    return { Owners: ownerGraph };
})

// error: recursion is not allowed by the javascript host
</code>```

The problem with this is that I'm getting an error that recursion is not allowed.

So I'm stumped now. Am I going about this wrong? I feel like this could be a subquery of sorts or a filter by function, but I'm not sure how to do that either. Am I going to have to do this in two separate queries (i.e. two round-trips), one to get the IDs and the other to get the docs?

Update 1

I've revised my attempt at the index to the following and I'm not getting the recursion error anymore, but assuming my queries are correct, it's not returning anything

// Entity/ByOwnerGraph
map('@all_docs', function(doc) {

    function walkGraph(ownerId) {
        let owners = []
        let idsToProcess = [ownerId]
        while(idsToProcess.length > 0) {
            let current = idsToProcess.shift();
            if(current.startsWith('user:')){
                owners.push(current);
            } else if(current.startsWith('group:')) {
                owners.push(current);
                let group = load(current, 'Groups')
                if(!group) { continue; }
                idsToProcess.concat(group.Members)
            }
        }

        return owners;
    }

    let owners = [];
    if(doc.Owner) {
        owners.concat(walkGraph(doc.Owner))
    }

    return { Owners: owners };
})

// query (no results)
from index Entity/ByOwnerGraph as x
where x.Owners = "group:my-group-id"

// alternate query (no results)
from index Entity/ByOwnerGraph as x
where x.Owners ALL IN ("group:my-group-id")

```

I still can't use this approach in a query either as I get the same error that there are too many statements.

Title: How do perform a graph query and join?

Body:
I apologize for the title, I don't exactly know how to word it. But essentially, this is a graph-type query but I know RavenDB's graph functionality will be going away so this probably needs to be solved with Javascript.

Here is the scenario:

I have a bunch of documents of different types, call them A, B, C, D. Each of these particular types of documents have some common properties. The one that I'm interested in right now is "Owner". The owner field is an ID which points to one of two other document types; it can be a Group or a User.

The Group document has a 'Members' field which contains an ID which either points to a User or another Group. Something like this

It's worth noting that the documents in play have custom IDs that begin with their entity type. For example Users and Groups begin with user: and group: respectively. Example IDs look like this: user:john@castleblack.com or group:the-nights-watch. This comes into play later.

What I want to be able to do is the following type of query:
"Given that I have either a group id or a user id, return all documents of type a, b, or c where the group/user id is equal to or is a descendant of the document's owner."

In other words, I need to be able to return all documents that are owned by a particular user or group either explicitly or implicitly through a hierarchy.

I've considered solving this a couple different ways with no luck. Here are the two approaches I've tried:

Using a function within a query

With Dejan's help in an email thread, I was able to devise a function that would walk it's way down the ownership graph. What this attempted to do was build a flat array of IDs which represented explicit and implicit owners (i.e. root + descendants):

declare function hierarchy(doc, owners){
    owners = owners || [];
    while(doc != null) {
        let ownerId = id(doc)
        if(ownerId.startsWith('user:')) {
            owners.push(ownerId);
        } else if(ownerId.startsWith('group:')) {
            owners.push(ownerId);
            doc.Members.forEach(m => {
                let owner = load(m, 'Users') || load(m, 'Groups');
                owners = hierarchy(owner, owners);
            });
        }
    }

    return owners;
}

I had two issues with this. 1. I don't actually know how to use this in a query lol. I tried to use it as part of the where clause but apparently that's not allowed:

from @all_docs as d
where hierarchy(d) = 'group:my-group-d'

// error: method hierarchy not allowed

Or if I tried anything in the select statement, I got an error that I have exceeded the number of allowed statements.

As a custom index

I tried the same idea through a custom index. Essentially, I tried to create an index that would produce an array of IDs using roughly the same function above, so that I could just query where my id was in that array

map('@all_docs', function(doc) {

    function hierarchy(n, graph) {
        while(n != null) {
            let ownerId = id(n);
            if(ownerId.startsWith('user:')) {
                graph.push(ownerId);

                return graph;

            } else if(ownerId.startsWith('group:')){
                graph.push(ownerId);
                n.Members.forEach(g => {
                    let owner = load(g, 'Groups') || load(g, 'Users');
                    hierarchy(owner, graph);
                });

                return graph;
            }
        }
    }

    function distinct(value, index, self){ return self.indexOf(value) === index; }

    let ownerGraph = []
    if(doc.Owner) {
        let owner = load(doc.Owner, 'Groups') || load(doc.Owner, 'Users');
        ownerGraph = hierarchy(owner, ownerGraph).filter(distinct);
    }

    return { Owners: ownerGraph };
})

// error: recursion is not allowed by the javascript host

The problem with this is that I'm getting an error that recursion is not allowed.

So I'm stumped now. Am I going about this wrong? I feel like this could be a subquery of sorts or a filter by function, but I'm not sure how to do that either. Am I going to have to do this in two separate queries (i.e. two round-trips), one to get the IDs and the other to get the docs?

Update 1

I've revised my attempt at the index to the following and I'm not getting the recursion error anymore, but assuming my queries are correct, it's not returning anything

// Entity/ByOwnerGraph
map('@all_docs', function(doc) {

    function walkGraph(ownerId) {
        let owners = []
        let idsToProcess = [ownerId]
        while(idsToProcess.length > 0) {
            let current = idsToProcess.shift();
            if(current.startsWith('user:')){
                owners.push(current);
            } else if(current.startsWith('group:')) {
                owners.push(current);
                let group = load(current, 'Groups')
                if(!group) { continue; }
                idsToProcess.concat(group.Members)
            }
        }

        return owners;
    }

    let owners = [];
    if(doc.Owner) {
        owners.concat(walkGraph(doc.Owner))
    }

    return { Owners: owners };
})

// query (no results)
from index Entity/ByOwnerGraph as x
where x.Owners = "group:my-group-id"

// alternate query (no results)
from index Entity/ByOwnerGraph as x
where x.Owners ALL IN ("group:my-group-id")

I still can't use this approach in a query either as I get the same error that there are too many statements.


问:
Laravel Many To Many Relationships update
I am trying to make Many To Many Relationships with Laravel. but where I'm stuck is, when post is updated, how do I update the pivot table?

posts migration

```<code>Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('body');
            $table->timestamps();
        });
</code>```

languages migration

```<code>Schema::create('languages', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
</code>```

language_post migration

```<code>Schema::create('language_post', function (Blueprint $table) {
            $table->id();
            $table->foreignId('language_id')->constrained();
            $table->foreignId('post_id')->constrained();
            $table->timestamps();
            $table->boolean('active')->default(false);
        });

</code>```

Language Model

```<code>public function posts()
    {
        return $this->belongsToMany(Post::class)
            ->withTimestamps();
    }

</code>```

Post Model

```<code> public function languages()
    {
        return $this->belongsToMany(Language::class)
            ->withTimestamps()
            ->withPivot('active');
    }
</code>```

PostController

```<code>class PostController extends Controller
{
    public function index()
    {
        return Post::with('languages')->get();
    }

    public function store(Request $request)
    {
        $post = new Post();
        $post->title = $request->title;
        $post->body = $request->body;
        $post->save();
        $post->languages()->attach(explode(',', $request->language));
    }

    public function show($id)
    {
        $post = Post::find($id);
        $post->languages;
        return $post;
    }

    public function update(Request $request, $id)
    {

    }

    public function destroy($id)
    {
        $postDelete = Post::find($id);
        $postDelete->languages()->detach();
        return Post::destroy($id);
    }
}
</code>```

Body:
I am trying to make Many To Many Relationships with Laravel. but where I'm stuck is, when post is updated, how do I update the pivot table?

posts migration

Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('body');
            $table->timestamps();
        });

languages migration

Schema::create('languages', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });

language_post migration

Schema::create('language_post', function (Blueprint $table) {
            $table->id();
            $table->foreignId('language_id')->constrained();
            $table->foreignId('post_id')->constrained();
            $table->timestamps();
            $table->boolean('active')->default(false);
        });

Language Model

public function posts()
    {
        return $this->belongsToMany(Post::class)
            ->withTimestamps();
    }

Post Model

 public function languages()
    {
        return $this->belongsToMany(Language::class)
            ->withTimestamps()
            ->withPivot('active');
    }

PostController

class PostController extends Controller
{
    public function index()
    {
        return Post::with('languages')->get();
    }

    public function store(Request $request)
    {
        $post = new Post();
        $post->title = $request->title;
        $post->body = $request->body;
        $post->save();
        $post->languages()->attach(explode(',', $request->language));
    }

    public function show($id)
    {
        $post = Post::find($id);
        $post->languages;
        return $post;
    }

    public function update(Request $request, $id)
    {

    }

    public function destroy($id)
    {
        $postDelete = Post::find($id);
        $postDelete->languages()->detach();
        return Post::destroy($id);
    }
}


问:
How to use the Unsplash API?
I'm currently working on a new personal project and it seems that I can't retrieve the images that I want from my profile since I can't authenticate properly.

My code to authenticate is the following:

```<code>var dotenv = require('dotenv');
var unsplash = require('unsplash-api');

dotenv.config()

var clientId = new unsplash({ clientId: process.env.myAccessKey }); //this is required to verify your application's requests
unsplash.init(clientId);

</code>```

The issue that I'm getting is the following:

```<code>
var clientId = new unsplash({ clientId: process.env.myAccessKey }); //this is required to verify your application's requests
               ^
TypeError: unsplash is not a constructor
    at Object.<anonymous> (/Users/aharo5/Desktop/javascript/unsplash_portfolio/main.js:6:16)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
    at node:internal/main/run_main_module:23:47

</code>```

Could some one help me out with this request?

Title: How to use the Unsplash API?

Body:
I'm currently working on a new personal project and it seems that I can't retrieve the images that I want from my profile since I can't authenticate properly.

My code to authenticate is the following:

var dotenv = require('dotenv');
var unsplash = require('unsplash-api');

dotenv.config()

var clientId = new unsplash({ clientId: process.env.myAccessKey }); //this is required to verify your application's requests
unsplash.init(clientId);

The issue that I'm getting is the following:

var clientId = new unsplash({ clientId: process.env.myAccessKey }); //this is required to verify your application's requests
               ^
TypeError: unsplash is not a constructor
    at Object.<anonymous> (/Users/aharo5/Desktop/javascript/unsplash_portfolio/main.js:6:16)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
    at node:internal/main/run_main_module:23:47

Could some one help me out with this request?


问:
AFRAME - Display in-game camera on an entity ()
I've been creating a portal game for VR. I've been trying to figure out how to display a camera in-game as a texture so that I can display the other portal's perspective on the first portal. How do I go about displaying the in-game camera live on an entity's texture?

I have tried looking online numerous times, but could not find anything about it. I have no idea how to achieve this in AFRAME.

(I also rarely use Stack Overflow, so if I did something wrong, sorry!)

Title: AFRAME - Display in-game camera on an entity (<a-plane>)


问:
A way to create history table with Hibernate ddl-auto
I am trying to create a system-versioning (history) table in SQL-server via SpringBoot Hibernate entity, but I would like to make automatic creating via ddl-auto.

Is there a way to make it? all I found is Envers library with @Audited annotation, but it creates a new table not a system-versioning one.


问:
references return by findById() and save() method calls of spring JPA points to same object
I ve a method to first get the instance (here Organization) of the hibernate entity and then update it with some value.

```<code>    public Organization update(Organization organization) throws RecordNotFoundException {

      // verify organization exist or not

      Organization currentOrganization = getById(organization.getId());
      // getById internally calls findById of CrudRepository of JPA

      Organization updatedOrg = getRepository().save(organization);
      // this calls internally save method of CrudRepository of JPA

      return updatedOrg;

    }
</code>```

My query is why currentOrganization and updateOrg references points to the same object in the memory? i checked it by printing hashcodes of both the references.

I ve an createdAt field in organization object. It will automatically populated when first time organization is stored in db. But when i update it using the save() method i want to return the existing value rather than whatever is set the request object.

```<code> public Organization update(Organization organization) throws RecordNotFoundException {

      // verify organization exist or not

      Organization currentOrganization = getById(organization.getId());
      Organization updatedOrg = getRepository().save(organization);
      updatedOrg.setCreatedAt(currentOrganization.getCreatedAt());
      return updatedOrg;

    }
</code>```

but this is not working. After creating updatedOrg object, currentOrganzation is also some how points to the same object which updatedOrg is referencing.

Body:
I ve a method to first get the instance (here Organization) of the hibernate entity and then update it with some value.

    public Organization update(Organization organization) throws RecordNotFoundException {

      // verify organization exist or not

      Organization currentOrganization = getById(organization.getId());
      // getById internally calls findById of CrudRepository of JPA

      Organization updatedOrg = getRepository().save(organization);
      // this calls internally save method of CrudRepository of JPA

      return updatedOrg;

    }

My query is why currentOrganization and updateOrg references points to the same object in the memory? i checked it by printing hashcodes of both the references.

I ve an createdAt field in organization object. It will automatically populated when first time organization is stored in db. But when i update it using the save() method i want to return the existing value rather than whatever is set the request object.

 public Organization update(Organization organization) throws RecordNotFoundException {

      // verify organization exist or not

      Organization currentOrganization = getById(organization.getId());
      Organization updatedOrg = getRepository().save(organization);
      updatedOrg.setCreatedAt(currentOrganization.getCreatedAt());
      return updatedOrg;

    }

but this is not working. After creating updatedOrg object, currentOrganzation is also some how points to the same object which updatedOrg is referencing.


问:
how to implement Application.UserAppDataPath in .net standard 2.0
Currently in our Application is in .net 4.8 and we are using Application.UserAppDataPath to get the path for the application data of a user.

```<code>if (TestManager.Singleton.IsUnitTestActive)
        {   // Unit test is running...
            string appUserPath = Application.UserAppDataPath;
            this.Path = appUserPath.Substring(0, appUserPath.LastIndexOf('\\')) + "\\Config.xml";
        }
</code>```

recently we have migrated the logic into .net Standard 2.0 to make it crossplatform.

is there any way to find the path in .net Standard

Body:
Currently in our Application is in .net 4.8 and we are using Application.UserAppDataPath to get the path for the application data of a user.

if (TestManager.Singleton.IsUnitTestActive)
        {   // Unit test is running...
            string appUserPath = Application.UserAppDataPath;
            this.Path = appUserPath.Substring(0, appUserPath.LastIndexOf('\\')) + "\\Config.xml";
        }

recently we have migrated the logic into .net Standard 2.0 to make it crossplatform.

is there any way to find the path in .net Standard


问:
Adding TMXParser as a library to a CLion project using CMake
My friend & I are trying to build a small game & game-engine using SDL2. We decided to use CLion along with CMake for the compilation & linking procedures. We now want to use the TMXParser but we want to make sure that:

We can use TMXParser as a library in our project and that

If someone grabs our project from, i.e., GitHub, that they too will have all the necessary files.

How can we achieve these goals using CMake?

Our current CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.24)
project(CS454)

# set variables
set(CMAKE_CXX_STANDARD 17)
set(SDL2_INCLUDE_DIR "$ENV{SDL2_INCLUDE_DIR_PATH}") # points to the include dir of SDL
set(SDL2_LIB_DIR "$ENV{SDL2_LIB_DIR_PATH}") # point to the libraries of SDL (x64 for 64bit, x86 for 32bit)
set(ENGINE_SOURCES main.cpp utils/src/JsonParser.cpp utils/include/JsonParser.h Engine/src/App.h Engine/src/entities/Entity.cpp Engine/src/entities/Entity.h Engine/src/game/Game.cpp Engine/src/game/Game.h Engine/src/map/MapManager.cpp Engine/src/map/MapManager.h) #specify source files required by the engine

include_directories(${SDL2_INCLUDE_DIR}) # from the docs: Add the given directories to those the compiler uses to search for include files.
link_directories(${SDL2_LIB_DIR}) # from the docs: Adds the paths in which the linker should search for libraries.

find_package(PkgConfig REQUIRED) #Add the jsoncpp module
pkg_check_modules(JSONCPP jsoncpp)
link_libraries(${JSONCPP_LIBRARIES})

# unit test libs
add_library(ut1 UnitTests/UnitTest1/TileManager.cpp UnitTests/UnitTest1/TileManager.h)
#main render library
add_library(screenElement UnitTests/UnitTest1/ScreenElement.cpp UnitTests/UnitTest1/ScreenElement.h)

# unit test executables
add_executable(unit-test-1 UnitTests/UnitTest1/ReadTextMap.cpp)

# game engine executable
add_executable(CS454 ${ENGINE_SOURCES})

# link unit test lib(s) with executable
target_link_libraries(unit-test-1 ut1 screenElement SDL2)

# engine executable linking
target_link_libraries(${PROJECT_NAME} screenElement SDL2main SDL2 SDL2_image ut1 ${JSONCPP_LIBRARIES})
</code>```

Body:
My friend & I are trying to build a small game & game-engine using SDL2. We decided to use CLion along with CMake for the compilation & linking procedures. We now want to use the TMXParser but we want to make sure that:

We can use TMXParser as a library in our project and that

If someone grabs our project from, i.e., GitHub, that they too will have all the necessary files.

How can we achieve these goals using CMake?

Our current CMakeLists.txt:

cmake_minimum_required(VERSION 3.24)
project(CS454)

# set variables
set(CMAKE_CXX_STANDARD 17)
set(SDL2_INCLUDE_DIR "$ENV{SDL2_INCLUDE_DIR_PATH}") # points to the include dir of SDL
set(SDL2_LIB_DIR "$ENV{SDL2_LIB_DIR_PATH}") # point to the libraries of SDL (x64 for 64bit, x86 for 32bit)
set(ENGINE_SOURCES main.cpp utils/src/JsonParser.cpp utils/include/JsonParser.h Engine/src/App.h Engine/src/entities/Entity.cpp Engine/src/entities/Entity.h Engine/src/game/Game.cpp Engine/src/game/Game.h Engine/src/map/MapManager.cpp Engine/src/map/MapManager.h) #specify source files required by the engine

include_directories(${SDL2_INCLUDE_DIR}) # from the docs: Add the given directories to those the compiler uses to search for include files.
link_directories(${SDL2_LIB_DIR}) # from the docs: Adds the paths in which the linker should search for libraries.

find_package(PkgConfig REQUIRED) #Add the jsoncpp module
pkg_check_modules(JSONCPP jsoncpp)
link_libraries(${JSONCPP_LIBRARIES})

# unit test libs
add_library(ut1 UnitTests/UnitTest1/TileManager.cpp UnitTests/UnitTest1/TileManager.h)
#main render library
add_library(screenElement UnitTests/UnitTest1/ScreenElement.cpp UnitTests/UnitTest1/ScreenElement.h)

# unit test executables
add_executable(unit-test-1 UnitTests/UnitTest1/ReadTextMap.cpp)

# game engine executable
add_executable(CS454 ${ENGINE_SOURCES})

# link unit test lib(s) with executable
target_link_libraries(unit-test-1 ut1 screenElement SDL2)

# engine executable linking
target_link_libraries(${PROJECT_NAME} screenElement SDL2main SDL2 SDL2_image ut1 ${JSONCPP_LIBRARIES})


问:
How do you fix incorrect predicted values ("pred") being used in the plot_model function in R?
I am trying to fix a plot that I generated that has the incorrect predicted values along the y-axis. The predicted values should be "Score," my outcome variable. For some reason, the "id" variable is along the y-axis instead. Everything else is plotted correctly. I checked my model, and I can't see where the issue is coming from. I will post my regression model syntax and plot syntax below. The model is a multivariate regression with two outcomes. "scale" labels each of those two outcomes which are indicated by the Score variable. Both predictors are two-level categorical variables, and there is also an interaction between them.
If anyone has any ideas, I would greatly appreciate it!

```<code>multireg4 <- gls(Score ~ 0 + scale + scale:DrinkStat + scale:ACEHx + scale:DrinkStat:ACEHx,
                  data = R34_Long,
                  na.action = na.omit,
                  weights = varIdent(form = ~ 1 | scale),
                  correlation = corSymm(form = ~ as.numeric(scale) | id))

plot_model(multireg4, type = "pred", terms = c("DrinkStat", "ACEHx", "scale")) + theme_sjplot2()

</code>```

here is an image of the plot

I've tried adding limits to the scale variable in the plot_model code, but the issue is that the wrong predicted values are being pulled. This seems like an automatic function, so I am not exactly sure where to edit the syntax (in the model regression or the plot) in order to get R to use the correct predicted values.

Body:
I am trying to fix a plot that I generated that has the incorrect predicted values along the y-axis. The predicted values should be "Score," my outcome variable. For some reason, the "id" variable is along the y-axis instead. Everything else is plotted correctly. I checked my model, and I can't see where the issue is coming from. I will post my regression model syntax and plot syntax below. The model is a multivariate regression with two outcomes. "scale" labels each of those two outcomes which are indicated by the Score variable. Both predictors are two-level categorical variables, and there is also an interaction between them.
If anyone has any ideas, I would greatly appreciate it!

multireg4 <- gls(Score ~ 0 + scale + scale:DrinkStat + scale:ACEHx + scale:DrinkStat:ACEHx,
                  data = R34_Long,
                  na.action = na.omit,
                  weights = varIdent(form = ~ 1 | scale),
                  correlation = corSymm(form = ~ as.numeric(scale) | id))

plot_model(multireg4, type = "pred", terms = c("DrinkStat", "ACEHx", "scale")) + theme_sjplot2()

here is an image of the plot

I've tried adding limits to the scale variable in the plot_model code, but the issue is that the wrong predicted values are being pulled. This seems like an automatic function, so I am not exactly sure where to edit the syntax (in the model regression or the plot) in order to get R to use the correct predicted values.


问:
Is there a way to make intellij debugger not step into every recursive call?
I am trying to debug recursive functions and it automatically steps into every recursive call. Why would it ever do that when it has a step into button and it doesn't do that with other function calls? I know you can see the call stack and manually revert back, but that is very time consuming and easy to mess up. Is there a way to make it just not decide to automatically step into recursive calls that I haven't told it to step into?</p>


问:
PyInstaller project using matplotlib requires TkAgg fat binary, where can I get it?
I have a Python project is based on matplotlib. I use PyInstaller to build executables on my Intel Mac that should eventually run on both Intel and Apple Macs. This fails, because the binary for TkAgg is Intel-only.

```<code>(progress_simulator) joerg@Jorgs-MBP progress_simulator % pyinstaller --windowed --onefile --target-arch universal2 --collect-all tkinterweb ProgressDetourSim.py
84 INFO: PyInstaller: 5.7.0
84 INFO: Python: 3.11.1
95 INFO: Platform: macOS-13.0.1-x86_64-i386-64bit
96 INFO: wrote /Users/joerg/progress_simulator/ProgressDetourSim.spec
99 INFO: UPX is not available.
353 INFO: Determining a mapping of distributions to packages...
1207 WARNING: Unable to find package for requirement pillow from package tkinterweb.
1207 INFO: Packages required by tkinterweb:
[]
1207 INFO: Extending PYTHONPATH with paths
['/Users/joerg/progress_simulator']
1437 INFO: checking Analysis
1465 INFO: Appending 'binaries' from .spec
1465 INFO: Appending 'datas' from .spec
1467 INFO: checking PYZ
1475 INFO: EXE target arch: universal2
1475 INFO: Code signing identity: None
1476 INFO: checking PKG
1482 INFO: Building because toc changed
1482 INFO: Building PKG (CArchive) ProgressDetourSim.pkg
Traceback (most recent call last):
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/bin/pyinstaller", line 8, in <module>
    sys.exit(_console_script_run())
             ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/__main__.py", line 194, in _console_script_run
    run()
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/__main__.py", line 180, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/__main__.py", line 61, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/build_main.py", line 971, in main
    build(specfile, distpath, workpath, clean_build)
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/build_main.py", line 893, in build
    exec(code, spec_namespace)
  File "/Users/joerg/progress_simulator/ProgressDetourSim.spec", line 31, in <module>
    exe = EXE(
          ^^^^
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/api.py", line 534, in __init__
    self.pkg = PKG(
               ^^^^
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/api.py", line 216, in __init__
    self.__postinit__()
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/datastruct.py", line 173, in __postinit__
    self.assemble()
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/api.py", line 270, in assemble
    fnm = checkCache(
          ^^^^^^^^^^^
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/utils.py", line 373, in checkCache
    osxutils.binary_to_target_arch(cachedfile, target_arch, display_name=fnm)
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/utils/osx.py", line 312, in binary_to_target_arch
    raise IncompatibleBinaryArchError(f"{display_name} is not a fat binary!")
PyInstaller.utils.osx.IncompatibleBinaryArchError: /Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/matplotlib/backends/_tkagg.cpython-311-darwin.so is not a fat binary!
(progress_simulator) joerg@Jorgs-MBP progress_simulator %

</code>```

How can I resolve this, where can I get a universal2 version of TkAgg?

Alternatively, what would be the best way to obtain a Mac app that plots graphs similar to how matplotlib works and that runs on both Intel and Apple silicon?

Body:
I have a Python project is based on matplotlib. I use PyInstaller to build executables on my Intel Mac that should eventually run on both Intel and Apple Macs. This fails, because the binary for TkAgg is Intel-only.

(progress_simulator) joerg@Jorgs-MBP progress_simulator % pyinstaller --windowed --onefile --target-arch universal2 --collect-all tkinterweb ProgressDetourSim.py
84 INFO: PyInstaller: 5.7.0
84 INFO: Python: 3.11.1
95 INFO: Platform: macOS-13.0.1-x86_64-i386-64bit
96 INFO: wrote /Users/joerg/progress_simulator/ProgressDetourSim.spec
99 INFO: UPX is not available.
353 INFO: Determining a mapping of distributions to packages...
1207 WARNING: Unable to find package for requirement pillow from package tkinterweb.
1207 INFO: Packages required by tkinterweb:
[]
1207 INFO: Extending PYTHONPATH with paths
['/Users/joerg/progress_simulator']
1437 INFO: checking Analysis
1465 INFO: Appending 'binaries' from .spec
1465 INFO: Appending 'datas' from .spec
1467 INFO: checking PYZ
1475 INFO: EXE target arch: universal2
1475 INFO: Code signing identity: None
1476 INFO: checking PKG
1482 INFO: Building because toc changed
1482 INFO: Building PKG (CArchive) ProgressDetourSim.pkg
Traceback (most recent call last):
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/bin/pyinstaller", line 8, in <module>
    sys.exit(_console_script_run())
             ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/__main__.py", line 194, in _console_script_run
    run()
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/__main__.py", line 180, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/__main__.py", line 61, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/build_main.py", line 971, in main
    build(specfile, distpath, workpath, clean_build)
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/build_main.py", line 893, in build
    exec(code, spec_namespace)
  File "/Users/joerg/progress_simulator/ProgressDetourSim.spec", line 31, in <module>
    exe = EXE(
          ^^^^
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/api.py", line 534, in __init__
    self.pkg = PKG(
               ^^^^
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/api.py", line 216, in __init__
    self.__postinit__()
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/datastruct.py", line 173, in __postinit__
    self.assemble()
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/api.py", line 270, in assemble
    fnm = checkCache(
          ^^^^^^^^^^^
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/building/utils.py", line 373, in checkCache
    osxutils.binary_to_target_arch(cachedfile, target_arch, display_name=fnm)
  File "/Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/PyInstaller/utils/osx.py", line 312, in binary_to_target_arch
    raise IncompatibleBinaryArchError(f"{display_name} is not a fat binary!")
PyInstaller.utils.osx.IncompatibleBinaryArchError: /Users/joerg/.local/share/virtualenvs/progress_simulator-bvQB0wNI/lib/python3.11/site-packages/matplotlib/backends/_tkagg.cpython-311-darwin.so is not a fat binary!
(progress_simulator) joerg@Jorgs-MBP progress_simulator %

How can I resolve this, where can I get a universal2 version of TkAgg?

Alternatively, what would be the best way to obtain a Mac app that plots graphs similar to how matplotlib works and that runs on both Intel and Apple silicon?


问:
Errors with mongo-community6 on mac cannot start
I am having these issues with mongo startup on mac.  There are two.  One when I start without sudo and one with sudo.  Setup with brew.

brew install mongodb-community@6.0

Tried: sudo brew services restart mongodb-community

Without sudo, permission denied error.

{"t":{"$date":"2022-12-10T14:01:32.755-05:00"},"s":"E",  "c":"NETWORK",  "id":23024,   "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Permission denied"}}

With sudo

```<code>{"t":{"$date":"2022-12-10T13:55:50.382-05:00"},"s":"F",  "c":"CONTROL",  "id":20573,   "ctx":"initandlisten","msg":"Wrong mongod version","attr":{"error":"UPGRADE PROBLEM: Found an invalid featureCompatibilityVersion document (ERROR: Location4926900: Invalid featureCompatibilityVersion document in admin.system.version: { _id: \"featureCompatibilityVersion\", version: \"4.2\" }. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility. :: caused by :: Invalid feature compatibility version value, expected '5.0' or '5.3' or '6.0. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility.). If the current featureCompatibilityVersion is below 5.0, see the documentation on upgrading at https://docs.mongodb.com/master/release-notes/5.0/#upgrade-procedures."}}
{"t":{"$date":"2022-12-10T13:5
</code>```

Body:
I am having these issues with mongo startup on mac.  There are two.  One when I start without sudo and one with sudo.  Setup with brew.

brew install mongodb-community@6.0

Tried: sudo brew services restart mongodb-community

Without sudo, permission denied error.

{"t":{"$date":"2022-12-10T14:01:32.755-05:00"},"s":"E",  "c":"NETWORK",  "id":23024,   "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Permission denied"}}

With sudo

{"t":{"$date":"2022-12-10T13:55:50.382-05:00"},"s":"F",  "c":"CONTROL",  "id":20573,   "ctx":"initandlisten","msg":"Wrong mongod version","attr":{"error":"UPGRADE PROBLEM: Found an invalid featureCompatibilityVersion document (ERROR: Location4926900: Invalid featureCompatibilityVersion document in admin.system.version: { _id: \"featureCompatibilityVersion\", version: \"4.2\" }. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility. :: caused by :: Invalid feature compatibility version value, expected '5.0' or '5.3' or '6.0. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility.). If the current featureCompatibilityVersion is below 5.0, see the documentation on upgrading at https://docs.mongodb.com/master/release-notes/5.0/#upgrade-procedures."}}
{"t":{"$date":"2022-12-10T13:5


问:
Authorization function for R program, trying to use openai package, yet still getting an error
I am trying to use the openai package in R. I have used the Sys.setenv function and filled in the prompt. Although I have entered the API key in the code, this error still comes up:

Error: OpenAI API request failed [401]:

You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://beta.openai.com.

enter image description here

I tried putting bearer API_KEY in quotes and taken the quotes out.


问:
Issue with writing script autosave Roblox Studio
I'm currently learning lua/roblox scripting and whenever I open my project I get a message in my terminal that says "Issue writing script autosave" and whenever I edit my code the message multiplies.
I haven't encountered anything strange happening after that message but im just concerned on what it means and how to get rid of it.

I try searching it up on the roblox studio developer forums but can't find anything, a link to a forum about my problem would be appreciated.


问:
Autocomplete window appearing in wrong place for NSTokenField
I have a layer-backed NSTokenField that is in a NSSplitView. The split is initially collapsed, with the token field hidden. When I reveal the token field, it works properly, except that the autocomplete menu is in the wrong place: instead of being attached to the field, it appears at the bottom left of the window.

It seems like the menu is positioned before the view is in the window, or something like that.

Anyone else seen this, or have a possible workaround?

ContentLicense: CC BY-SA 3.0


问:
Why does python allow Else statements after a while loop?
I was wondering if there were any legit usecases for writing an else statement after a while loop as they are valid in python?

```<code>eat = 0

while eat < 3:
    print(eat)
    eat += 1
else:
    print("done")
</code>```

i cannot think of any usecases but my friend says there is one but doesnt know it

Body:
I was wondering if there were any legit usecases for writing an else statement after a while loop as they are valid in python?

eat = 0

while eat < 3:
    print(eat)
    eat += 1
else:
    print("done")

i cannot think of any usecases but my friend says there is one but doesnt know it


问:
Align the UILabel inside FSCalendar
After added below code its display list of UILabel below FSCalendar dates.
But the label overlap dates inside calendar.

How to align weekly / Monthly FSCalendar Label below dates?

```<code> func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at monthPosition: FSCalendarMonthPosition) {
            let labelMy2 = UILabel(frame: CGRect(x: 10, y:  calendar.rowHeight, width: cell.bounds.width - 20, height: 20))
            labelMy2.font = UIFont.init(font: Font.interRegular, size: 10)
            labelMy2.text = " 00.00 "
        labelMy2.textAlignment = .center
            labelMy2.backgroundColor = UIColor.init(named: ColorPalette.gray100Color)
            labelMy2.textColor = UIColor.init(named: ColorPalette.gray600kColor)
            cell.addSubview(labelMy2)
    }
</code>```

Below Added Image

Title: Align the UILabel inside FSCalendar

Body:
After added below code its display list of UILabel below FSCalendar dates.
But the label overlap dates inside calendar.

How to align weekly / Monthly FSCalendar Label below dates?

 func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at monthPosition: FSCalendarMonthPosition) {
            let labelMy2 = UILabel(frame: CGRect(x: 10, y:  calendar.rowHeight, width: cell.bounds.width - 20, height: 20))
            labelMy2.font = UIFont.init(font: Font.interRegular, size: 10)
            labelMy2.text = " 00.00 "
        labelMy2.textAlignment = .center
            labelMy2.backgroundColor = UIColor.init(named: ColorPalette.gray100Color)
            labelMy2.textColor = UIColor.init(named: ColorPalette.gray600kColor)
            cell.addSubview(labelMy2)
    }

Below Added Image


问:
How to pass partial data to a parent component in react
I have the following Component TBorrowed

```<code>import React, { Fragment, useState} from "react";
import {Link} from 'react-router-dom';
const EditItem = ({ item }) => {
const [name, setName] = useState(item.name)

const saveData = async (e) => {
    e.preventDefault();
        const body = { name}
        await fetch(`http://127.0.0.1:5000/item/edit/${item.id}`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(body)
        })
}

return (
    <Fragment>
        <Link className="link" data-toggle="modal" data-target={`#id${item.id}`} >{item.name}</Link>

        <div className="modal" id={`id${item.id}`}>
            <div className="modal-dialog">
                <div className="modal-content">

                    <div className="modal-header">
                        <h4 className="modal-title">Edit Item</h4>
                    </div>

                    <div className="modal-body">
                        <label>Name</label>
                        <input value={name} onChange={e => { setName(e.target.value) }}  type="text" />

                    </div>

                    <div className="modal-footer">
                        <button onClick={e => { saveData(e) }} type="button" className="btn btn-outline-success ml-auto" data-dismiss="modal">Save</button>

                    </div>

                </div>
            </div>
        </div>
    </Fragment>

)
}
export default EditItem;
</code>```

The above is called in another component, Main as shown below

```<code>import React, {  useState} from 'react';
import TBorrowed from './TBorrowed';

const Main = () => {
    const [items, setItems] = useState([]);
    ...MANY ITEMS SKIPPED...

    return (

    <table className="layout">
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Code</th>
            </tr>
            </thead>
            <tbody>
                {
                    items.map((item, index) => (
                        <tr key={item.id}>
                            <td>{index + 1}</td>
                            <td>{item.name}</td>
                            <td>{<TBorrowed item={item} />}</td>
                        </tr>
                    ))
                }
            </tbody>
        </table>
    )
}
export default Main;
</code>```

The above works well where I am able to see the item code in the Main component's 	 when rendered, which when I click, I am able to edit the particular item in a modal.

My issue is I no longer want to edit an item in a modal but I want it rendered on it's own page for editing.

When I try it without a data-toggle = "modal" in the TBorrowed component, I get all the contents of the TBorrowed component displaying in the Main component where the modal is called i.e {<TBorrowed item={item} />}	. All the data in TBorrowed is shown in that 	 instead of just the item.code as it was showing while using the modal
My code has some parts missing so it can fit here.
Please assist, and if there's more information required I'll provide it.

Body:
I have the following Component TBorrowed

import React, { Fragment, useState} from "react";
import {Link} from 'react-router-dom';
const EditItem = ({ item }) => {
const [name, setName] = useState(item.name)

const saveData = async (e) => {
    e.preventDefault();
        const body = { name}
        await fetch(`http://127.0.0.1:5000/item/edit/${item.id}`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(body)
        })
}

return (
    <Fragment>
        <Link className="link" data-toggle="modal" data-target={`#id${item.id}`} >{item.name}</Link>

        <div className="modal" id={`id${item.id}`}>

Edit Item

                        Name
                        <input value={name} onChange={e => { setName(e.target.value) }}  type="text" />

                        <button onClick={e => { saveData(e) }} type="button" className="btn btn-outline-success ml-auto" data-dismiss="modal">Save</button>

    </Fragment>

)
}
export default EditItem;

The above is called in another component, Main as shown below

import React, {  useState} from 'react';
import TBorrowed from './TBorrowed';

const Main = () => {
    const [items, setItems] = useState([]);
    ...MANY ITEMS SKIPPED...

    return (

                #
                Name
                Code

                {
                    items.map((item, index) => (

                            {index + 1}
                            {item.name}
                            {<TBorrowed item={item} />}

                    ))
                }

    )
}
export default Main;

The above works well where I am able to see the item code in the Main component's 	 when rendered, which when I click, I am able to edit the particular item in a modal.

My issue is I no longer want to edit an item in a modal but I want it rendered on it's own page for editing.

When I try it without a data-toggle = "modal" in the TBorrowed component, I get all the contents of the TBorrowed component displaying in the Main component where the modal is called i.e {<TBorrowed item={item} />}	. All the data in TBorrowed is shown in that 	 instead of just the item.code as it was showing while using the modal
My code has some parts missing so it can fit here.
Please assist, and if there's more information required I'll provide it.


问:
BulkIndexError while using elasticsearch with Python
I am using the following code to load some data on elasticsearch in a Python module:

```<code>def loadNewsDataToElasticsearch():
    if not es:
        print('Elasticsearch server not accessible.')

    #Delete all previous data
    print('Clearing old data from Elasticsearch server.')
    indices = ['articles']
    if es.indices.exists(index='articles'):
        es.delete_by_query(index=indices, body={"query": {"match_all": {}}})

    print('Loading new data from csv file to dataframe.')
    df = pd.read_csv(directory+"elasticsearch/dataset/newsDataSmall.csv",index_col=0)
    dataset = {'title': df['title'], 'link': df['link'], 'date': df.index}

    # Elasticsearch bulk buffer
    buffer = []
    rows = 0

    #Testing
    #print(dataset['title'][0])

    print('Inserting new data to Elasticsearch.')
    for title, link, date in zip(dataset['title'],dataset['link'],dataset['date']):
      # Article record
      article = {"_id": rows, "_index": "articles", "title": title, "link": link, "date": date}
      # Buffer article
      buffer.append(article)
      # Increment number of articles processed
      rows += 1
      # Bulk load every 1000 records
      if rows % 1000 == 0:
        helpers.bulk(es, buffer)
        buffer = []
        print("Inserted {} articles".format(rows), end="\r")

    if buffer:
        helpers.bulk(es, buffer)

    print("Total articles inserted: {}".format(rows))
    #return(es)
</code>```

The above code runs perfectly fine when I use it on Windows OS in Anaconda. However, when I am running the same code on Linux server, I get the following error:

loadNewsDataToElasticsearch()
Clearing old data from Elasticsearch server.
Loading new data from csv file to dataframe.
Inserting new data to Elasticsearch.
Traceback (most recent call last):
File "", line 1, in
File "/home/priyanka/final5-refined-pyc3.9.15/nlpfnews/semanticSearch.py", line 145, in loadNewsDataToElasticsearch
helpers.bulk(es, buffer)
File "/home/priyanka/miniconda3/lib/python3.9/site-packages/elasticsearch/helpers/actions.py", line 524, in bulk
for ok, item in streaming_bulk(
File "/home/priyanka/miniconda3/lib/python3.9/site-packages/elasticsearch/helpers/actions.py", line 438, in streaming_bulk
for data, (ok, info) in zip(
File "/home/priyanka/miniconda3/lib/python3.9/site-packages/elasticsearch/helpers/actions.py", line 355, in _process_bulk_chunk
yield from gen
File "/home/priyanka/miniconda3/lib/python3.9/site-packages/elasticsearch/helpers/actions.py", line 274, in _process_bulk_chunk_success
raise BulkIndexError(f"{len(errors)} document(s) failed to index.", errors)
elasticsearch.helpers.BulkIndexError: 500 document(s) failed to index.

I am stuck with this for the past few days and have not been able to resolve it. Any help or suggestions will be appreciated.

Body:
I am using the following code to load some data on elasticsearch in a Python module:

def loadNewsDataToElasticsearch():
    if not es:
        print('Elasticsearch server not accessible.')

    #Delete all previous data
    print('Clearing old data from Elasticsearch server.')
    indices = ['articles']
    if es.indices.exists(index='articles'):
        es.delete_by_query(index=indices, body={"query": {"match_all": {}}})

    print('Loading new data from csv file to dataframe.')
    df = pd.read_csv(directory+"elasticsearch/dataset/newsDataSmall.csv",index_col=0)
    dataset = {'title': df['title'], 'link': df['link'], 'date': df.index}

    # Elasticsearch bulk buffer
    buffer = []
    rows = 0

    #Testing
    #print(dataset['title'][0])

    print('Inserting new data to Elasticsearch.')
    for title, link, date in zip(dataset['title'],dataset['link'],dataset['date']):
      # Article record
      article = {"_id": rows, "_index": "articles", "title": title, "link": link, "date": date}
      # Buffer article
      buffer.append(article)
      # Increment number of articles processed
      rows += 1
      # Bulk load every 1000 records
      if rows % 1000 == 0:
        helpers.bulk(es, buffer)
        buffer = []
        print("Inserted {} articles".format(rows), end="\r")

    if buffer:
        helpers.bulk(es, buffer)

    print("Total articles inserted: {}".format(rows))
    #return(es)

The above code runs perfectly fine when I use it on Windows OS in Anaconda. However, when I am running the same code on Linux server, I get the following error:

loadNewsDataToElasticsearch()
Clearing old data from Elasticsearch server.
Loading new data from csv file to dataframe.
Inserting new data to Elasticsearch.
Traceback (most recent call last):
File "", line 1, in
File "/home/priyanka/final5-refined-pyc3.9.15/nlpfnews/semanticSearch.py", line 145, in loadNewsDataToElasticsearch
helpers.bulk(es, buffer)
File "/home/priyanka/miniconda3/lib/python3.9/site-packages/elasticsearch/helpers/actions.py", line 524, in bulk
for ok, item in streaming_bulk(
File "/home/priyanka/miniconda3/lib/python3.9/site-packages/elasticsearch/helpers/actions.py", line 438, in streaming_bulk
for data, (ok, info) in zip(
File "/home/priyanka/miniconda3/lib/python3.9/site-packages/elasticsearch/helpers/actions.py", line 355, in _process_bulk_chunk
yield from gen
File "/home/priyanka/miniconda3/lib/python3.9/site-packages/elasticsearch/helpers/actions.py", line 274, in _process_bulk_chunk_success
raise BulkIndexError(f"{len(errors)} document(s) failed to index.", errors)
elasticsearch.helpers.BulkIndexError: 500 document(s) failed to index.

I am stuck with this for the past few days and have not been able to resolve it. Any help or suggestions will be appreciated.


问:
How to set the Swiper.js speed (transition duration) to zero on mouse Enter?
I made a slider with Swiper.js which automatically scrolls in a loop.

My code: https://codepen.io/BehnamAzg/pen/NWzmBKo

I wanted it to stop scrolling when it's being hovered, so I add this code:

```<code>autoplay: {
    disableOnInteraction: false,
    pauseOnMouseEnter: true
  }
</code>```

This is working fine, but the speed of scrolling is too high
so to adjust that I have to add a speed (transition duration) to it. but by adding this it makes the mouseEnter a delay to make an effect.

For example:
If I set the "speed" to 5000ms, it would take 5 seconds till the slider stops scrolling when it's hovered.

I don't want this "speed attribute" effects my hovering, I want it to immediately stop the scrolling.

For solving this, I tried to add a delay instead of speed but it will remove the smoothness of scrolling.

I tried to set the transition duration to zero while being hovered with CSS, but that also didn't work:

```<code>.swiper:hover > .swiper-wrapper {
  transition-duration: 0 !important;
}
</code>```

I also tried to add a swiper.setProgress(progress, speed) to it and set the speed to zero, it did work but it will mess up the progress of the slider:

```<code>$(".swiper").each(function(elem, target){
  var test = target.swiper;
  $(this).hover(function() {
      test.setProgress(0, 0);
  }, function() {
      test.setProgress(0, 5000);
  });
});
</code>```

I don't know what to do anymore, any suggestions?!

Body:
I made a slider with Swiper.js which automatically scrolls in a loop.

My code: https://codepen.io/BehnamAzg/pen/NWzmBKo

I wanted it to stop scrolling when it's being hovered, so I add this code:

autoplay: {
    disableOnInteraction: false,
    pauseOnMouseEnter: true
  }

This is working fine, but the speed of scrolling is too high
so to adjust that I have to add a speed (transition duration) to it. but by adding this it makes the mouseEnter a delay to make an effect.

For example:
If I set the "speed" to 5000ms, it would take 5 seconds till the slider stops scrolling when it's hovered.

I don't want this "speed attribute" effects my hovering, I want it to immediately stop the scrolling.

For solving this, I tried to add a delay instead of speed but it will remove the smoothness of scrolling.

I tried to set the transition duration to zero while being hovered with CSS, but that also didn't work:

.swiper:hover > .swiper-wrapper {
  transition-duration: 0 !important;
}

I also tried to add a swiper.setProgress(progress, speed) to it and set the speed to zero, it did work but it will mess up the progress of the slider:

$(".swiper").each(function(elem, target){
  var test = target.swiper;
  $(this).hover(function() {
      test.setProgress(0, 0);
  }, function() {
      test.setProgress(0, 5000);
  });
});

I don't know what to do anymore, any suggestions?!


问:
Unnormalizing in Knuth's Algorithm D
I'm trying to implement Algorithm D from Knuth's "The Art of Computer Programming, Vol 2" in Rust although I'm having trouble understating how to implement the very last step of unnormalizing. My natural numbers are a class where each number is a vector of u64, in base u64::MAX. Addition, subtraction, and multiplication have been implemented.

Knuth's Algorithm D is a euclidean division algorithm which takes two natural numbers x and y and returns (q,r) where q = x / y (integer division) and r = x % y, the remainder. The algorithm depends on an approximation method which only works if the first digit of y is greater than b/2, where b is the base you're representing the numbers in. Since not all numbers are of this form, it uses a "normalizing trick", for example (if we were in base 10) instead of doing 200 / 23, we calculate a normalizer d and do (200 * d) / (23 * d) so that 23 * d has a first digit greater than b/2.

So when we use the approximation method, we end up with the desired q but the remainder is multiplied by a factor of d. So the last step is to divide r by d so that we can get the q and r we want. My problem is, I'm a bit confused at how we're suppose to do this last step as it requires division and the method it's part of is trying to implement division.

(Maybe helpful?):
The way that d is calculated is just by taking the integer floor of b-1 divided by the first digit of y. However, Knuth suggests that it's possible to make d a power of 2, as long as d * the first digit of y is greater than b / 2. I think he makes this suggestion so that instead of dividing, we can just do a binary shift for this last step. Although I don't think I can do that given that my numbers are represented as vectors of u64 values, instead of binary.

Any suggestions?

Title: Unnormalizing in Knuth's Algorithm D


问:
svgr/webpack Not Working With Webpack 5 and SingleSpa
I been struggling with this for a week, I been reading another Stackoverflow questions and the SVGR/WEBPACK documentation but I'm unable to solve this.

I wanted to upgrade an old react single-spa application but it had a lot of conflicting dependencies so I simply went and created a new one using the Single Spa Playground web application, everything works great but I can't get my SVG'S as React Components with SVGR/WEBPACK.

The error:

webpack.config.js

```<code>const webpackMerge = require("webpack-merge").merge;
const singleSpaDefaults = require("webpack-config-single-spa-react-ts");

module.exports = (webpackConfigEnv, argv) => {
  const defaultConfig = singleSpaDefaults({
    orgName: "testorg",
    projectName: "testproj",
    webpackConfigEnv,
    argv,
  });

  return webpackMerge(defaultConfig, {
    module: {
      rules: [
        {
          test: /\.s[ac]ss$/i,
          use: ["style-loader", "css-loader", "sass-loader"],
        },
        {
          test: /\.svg$/,
          use: ["@svgr/webpack"],
        },
      ],
    },
  });
};
</code>```

How I'm importing the svg

```<code>import TestImg from "../../assets/icons/testimage.svg";
</code>```

How I'm using the SVG

```<code><TestImg />
</code>```

declarations.d.ts

I'm not entirely sure how does this works but I also removed this and it's the same.

```<code>declare module "*.svg" {
  const content: React.FC<React.SVGAttributes<SVGElement>>;
  export default content;
}

</code>```

package.json

```<code>{
  "name": "@testorg/testproj",
  "scripts": {
    "start": "webpack serve",
    "start:standalone": "webpack serve --env standalone",
    "build": "concurrently npm:build:*",
    "build:webpack": "webpack --mode=production",
    "analyze": "webpack --mode=production --env analyze",
    "lint": "eslint src --ext js,ts,tsx",
    "format": "prettier --write .",
    "check-format": "prettier --check .",
    "test": "cross-env BABEL_ENV=test jest",
    "watch-tests": "cross-env BABEL_ENV=test jest --watch",
    "prepare": "husky install",
    "coverage": "cross-env BABEL_ENV=test jest --coverage",
    "build:types": "tsc"
  },
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/eslint-parser": "^7.15.0",
    "@babel/plugin-transform-runtime": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "@babel/preset-react": "^7.14.5",
    "@babel/preset-typescript": "^7.15.0",
    "@babel/runtime": "^7.15.3",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^12.0.0",
    "@types/testing-library__jest-dom": "^5.14.1",
    "babel-jest": "^27.0.6",
    "concurrently": "^6.2.1",
    "cross-env": "^7.0.3",
    "eslint": "^7.32.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-config-ts-react-important-stuff": "^3.0.0",
    "eslint-plugin-prettier": "^3.4.1",
    "husky": "^7.0.2",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.0.6",
    "jest-cli": "^27.0.6",
    "prettier": "^2.3.2",
    "pretty-quick": "^3.1.1",
    "sass": "^1.56.2",
    "sass-loader": "^13.2.0",
    "ts-config-single-spa": "^3.0.0",
    "typescript": "^4.3.5",
    "webpack": "^5.75.0",
    "webpack-cli": "^4.8.0",
    "webpack-config-single-spa-react": "^4.0.0",
    "webpack-config-single-spa-react-ts": "^4.0.0",
    "webpack-config-single-spa-ts": "^4.0.0",
    "webpack-dev-server": "^4.0.0",
    "webpack-merge": "^5.8.0"
  },
  "dependencies": {
    "@datepicker-react/hooks": "^2.8.4",
    "@svgr/webpack": "^6.5.1",
    "@types/jest": "^27.0.1",
    "@types/react": "^17.0.19",
    "@types/react-dom": "^17.0.9",
    "@types/systemjs": "^6.1.1",
    "@types/webpack-env": "^1.16.2",
    "date-fns": "^2.29.3",
    "prop-types": "^15.8.1",
    "react": "^17.0.2",
    "react-datepicker": "^4.8.0",
    "react-dom": "^17.0.2",
    "react-modal": "^3.16.1",
    "react-number-format": "^5.1.2",
    "react-toastify": "^6.2.0",
    "single-spa": "^5.9.3",
    "single-spa-react": "^4.3.1",
    "styled-components": "^5.3.6"
  },
  "types": "dist/testorg-testproj.d.ts"
}
</code>```

The only way it works

The only way I got it working is uninstalling @svgr/webpack and using my imported svg inside of an img tag, as a source.

```<code><img src={TestImg} alt='' width='200' height='200' />
</code>```

But is not what I want, I need to be able modify the svg fill by props and that's why I need it as a React Component.

Also, I have a LOT of icons and logos in this project, so manually creating a React Component in my project for each image/icon it's not the solution I'm looking for.

Additional information 1

I put a console log for the TestImg and it shows an url, clearly it's not importing it as a component

If I go to the url this is what it shows:

Additional information 2

```<code>import { ReactComponent as TestImg } from "../../assets/icons/testimage.svg"
</code>```

Doesn't work either, it says:

Can't import the named export 'ReactComponent' (imported as 'TestImg') from default-exporting module (only default export is available)

Body:
I been struggling with this for a week, I been reading another Stackoverflow questions and the SVGR/WEBPACK documentation but I'm unable to solve this.

I wanted to upgrade an old react single-spa application but it had a lot of conflicting dependencies so I simply went and created a new one using the Single Spa Playground web application, everything works great but I can't get my SVG'S as React Components with SVGR/WEBPACK.

The error:

webpack.config.js

const webpackMerge = require("webpack-merge").merge;
const singleSpaDefaults = require("webpack-config-single-spa-react-ts");

module.exports = (webpackConfigEnv, argv) => {
  const defaultConfig = singleSpaDefaults({
    orgName: "testorg",
    projectName: "testproj",
    webpackConfigEnv,
    argv,
  });

  return webpackMerge(defaultConfig, {
    module: {
      rules: [
        {
          test: /\.s[ac]ss$/i,
          use: ["style-loader", "css-loader", "sass-loader"],
        },
        {
          test: /\.svg$/,
          use: ["@svgr/webpack"],
        },
      ],
    },
  });
};

How I'm importing the svg

import TestImg from "../../assets/icons/testimage.svg";

How I'm using the SVG

<TestImg />

declarations.d.ts

I'm not entirely sure how does this works but I also removed this and it's the same.

declare module "*.svg" {
  const content: React.FC<React.SVGAttributes<SVGElement>>;
  export default content;
}

package.json

{
  "name": "@testorg/testproj",
  "scripts": {
    "start": "webpack serve",
    "start:standalone": "webpack serve --env standalone",
    "build": "concurrently npm:build:*",
    "build:webpack": "webpack --mode=production",
    "analyze": "webpack --mode=production --env analyze",
    "lint": "eslint src --ext js,ts,tsx",
    "format": "prettier --write .",
    "check-format": "prettier --check .",
    "test": "cross-env BABEL_ENV=test jest",
    "watch-tests": "cross-env BABEL_ENV=test jest --watch",
    "prepare": "husky install",
    "coverage": "cross-env BABEL_ENV=test jest --coverage",
    "build:types": "tsc"
  },
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/eslint-parser": "^7.15.0",
    "@babel/plugin-transform-runtime": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "@babel/preset-react": "^7.14.5",
    "@babel/preset-typescript": "^7.15.0",
    "@babel/runtime": "^7.15.3",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^12.0.0",
    "@types/testing-library__jest-dom": "^5.14.1",
    "babel-jest": "^27.0.6",
    "concurrently": "^6.2.1",
    "cross-env": "^7.0.3",
    "eslint": "^7.32.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-config-ts-react-important-stuff": "^3.0.0",
    "eslint-plugin-prettier": "^3.4.1",
    "husky": "^7.0.2",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.0.6",
    "jest-cli": "^27.0.6",
    "prettier": "^2.3.2",
    "pretty-quick": "^3.1.1",
    "sass": "^1.56.2",
    "sass-loader": "^13.2.0",
    "ts-config-single-spa": "^3.0.0",
    "typescript": "^4.3.5",
    "webpack": "^5.75.0",
    "webpack-cli": "^4.8.0",
    "webpack-config-single-spa-react": "^4.0.0",
    "webpack-config-single-spa-react-ts": "^4.0.0",
    "webpack-config-single-spa-ts": "^4.0.0",
    "webpack-dev-server": "^4.0.0",
    "webpack-merge": "^5.8.0"
  },
  "dependencies": {
    "@datepicker-react/hooks": "^2.8.4",
    "@svgr/webpack": "^6.5.1",
    "@types/jest": "^27.0.1",
    "@types/react": "^17.0.19",
    "@types/react-dom": "^17.0.9",
    "@types/systemjs": "^6.1.1",
    "@types/webpack-env": "^1.16.2",
    "date-fns": "^2.29.3",
    "prop-types": "^15.8.1",
    "react": "^17.0.2",
    "react-datepicker": "^4.8.0",
    "react-dom": "^17.0.2",
    "react-modal": "^3.16.1",
    "react-number-format": "^5.1.2",
    "react-toastify": "^6.2.0",
    "single-spa": "^5.9.3",
    "single-spa-react": "^4.3.1",
    "styled-components": "^5.3.6"
  },
  "types": "dist/testorg-testproj.d.ts"
}

The only way it works

The only way I got it working is uninstalling @svgr/webpack and using my imported svg inside of an img tag, as a source.

But is not what I want, I need to be able modify the svg fill by props and that's why I need it as a React Component.

Also, I have a LOT of icons and logos in this project, so manually creating a React Component in my project for each image/icon it's not the solution I'm looking for.

Additional information 1

I put a console log for the TestImg and it shows an url, clearly it's not importing it as a component

If I go to the url this is what it shows:

Additional information 2

import { ReactComponent as TestImg } from "../../assets/icons/testimage.svg"

Doesn't work either, it says:

Can't import the named export 'ReactComponent' (imported as 'TestImg') from default-exporting module (only default export is available)


问:
Overriding default login page of spring security OAuth2 while using new Authorization Server and PKCE
I'm using React JS as client and my Authorization server uses new OAuth2 with PKCE. The whole flow works but during authentication process, spring security returns me default login page. I have made a change to get the custom React JS login page but the question is, how to handle the submit of the login page from React JS? I am using PKCE so once I submit login page, I need to get the 'code' back in response which I need to further pass (along with verification code) to request JWT Token. Application details are given below,

I got a separate Authorization server OAuth2 using <artifactId>spring-security-oauth2-authorization-server</artifactId>. Authorization server issues JWT upon successful authentication using PKCE. I'm using PKCE because front end is React JS and I do not wish to save client secret at Front end. This is how the flow works (without explaining minute details),

UI calls ${AUTHORIZATION_SERVER_BASE_URL}/oauth2/authorize?response_type=code&client_id=${CLIENT_ID}&scope=openid&redirect_uri=${REDIRECT_URI}&code_challenge=${codeChallenge}&code_challenge_method=S256;

Spring gives back default login page

User enters credentials

Upon successful authentication, spring returns 'code' to the specified 'REDIRECT_URI'

I make Axios POST request passing 'code' and original code_verifier to get JWT Token eg endpoint post(${AUTHORIZATION_SERVER_BASE_URL}/oauth2/token, paramsEncoded, axiosConfig)

AuthorizationServerConfig class is pasted below.

@Configuration
@AllArgsConstructor
public class AuthorizationServerConfig {

```<code>private final CORSCustomizer corsCustomizer;

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
    OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
    corsCustomizer.corsCustomizer(http);
    return http.formLogin().loginPage("http://127.0.0.1:3000/login").and().build();
    //return http.formLogin(Customizer.withDefaults()).build();
}

@Bean
public RegisteredClientRepository registeredClientRepository() {

    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
            .clientId("client")
            .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
            .redirectUri("http://127.0.0.1:3000/authorized")
            .scope(OidcScopes.OPENID)
            .clientSettings(ClientSettings.builder()
                    .requireAuthorizationConsent(true).build())
            .tokenSettings(TokenSettings.builder()
                    .refreshTokenTimeToLive(Duration.ofHours(10))
                    .build())
            .build();

    return new InMemoryRegisteredClientRepository(registeredClient);
}

@Bean
public ProviderSettings providerSettings() {
    return ProviderSettings.builder()
            .issuer("http://auth-server:3001")
            .build();
}

@Bean
public JWKSource<SecurityContext> jwkSource() throws NoSuchAlgorithmException {
    RSAKey rsaKey = JwksKeys.generateRSAKey();
    JWKSet jwkSet = new JWKSet(rsaKey);
    return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}

@Bean
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
    return context -> {
        if (context.getTokenType() == OAuth2TokenType.ACCESS_TOKEN) {
            Authentication principal = context.getPrincipal();
            Set<String> authorities = principal.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toSet());
                    context.getClaims().claim("roles", authorities);
        }
    };
}
</code>```

}

Body:
I'm using React JS as client and my Authorization server uses new OAuth2 with PKCE. The whole flow works but during authentication process, spring security returns me default login page. I have made a change to get the custom React JS login page but the question is, how to handle the submit of the login page from React JS? I am using PKCE so once I submit login page, I need to get the 'code' back in response which I need to further pass (along with verification code) to request JWT Token. Application details are given below,

I got a separate Authorization server OAuth2 using <artifactId>spring-security-oauth2-authorization-server</artifactId>. Authorization server issues JWT upon successful authentication using PKCE. I'm using PKCE because front end is React JS and I do not wish to save client secret at Front end. This is how the flow works (without explaining minute details),

UI calls ${AUTHORIZATION_SERVER_BASE_URL}/oauth2/authorize?response_type=code&client_id=${CLIENT_ID}&scope=openid&redirect_uri=${REDIRECT_URI}&code_challenge=${codeChallenge}&code_challenge_method=S256;

Spring gives back default login page

User enters credentials

Upon successful authentication, spring returns 'code' to the specified 'REDIRECT_URI'

I make Axios POST request passing 'code' and original code_verifier to get JWT Token eg endpoint post(${AUTHORIZATION_SERVER_BASE_URL}/oauth2/token, paramsEncoded, axiosConfig)

AuthorizationServerConfig class is pasted below.

@Configuration
@AllArgsConstructor
public class AuthorizationServerConfig {

private final CORSCustomizer corsCustomizer;

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
    OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
    corsCustomizer.corsCustomizer(http);
    return http.formLogin().loginPage("http://127.0.0.1:3000/login").and().build();
    //return http.formLogin(Customizer.withDefaults()).build();
}

@Bean
public RegisteredClientRepository registeredClientRepository() {

    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
            .clientId("client")
            .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
            .redirectUri("http://127.0.0.1:3000/authorized")
            .scope(OidcScopes.OPENID)
            .clientSettings(ClientSettings.builder()
                    .requireAuthorizationConsent(true).build())
            .tokenSettings(TokenSettings.builder()
                    .refreshTokenTimeToLive(Duration.ofHours(10))
                    .build())
            .build();

    return new InMemoryRegisteredClientRepository(registeredClient);
}

@Bean
public ProviderSettings providerSettings() {
    return ProviderSettings.builder()
            .issuer("http://auth-server:3001")
            .build();
}

@Bean
public JWKSource<SecurityContext> jwkSource() throws NoSuchAlgorithmException {
    RSAKey rsaKey = JwksKeys.generateRSAKey();
    JWKSet jwkSet = new JWKSet(rsaKey);
    return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}

@Bean
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
    return context -> {
        if (context.getTokenType() == OAuth2TokenType.ACCESS_TOKEN) {
            Authentication principal = context.getPrincipal();
            Set<String> authorities = principal.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toSet());
                    context.getClaims().claim("roles", authorities);
        }
    };
}

}


问:
surround planets (points) groups on a map (Canvas)
Hello i am using actually CANVAS Drawing on javascript.

I have a bench of points, which represent planets :
I know how to do : with canvas.context(2d) or P5.Js librairie ...

But do you see the blue or red lines ? it creates "packets" or "zone" or "territory".

I have absoluly no idea how to programm this, which mathematics concepts behind ....someone can push me on the rails ? I don't know how to call this in english too ....

Edit :

I want something similar at the end

Best regards


问:
Uvloop Bad Installation on Docker
This was an issue when I was building my docker image and experienced a failure when trying to install uvloop in my requirements file

when building a docker image using

```<code>python:3.10-alpine
</code>```

and using uvloop version

```<code>uvloop==0.16.0
</code>```

the following will come up

```<code>#0 61.50       /usr/local/lib/python3.10/site-packages/setuptools/command/build_py.py:202: SetuptoolsDeprecationWarning:     Installing 'uvloop.handles' as data is deprecated, please list it in `packages`.
#0 61.50           !!
#0 61.50
#0 61.50
#0 61.50           ############################
#0 61.50           # Package would be ignored #
#0 61.50           ############################
#0 61.50           Python recognizes 'uvloop.handles' as an importable package,
#0 61.50           but it is not listed in the `packages` configuration of setuptools.
#0 61.50
#0 61.50           'uvloop.handles' has been automatically added to the distribution only
#0 61.50           because it may contain data files, but this behavior is likely to change
#0 61.50           in future versions of setuptools (and therefore is considered deprecated).
#0 61.50
#0 61.50           Please make sure that 'uvloop.handles' is included as a package by using
#0 61.50           the `packages` configuration field or the proper discovery methods
#0 61.50           (for example by using `find_namespace_packages(...)`/`find_namespace:`
#0 61.50           instead of `find_packages(...)`/`find:`).
#0 61.50
#0 61.50           You can read more about "package discovery" and "data files" on setuptools
#0 61.50           documentation page.
#0 61.50
#0 61.50
#0 61.50       !!
</code>```

I tried using pip install -U setuptools pip inside of the Dockerfile but that doesn't solve the problem.

The way I resolved this issue was to simply update uvloop to
uvloop==0.17.0

Title: Uvloop Bad Installation on Docker

Body:
This was an issue when I was building my docker image and experienced a failure when trying to install uvloop in my requirements file

when building a docker image using

python:3.10-alpine

and using uvloop version

uvloop==0.16.0

the following will come up

#0 61.50       /usr/local/lib/python3.10/site-packages/setuptools/command/build_py.py:202: SetuptoolsDeprecationWarning:     Installing 'uvloop.handles' as data is deprecated, please list it in `packages`.
#0 61.50           !!
#0 61.50
#0 61.50
#0 61.50           ############################
#0 61.50           # Package would be ignored #
#0 61.50           ############################
#0 61.50           Python recognizes 'uvloop.handles' as an importable package,
#0 61.50           but it is not listed in the `packages` configuration of setuptools.
#0 61.50
#0 61.50           'uvloop.handles' has been automatically added to the distribution only
#0 61.50           because it may contain data files, but this behavior is likely to change
#0 61.50           in future versions of setuptools (and therefore is considered deprecated).
#0 61.50
#0 61.50           Please make sure that 'uvloop.handles' is included as a package by using
#0 61.50           the `packages` configuration field or the proper discovery methods
#0 61.50           (for example by using `find_namespace_packages(...)`/`find_namespace:`
#0 61.50           instead of `find_packages(...)`/`find:`).
#0 61.50
#0 61.50           You can read more about "package discovery" and "data files" on setuptools
#0 61.50           documentation page.
#0 61.50
#0 61.50
#0 61.50       !!

I tried using pip install -U setuptools pip inside of the Dockerfile but that doesn't solve the problem.

The way I resolved this issue was to simply update uvloop to
uvloop==0.17.0