问:
How to define an array[object] parameter correctly in the query string - OAS 3.0
I have a few issues with an array[object] query string definition in OpenAPI 3.0.3:

      parameters:
        - in: query
          name: find
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  minItems: 1
                  maxItems: 1
                  properties:
                    $match:
                      type: object
                      description: To specify conditions to filter the result.
                      properties:
                        name:
                          type: string
                          description: Name of the desired import
```
<p>1 - Even though I have specified that the array can only have 1 item, Swagger UI allows me to add multiple items.</p>
<p>2 - It seems that Swagger UI doesn't encode the content properly or the way I want it. When I call my function in my code, I pass the parameter after stringifying (<code>JSON.stringify()</code>) and it is sent like below in the URL:</p>
```[{%22$match%22:{%22name%22:%22ffghhhjjj%22}}]
```
<p>which is deserialized correctly: <code>[{"$match":{"name":"ffghhhjjj"}}"]</code></p>
<p>But when I see the URL in Swagger UI, it is different:</p>
```https://.../api/contact-service/v1/imports?find=%5B%22%7B%5C%22%24match%5C%22%3A%7B%5C%22name%5C%22%3A%5C%22ffghhhjjj%5C%22%7D%7D%22%5D&limit=2&skip=0
```
<p>This is how the parameter looks like after decoding:</p>
```["{\"$match\":{\"name\":\"ffghhhjjj\"}}"]
```
<p>As you can see, it has sent the array item as string as it should be an object or that the whole value should have been in string that it can be deserialized correctly on the server side.</p>
<p>3 - Another problem is that even though I defined the <code>description</code> for my object's properties, Swagger UI doesn't show it. Defining parameters under <code>components</code> also won't show them as it does for the schemas. Any idea that how I can give the user hints about different properties in my parameter object? I need description to explain different ways that the user can fill up the filter. I.e., "name" can be specified in different formats for filtering:</p>
<pre class="lang-json prettyprint-override"><code>{"name": "item-name"}
</code>```

to just items with the specified name), OR:

"name": {"$in": ["name-1","name-2"]}
```

to get all items that their names matches one of the specified names.

I have tried to place minItems and maxItems in the different locations but didn't work. The current location doesn't give me any errors. Also, I have tried to remove the content and application/json properties but didn't make any changes.

Body:
I have a few issues with an array[object] query string definition in OpenAPI 3.0.3:

      parameters:
        - in: query
          name: find
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  minItems: 1
                  maxItems: 1
                  properties:
                    $match:
                      type: object
                      description: To specify conditions to filter the result.
                      properties:
                        name:
                          type: string
                          description: Name of the desired import

1 - Even though I have specified that the array can only have 1 item, Swagger UI allows me to add multiple items.

2 - It seems that Swagger UI doesn't encode the content properly or the way I want it. When I call my function in my code, I pass the parameter after stringifying (JSON.stringify()) and it is sent like below in the URL:

[{%22$match%22:{%22name%22:%22ffghhhjjj%22}}]

which is deserialized correctly: [{"$match":{"name":"ffghhhjjj"}}"]

But when I see the URL in Swagger UI, it is different:

https://.../api/contact-service/v1/imports?find=%5B%22%7B%5C%22%24match%5C%22%3A%7B%5C%22name%5C%22%3A%5C%22ffghhhjjj%5C%22%7D%7D%22%5D&limit=2&skip=0

This is how the parameter looks like after decoding:

["{\"$match\":{\"name\":\"ffghhhjjj\"}}"]

As you can see, it has sent the array item as string as it should be an object or that the whole value should have been in string that it can be deserialized correctly on the server side.

3 - Another problem is that even though I defined the description for my object's properties, Swagger UI doesn't show it. Defining parameters under components also won't show them as it does for the schemas. Any idea that how I can give the user hints about different properties in my parameter object? I need description to explain different ways that the user can fill up the filter. I.e., "name" can be specified in different formats for filtering:

{"name": "item-name"}

to just items with the specified name), OR:

"name": {"$in": ["name-1","name-2"]}

to get all items that their names matches one of the specified names.

I have tried to place minItems and maxItems in the different locations but didn't work. The current location doesn't give me any errors. Also, I have tried to remove the content and application/json properties but didn't make any changes.


来源: stackexchange

问:
Chrome Management API not pulling installed apps
I am using the Reports API to pull data from Chromebooks. The countChromeVersions method works as intended but countInstalledApps is returning {} instead of the app data. The Chromebooks have apps installed from the Chrome Webstore in addition to the Workspace Core apps. What am I missing? Is there a configuration setting required to pull the app data?

ContentLicense: CC BY-SA 4.0


问:
How to tune number of hidden layers and hidden layer size for a big model? (except random search and grid search)
I intend to find the best value (sub-optimal) of the hidden layer size of a Keras model (TensorFlow).
As the search space is too big, I could not use generic algorithms such as GS and RS. Is there any hyperparameter optimization algorithm suitable for this task?</p>


问:
Nodes cannot be accumulated into a list that need to be evaluated when a certain node is removed
I am a beginner in the programing world and have a small network of nodes. I would like to analyze it and later use it on a more extensive network (supply chain network) as part of my master's thesis. I have uploaded the example network here.

The network image is here

The following network has 5 nodes. If a user types the name of a node, for instance (1) here, then it should be programmed such that firstly, the given node (1) is removed and then one of the neighbors (3 here) is selected and checked against criteria (if G.in_degree(3) >2). If node 3 does not meet the criteria, it should be removed and the next node should be selected (5 here). If node 3 meets the criteria, the loop should stop here and check the next neighboring node (4). I have written the following code, but I have typed the queue manually:

```<code>#input = 1

queue = [1,3,5,4,2]   # I typed this manually, but I would like to make it dynamic,

                        so that the program automatically detects it based on the conditions

for node in queue:

     if G.in_degree(node)<2:

         G.remove_node(node)

          print(str(node) + ' is removed....')

      else:

          print(str(node)+' is and node and exists ')

       if node == queue[-1]:

           print('all nodes are visited')

           nx.draw_networkx(G,with_labels=True)
</code>```

Body:
I am a beginner in the programing world and have a small network of nodes. I would like to analyze it and later use it on a more extensive network (supply chain network) as part of my master's thesis. I have uploaded the example network here.

The network image is here

The following network has 5 nodes. If a user types the name of a node, for instance (1) here, then it should be programmed such that firstly, the given node (1) is removed and then one of the neighbors (3 here) is selected and checked against criteria (if G.in_degree(3) >2). If node 3 does not meet the criteria, it should be removed and the next node should be selected (5 here). If node 3 meets the criteria, the loop should stop here and check the next neighboring node (4). I have written the following code, but I have typed the queue manually:

#input = 1

queue = [1,3,5,4,2]   # I typed this manually, but I would like to make it dynamic,

                        so that the program automatically detects it based on the conditions

for node in queue:

     if G.in_degree(node)<2:

         G.remove_node(node)

          print(str(node) + ' is removed....')

      else:

          print(str(node)+' is and node and exists ')

       if node == queue[-1]:

           print('all nodes are visited')

           nx.draw_networkx(G,with_labels=True)


问:
Rails parse JSON params with leading zeroes in POST body
I'm writing an API that should receive a POST with JSON in it's body. It already works but when the numbers in the JSON have leading zeroes it gives me this error:

```<code>eval error: Error occurred while parsing request parameters
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/parameters.rb:96:in `rescue in parse_formatted_parameters'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/parameters.rb:92:in `parse_formatted_parameters'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/request.rb:390:in `block in POST'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/rack-2.2.4/lib/rack/request.rb:69:in `fetch'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/rack-2.2.4/lib/rack/request.rb:69:in `fetch_header'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/request.rb:389:in `POST'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/parameters.rb:55:in `parameters'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_controller/metal/strong_parameters.rb:1232:in `params'
  (rdbg)//home/danniel/workspace/check-my-cep/app/controllers/api/customers_controller.rb:1:in `create'
</code>```

Here's a request that works:
curl -d '[{"zip": 1001000,"name": "JOSE"}, {"zip": 1001900,"name": "FRANCISCO"}]' http://localhost:3000/api/customers --header "Accept: application/json" --header "Content-Type: application/json"

This one doesn't:
curl -d '[{"zip": 01001000,"name": "JOSE"}, {"zip": 01001900,"name": "FRANCISCO"}]' http://localhost:3000/api/customers --header "Accept: application/json" --header "Content-Type: application/json"

The only difference is the leading zeroes in "zip".

My controller is quite simple:

```<code>class Api::CustomersController < ApplicationController
  before_action :set_customer, only: %i[ destroy ]

  def create
    ...
  end

  def destroy
    @customer.destroy
  end

  private
    def set_customer
      @customer = Customer.find(params[:id])
    end

    def customer_params
      params.permit(_json: [:cep, :name]).require(:_json)
    end
end
</code>```

Update: I can't control the request.

Body:
I'm writing an API that should receive a POST with JSON in it's body. It already works but when the numbers in the JSON have leading zeroes it gives me this error:

eval error: Error occurred while parsing request parameters
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/parameters.rb:96:in `rescue in parse_formatted_parameters'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/parameters.rb:92:in `parse_formatted_parameters'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/request.rb:390:in `block in POST'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/rack-2.2.4/lib/rack/request.rb:69:in `fetch'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/rack-2.2.4/lib/rack/request.rb:69:in `fetch_header'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/request.rb:389:in `POST'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_dispatch/http/parameters.rb:55:in `parameters'
  /home/danniel/.rvm/gems/ruby-2.7.5/gems/actionpack-7.0.4/lib/action_controller/metal/strong_parameters.rb:1232:in `params'
  (rdbg)//home/danniel/workspace/check-my-cep/app/controllers/api/customers_controller.rb:1:in `create'

Here's a request that works:
curl -d '[{"zip": 1001000,"name": "JOSE"}, {"zip": 1001900,"name": "FRANCISCO"}]' http://localhost:3000/api/customers --header "Accept: application/json" --header "Content-Type: application/json"

This one doesn't:
curl -d '[{"zip": 01001000,"name": "JOSE"}, {"zip": 01001900,"name": "FRANCISCO"}]' http://localhost:3000/api/customers --header "Accept: application/json" --header "Content-Type: application/json"

The only difference is the leading zeroes in "zip".

My controller is quite simple:

class Api::CustomersController < ApplicationController
  before_action :set_customer, only: %i[ destroy ]

  def create
    ...
  end

  def destroy
    @customer.destroy
  end

  private
    def set_customer
      @customer = Customer.find(params[:id])
    end

    def customer_params
      params.permit(_json: [:cep, :name]).require(:_json)
    end
end

Update: I can't control the request.


问:
How do you load python lists into JSON Arrays?
I have some data

```<code>types = ['type1', 'type2', 'type3']
names = ['name1', 'name2', 'name3']
</code>```

That I want to load into a JSON as nested string sets that look something like this

```<code>{
    labels{
        type1:name1
        type2:name2
    }
}
</code>```

I've tried a few things including

```<code>labels={types:names}                           (didnt work)
labels=json.loads{types:names}                 (various versions of this)
labels=json.dumps{types:names}                 (various versions of this)
labels=json.loads(json.dumps(types:names))     (I was getting desperate here)
</code>```

I asked a friend, and he said you can only use variables for key values, and not for key names in python's jsonlib. Is there a better way to do this than looping through all types and names?

Body:
I have some data

types = ['type1', 'type2', 'type3']
names = ['name1', 'name2', 'name3']

That I want to load into a JSON as nested string sets that look something like this

{
    labels{
        type1:name1
        type2:name2
    }
}

I've tried a few things including

labels={types:names}                           (didnt work)
labels=json.loads{types:names}                 (various versions of this)
labels=json.dumps{types:names}                 (various versions of this)
labels=json.loads(json.dumps(types:names))     (I was getting desperate here)

I asked a friend, and he said you can only use variables for key values, and not for key names in python's jsonlib. Is there a better way to do this than looping through all types and names?


问:
PySide2 remove QPushButton hover style
i am trying to create a small corner icon on top of an image in Python3.9 using Pyside2 Qt Widgets.
How can i remove the hover style effect?</p>
```<code> # Corner button
    self.corner_btn = QtWidgets.QPushButton(self, flat=True) # create button
    self.corner_btn.setIcon(createIcon("TOP_status_cooked", 50)) # set icon to button
    self.corner_btn.setProperty('transparent', True) # make rest of the button transparent

    # remove hover style - these do not work
    self.corner_btn.setFlat(True)
    self.corner_btn.setFocusPolicy(Qt.NoFocus)
    self.corner_btn .setStyleSheet("QToolButton::hover{background-color: #ffffff;}")
</code>```

Title: PySide2 remove QPushButton hover style

Body:
i am trying to create a small corner icon on top of an image in Python3.9 using Pyside2 Qt Widgets.
How can i remove the hover style effect?

 # Corner button
    self.corner_btn = QtWidgets.QPushButton(self, flat=True) # create button
    self.corner_btn.setIcon(createIcon("TOP_status_cooked", 50)) # set icon to button
    self.corner_btn.setProperty('transparent', True) # make rest of the button transparent

    # remove hover style - these do not work
    self.corner_btn.setFlat(True)
    self.corner_btn.setFocusPolicy(Qt.NoFocus)
    self.corner_btn .setStyleSheet("QToolButton::hover{background-color: #ffffff;}")


问:
Error when using backupSchedules in InnoDBCluster on kubernetes
Faced the problem - when trying to backup MySQL database by schedule, I'm getting an error:

2022-12-08T23:45:15.21758983+02:00 stderr F [2022-12-08 21:45:15,217] kopf.objects         [ERROR   ] Handler 'on_innodbcluster_field_backup_schedules/spec.backupSchedules' failed with an exception. Will retry.

I'm using the following configuration:

```<code>---
apiVersion: mysql.oracle.com/v2
kind: InnoDBCluster
metadata:
  name: mysql
spec:
  tlsUseSelfSigned: true
  secretName: mysql-secret
  instances: 3
  router:
    instances: 1
  baseServerId: 2000
  imagePullPolicy: IfNotPresent
  version: 8.0.30
  datadirVolumeClaimTemplate:
    storageClassName: local-path
  backupSchedules:
    - name: backupschedule
      schedule: "* */5 * * *"
      backupProfileName: backupprofile
      enabled: true
  backupProfiles:
    - name: backupprofile
      dumpInstance:
        storage:
          persistentVolumeClaim:
            claimName: mysqlbackup-pvc
</code>```

Let me know where the problem may be - thanks!

Body:
Faced the problem - when trying to backup MySQL database by schedule, I'm getting an error:

2022-12-08T23:45:15.21758983+02:00 stderr F [2022-12-08 21:45:15,217] kopf.objects         [ERROR   ] Handler 'on_innodbcluster_field_backup_schedules/spec.backupSchedules' failed with an exception. Will retry.

I'm using the following configuration:

---
apiVersion: mysql.oracle.com/v2
kind: InnoDBCluster
metadata:
  name: mysql
spec:
  tlsUseSelfSigned: true
  secretName: mysql-secret
  instances: 3
  router:
    instances: 1
  baseServerId: 2000
  imagePullPolicy: IfNotPresent
  version: 8.0.30
  datadirVolumeClaimTemplate:
    storageClassName: local-path
  backupSchedules:
    - name: backupschedule
      schedule: "* */5 * * *"
      backupProfileName: backupprofile
      enabled: true
  backupProfiles:
    - name: backupprofile
      dumpInstance:
        storage:
          persistentVolumeClaim:
            claimName: mysqlbackup-pvc

Let me know where the problem may be - thanks!


问:
What causes unability to fetch entities in this code?
So i'm developing a REST API for my Spring appplication. I have to store all data in H2 database and i'm trying to find a correct way to do so. I'm new to JPA and databases and general and need help understanding the causes of errors here.

First, i have these entities.

Position.java:

```<code>package com.example.offerserver.offerservice.task1;

@Entity
@Table(name = "position_table")

public class Position {
    public Position() {
    }

    public Position(UUID id, String name, Integer salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }
    @Id
    private UUID id;
    @Column(name = "name")
    private String name;
    @Column(name = "salary")
    private Integer salary;

    //getters and setters
</code>```

Stuff.java:

```<code>package com.example.offerserver.offerservice.task1;

@Entity
@Table(name = "stuff_table")
public class Stuff {
    public Stuff(){};

    public Stuff(UUID id,
                 String surname,
                 String name,
                 String patronymic,
                 boolean sex,
                 LocalDate birthDate,
                 Double salaryMultiplier,
                 Position position) {
        this.id = id;
        this.surname = surname;
        this.name = name;
        this.patronymic = patronymic;
        this.sex = sex;
        this.birthDate = birthDate;
        this.salaryMultiplier = salaryMultiplier;
        this.position = position;
    }
    @Id
    private UUID id;
    @Column(name="surname")
    private String surname;
    @Column(name="name")
    private String name;
    @Column(name="patronymic")
    private String patronymic;
    @Column(name="sex")
    private boolean sex;
    @Column(name="birth_date")
    private LocalDate birthDate;
    @Column(name="salary_multiplier")
    private Double salaryMultiplier;
    @OneToOne(fetch = FetchType.LAZY)
    private Position position;
</code>```

And JPA repositories:

```<code>
package com.example.offerserver.repository;
@Repository
public interface StuffRepository extends JpaRepository<Stuff, String> {
}
</code>```
```<code>
package com.example.offerserver.repository;
@Repository
public interface PositionRepository extends JpaRepository<Position, UUID> {
}
</code>```

And i have this request:

```<code>package com.example.offerserver.controller;

@Controller
@RequestMapping("/api/v1/stuff")
public class StuffListController {
    @Autowired
    StuffRepository repository;
    @GetMapping("")
    public ResponseEntity<List<Stuff>> getStuffList(){
        List<Stuff> stuff = repository.findAll();
        return new ResponseEntity<>(stuff, HttpStatus.OK);
</code>```

Sending this request i'm getting this error:

Could not write JSON: Unable to find com.example.offerserver.offerservice.task1.Position with id f0bd15f2-74c1-4979-854b-ffbe44b3da59; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unable to find com.example.offerserver.offerservice.task1.Position with id f0bd15f2-74c1-4979-854b-ffbe44b3da59 (through reference chain: java.util.ArrayList[0]->com.example.offerserver.offerservice.task1.Stuff["position"]->com.example.offerserver.offerservice.task1.Position$HibernateProxy$E63ZeIxs["id"])
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Unable to find com.example.offerserver.offerservice.task1.Position with id f0bd15f2-74c1-4979-854b-ffbe44b3da59; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unable to find com.example.offerserver.offerservice.task1.Position with id f0bd15f2-74c1-4979-854b-ffbe44b3da59 (through reference chain: java.util.ArrayList[0]->com.example.offerserver.offerservice.task1.Stuff["position"]->com.example.offerserver.offerservice.task1.Position$HibernateProxy$E63ZeIxs["id"])

In debug every instance of stuff in the list is initialized without its "position" field, throwing an error:

Method threw 'javax.persistence.EntityNotFoundException' exception. Cannot evaluate com.example.offerserver.offerservice.task1.Position$HibernateProxy$2ZiRYZbP.toString()

This is how position repository is initialized on launch:

```<code>public static List<Position> POSITIONS = List.of(
    new Position(UUID.randomUUID(), "Junior Java Backend Developer", 60000),
    new Position(UUID.randomUUID(), "Middle Machine Learning Engineer", 120000),
    new Position(UUID.randomUUID(), "Senior DevOps Engineer", 200000),
    new Position(UUID.randomUUID(), "Senior DevOps Engineer", 150000),
    new Position(UUID.randomUUID(), "Intern System Engineer", 20000)
);
positionRepository.saveAll(POSITIONS);
</code>```

Stuff repository as well. Position field for every stuff instance is randomly chosen from a POSITIONS list.

Body:
So i'm developing a REST API for my Spring appplication. I have to store all data in H2 database and i'm trying to find a correct way to do so. I'm new to JPA and databases and general and need help understanding the causes of errors here.

First, i have these entities.

Position.java:

package com.example.offerserver.offerservice.task1;

@Entity
@Table(name = "position_table")

public class Position {
    public Position() {
    }

    public Position(UUID id, String name, Integer salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }
    @Id
    private UUID id;
    @Column(name = "name")
    private String name;
    @Column(name = "salary")
    private Integer salary;

    //getters and setters

Stuff.java:

package com.example.offerserver.offerservice.task1;

@Entity
@Table(name = "stuff_table")
public class Stuff {
    public Stuff(){};

    public Stuff(UUID id,
                 String surname,
                 String name,
                 String patronymic,
                 boolean sex,
                 LocalDate birthDate,
                 Double salaryMultiplier,
                 Position position) {
        this.id = id;
        this.surname = surname;
        this.name = name;
        this.patronymic = patronymic;
        this.sex = sex;
        this.birthDate = birthDate;
        this.salaryMultiplier = salaryMultiplier;
        this.position = position;
    }
    @Id
    private UUID id;
    @Column(name="surname")
    private String surname;
    @Column(name="name")
    private String name;
    @Column(name="patronymic")
    private String patronymic;
    @Column(name="sex")
    private boolean sex;
    @Column(name="birth_date")
    private LocalDate birthDate;
    @Column(name="salary_multiplier")
    private Double salaryMultiplier;
    @OneToOne(fetch = FetchType.LAZY)
    private Position position;

And JPA repositories:

package com.example.offerserver.repository;
@Repository
public interface StuffRepository extends JpaRepository<Stuff, String> {
}

package com.example.offerserver.repository;
@Repository
public interface PositionRepository extends JpaRepository<Position, UUID> {
}

And i have this request:

package com.example.offerserver.controller;

@Controller
@RequestMapping("/api/v1/stuff")
public class StuffListController {
    @Autowired
    StuffRepository repository;
    @GetMapping("")
    public ResponseEntity<List<Stuff>> getStuffList(){
        List<Stuff> stuff = repository.findAll();
        return new ResponseEntity<>(stuff, HttpStatus.OK);

Sending this request i'm getting this error:

Could not write JSON: Unable to find com.example.offerserver.offerservice.task1.Position with id f0bd15f2-74c1-4979-854b-ffbe44b3da59; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unable to find com.example.offerserver.offerservice.task1.Position with id f0bd15f2-74c1-4979-854b-ffbe44b3da59 (through reference chain: java.util.ArrayList[0]->com.example.offerserver.offerservice.task1.Stuff["position"]->com.example.offerserver.offerservice.task1.Position$HibernateProxy$E63ZeIxs["id"])
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Unable to find com.example.offerserver.offerservice.task1.Position with id f0bd15f2-74c1-4979-854b-ffbe44b3da59; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unable to find com.example.offerserver.offerservice.task1.Position with id f0bd15f2-74c1-4979-854b-ffbe44b3da59 (through reference chain: java.util.ArrayList[0]->com.example.offerserver.offerservice.task1.Stuff["position"]->com.example.offerserver.offerservice.task1.Position$HibernateProxy$E63ZeIxs["id"])

In debug every instance of stuff in the list is initialized without its "position" field, throwing an error:

Method threw 'javax.persistence.EntityNotFoundException' exception. Cannot evaluate com.example.offerserver.offerservice.task1.Position$HibernateProxy$2ZiRYZbP.toString()

This is how position repository is initialized on launch:

public static List<Position> POSITIONS = List.of(
    new Position(UUID.randomUUID(), "Junior Java Backend Developer", 60000),
    new Position(UUID.randomUUID(), "Middle Machine Learning Engineer", 120000),
    new Position(UUID.randomUUID(), "Senior DevOps Engineer", 200000),
    new Position(UUID.randomUUID(), "Senior DevOps Engineer", 150000),
    new Position(UUID.randomUUID(), "Intern System Engineer", 20000)
);
positionRepository.saveAll(POSITIONS);

Stuff repository as well. Position field for every stuff instance is randomly chosen from a POSITIONS list.


问:
R Rayshader Render Points Don't Show as Expected
I'm trying to use the rayshader package in R to produce an elevation plot with points on the surface (or floating just above) that represent where samples were taken. However, I can't seem to get the points to show up on the map, or when they do, they don't show up where I expect them.

Here's a toy example:

```<code>library(raster)
set.seed(1)
x <- raster(ncol=50, nrow=50, xmn=-1, xmx=1, ymn=-1, ymx=1)
res(x) <- .5
x[] <- rnorm(16, -5, 10)
fakepoints <- data.frame(x = c(0, -.5),
                         y = c(0, 0))
fakepoints$elev <- (raster::extract(x, fakepoints))
x_dat <- data.frame(rasterToPoints(x, spatial = T))
library(rayshader)
library(ggplot2)
e_mat = raster_to_matrix(x)
a <- ggplot()+
  geom_tile(data =x_dat, aes(x =x, y = y, fill = layer ))+
  scale_fill_gradientn(colors = rev(topo.colors(10)))

height <- plot_gg(a, multicore = TRUE, raytrace = TRUE, width = 7, height = 4,
             scale = 300, windowsize = c(1400, 866), zoom = .5, theta = 30, max_error = 0.001,save_height_matrix = T)

render_points(extent = attr(x,"extent"),
              size = 10,
              color = "black",
              heightmap = height,
              altitude = fakepoints$elev+.1,
              zscale = 1,
              offset = 0,
              lat = fakepoints$y, long = fakepoints$x,
              clear_previous = T)
</code>```

The points should show up  at (0,0) and (-.5, 0), but I can't see to make them appear anywhere.

Body:
I'm trying to use the rayshader package in R to produce an elevation plot with points on the surface (or floating just above) that represent where samples were taken. However, I can't seem to get the points to show up on the map, or when they do, they don't show up where I expect them.

Here's a toy example:

library(raster)
set.seed(1)
x <- raster(ncol=50, nrow=50, xmn=-1, xmx=1, ymn=-1, ymx=1)
res(x) <- .5
x[] <- rnorm(16, -5, 10)
fakepoints <- data.frame(x = c(0, -.5),
                         y = c(0, 0))
fakepoints$elev <- (raster::extract(x, fakepoints))
x_dat <- data.frame(rasterToPoints(x, spatial = T))
library(rayshader)
library(ggplot2)
e_mat = raster_to_matrix(x)
a <- ggplot()+
  geom_tile(data =x_dat, aes(x =x, y = y, fill = layer ))+
  scale_fill_gradientn(colors = rev(topo.colors(10)))

height <- plot_gg(a, multicore = TRUE, raytrace = TRUE, width = 7, height = 4,
             scale = 300, windowsize = c(1400, 866), zoom = .5, theta = 30, max_error = 0.001,save_height_matrix = T)

render_points(extent = attr(x,"extent"),
              size = 10,
              color = "black",
              heightmap = height,
              altitude = fakepoints$elev+.1,
              zscale = 1,
              offset = 0,
              lat = fakepoints$y, long = fakepoints$x,
              clear_previous = T)

The points should show up  at (0,0) and (-.5, 0), but I can't see to make them appear anywhere.


问:
Is it possible to make a custom calendar widget with PyQt5 that looks like this one?
Source: https://github.com/pyrochlore/obsidian-tracker

The image above comes from a plug-in for Obsidian.

The following picture is from a custom QCalendarWidget I made that shows a different color depending on the % of tasks completed for each day.

(https://i.stack.imgur.com/unmMu.png)

I've found this answer from @eyllanesc showing how to make a custom QCalendarWidget that displays a round edge around the selected day. I wonder if it's also possible to make it looks like the picture I posted above.


问:
How do I fix my Select Where statements and add month to date and previous month to date?
I am trying to create a report that shows pounds produced by customer and item no and show totals on month to date and previous month to date.  I am VERY rusty with my sql skills and need help.  This is what I have so far (I need the Net_Weight to be a SUM statement too)

```<code>SELECT

C.Customer_Code,
P.Part_No as Item,
P.Name,
LBS.Net_Weight

FROM Part_v_Part as P

JOIN Common_v_Customer as C
ON C.Plexus_Customer_No = P.Plexus_Customer_No
JOIN Part_v_Production as LBS
ON LBS.Plexus_Customer_No = P.Plexus_Customer_No
JOIN Part_v_Workcenter as W
ON W.Plexus_Customer_No = P.Plexus_Customer_No
JOIN Part_v_Container as CS
ON CS.Plexus_Customer_No = P.Plexus_Customer_No

SELECT * FROM Part_v_Container WHERE CONTAINER_STATUS != Rework;
SELECT * FROM Common_v_Customer ORDER BY Customer_Code;
SELECT * FROM Part_v_Workcenter WHERE WORKCENTER_CODE = 'LF Production%' AND 'Plant Production%'
</code>```

I tried googling what I was doing wrong but there is so much information out there I couldn't figure out which was the best answer - I did try a few and kept getting errors.  In the query above I get the error message: "SQL Syntax error on line 29 symbol 78. Found 'Plant Production%', expected invalid relational operator."

The table should look like below when query is run:

Customer
Item_No
Name
Last Month To Date (LMTD)
Current Month To Date
Net_Weight

Cell 1
Cell 2

Cell 3
Cell 4

I am looking to compare current months production to last months production.

I would appreciate any help I can get.

Thank  you,

Body:
I am trying to create a report that shows pounds produced by customer and item no and show totals on month to date and previous month to date.  I am VERY rusty with my sql skills and need help.  This is what I have so far (I need the Net_Weight to be a SUM statement too)

SELECT

C.Customer_Code,
P.Part_No as Item,
P.Name,
LBS.Net_Weight

FROM Part_v_Part as P

JOIN Common_v_Customer as C
ON C.Plexus_Customer_No = P.Plexus_Customer_No
JOIN Part_v_Production as LBS
ON LBS.Plexus_Customer_No = P.Plexus_Customer_No
JOIN Part_v_Workcenter as W
ON W.Plexus_Customer_No = P.Plexus_Customer_No
JOIN Part_v_Container as CS
ON CS.Plexus_Customer_No = P.Plexus_Customer_No

SELECT * FROM Part_v_Container WHERE CONTAINER_STATUS != Rework;
SELECT * FROM Common_v_Customer ORDER BY Customer_Code;
SELECT * FROM Part_v_Workcenter WHERE WORKCENTER_CODE = 'LF Production%' AND 'Plant Production%'

I tried googling what I was doing wrong but there is so much information out there I couldn't figure out which was the best answer - I did try a few and kept getting errors.  In the query above I get the error message: "SQL Syntax error on line 29 symbol 78. Found 'Plant Production%', expected invalid relational operator."

The table should look like below when query is run:

Customer
Item_No
Name
Last Month To Date (LMTD)
Current Month To Date
Net_Weight

Cell 1
Cell 2

Cell 3
Cell 4

I am looking to compare current months production to last months production.

I would appreciate any help I can get.

Thank  you,


问:
Java Certificate Error when trying to connect to Azure SQL Server
As the title says trying to connect but I get the following error.

```<code>
Failed to authenticate the user ************* in Active Directory (Authentication=ActiveDirectoryPassword). javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

</code>```

I'm using DBeaver in this case. But this occurs in code too.

Here's what I've tried.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

I've replaced my cacerts file with a coworkers who's connection works without issues.

DBeaver has its cacerts within program files and I've replaced this too and tried.

I've tried the "trust server certificate" option too.

I've added Microsofts TSL1/TSL2 certificates too (https://www.microsoft.com/pki/mscorp/cps/default.htm)

Also a certificate for the server itself.

Had JDK 17 deleted it updated to JDK 19, replaced carcerts.

I'm new to Java, so anything helps.

Body:
As the title says trying to connect but I get the following error.

Failed to authenticate the user ************* in Active Directory (Authentication=ActiveDirectoryPassword). javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I'm using DBeaver in this case. But this occurs in code too.

Here's what I've tried.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

I've replaced my cacerts file with a coworkers who's connection works without issues.

DBeaver has its cacerts within program files and I've replaced this too and tried.

I've tried the "trust server certificate" option too.

I've added Microsofts TSL1/TSL2 certificates too (https://www.microsoft.com/pki/mscorp/cps/default.htm)

Also a certificate for the server itself.

Had JDK 17 deleted it updated to JDK 19, replaced carcerts.

I'm new to Java, so anything helps.


问:
HSTS header in .htaccess set up, but not working
I set the lines below on .htaccess file for many websites I developed :

```<code>RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

<if "%{HTTPS} == 'on'">
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
</if>
</code>```

I also successfully added the concerned domains on https://hstspreload.org/

Unfortunately, all tests I've done (Chrome development tools, https://securityheaders.com) in order to check if HSTS was well operational failed.

All of the domains have a valid SSL certificate installed, for all domains and subdomains.
I also tried to set headers with PHP, same results.

Does anyone know why, and how to make HSTS effective to pass the test ?

Thanks for your help

Body:
I set the lines below on .htaccess file for many websites I developed :

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

<if "%{HTTPS} == 'on'">
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
</if>

I also successfully added the concerned domains on https://hstspreload.org/

Unfortunately, all tests I've done (Chrome development tools, https://securityheaders.com) in order to check if HSTS was well operational failed.

All of the domains have a valid SSL certificate installed, for all domains and subdomains.
I also tried to set headers with PHP, same results.

Does anyone know why, and how to make HSTS effective to pass the test ?

Thanks for your help


问:
Query Firestore document by user UID with AngularFire
I need some basic 101 style advice here.
I've built an app using Angular 15, Firebase 9, AngularFire 7. I've got auth set up and can log in and do simple read/write operations.

Now I'm setting up a component and I want it to get fs.doc(`/users/${user.uid}`). This will retrieve a doc from the /users collection and from that I'll push some data to my view.

Everything in AngularFire (I'm in compat mode) seems to be an Observable so to get the uid I have to subscribe to auth.user, then when I get a result I can use the UID to query the /users collection.

But I'd like to know what the best approach is here - do I subscribe to auth, then nest another subscription on the result?

```<code>auth.user.subscribe((user:User|null)=>{
   if(user){
      fs.doc(`/users/${user.uid}`).valueChanges().subscribe((data)=>{
         console.log(data)
      })
   }
})
</code>```

Or do I store my UID in a service as a variable to use elsewhere? Or am I completely heading off into the weeds here?

Sorry for the vague, hand-wavey question. I've been Googling all evening and what I really need is just a good example app, or tutorial on best practice for working with AngularFire. Their docs aren't doing it for me and their examples just cover very basic single queries which I'm fine with.

Any advice? I'm terribly confused and I'm going to bed.

Body:
I need some basic 101 style advice here.
I've built an app using Angular 15, Firebase 9, AngularFire 7. I've got auth set up and can log in and do simple read/write operations.

Now I'm setting up a component and I want it to get fs.doc(`/users/${user.uid}`). This will retrieve a doc from the /users collection and from that I'll push some data to my view.

Everything in AngularFire (I'm in compat mode) seems to be an Observable so to get the uid I have to subscribe to auth.user, then when I get a result I can use the UID to query the /users collection.

But I'd like to know what the best approach is here - do I subscribe to auth, then nest another subscription on the result?

auth.user.subscribe((user:User|null)=>{
   if(user){
      fs.doc(`/users/${user.uid}`).valueChanges().subscribe((data)=>{
         console.log(data)
      })
   }
})

Or do I store my UID in a service as a variable to use elsewhere? Or am I completely heading off into the weeds here?

Sorry for the vague, hand-wavey question. I've been Googling all evening and what I really need is just a good example app, or tutorial on best practice for working with AngularFire. Their docs aren't doing it for me and their examples just cover very basic single queries which I'm fine with.

Any advice? I'm terribly confused and I'm going to bed.


问:
How to Mapping with Automapper dynamically?
im trying to use the AutoMapper dynamically
i have more than 20 TypeClasses that i receive from another library Project and it can be added more in a future (i dont control that)

Im using
Automapper 8.1
.Net 3.1
C# 8

in this case i have a DTO called TypeTableUpsert

```<code>public class TypeTableUpsert
    {

        public string TypeName { get; set; }
        public long TypeID { get; set; }
        public string TypeCode { get; set; }
        public string TypeDescription { get; set; }
}

</code>```

and the tables which comes from the library call like ProductType, FileType

```<code>public class ProductType
    {
        public long ProductTypeID {get;set}
        public string ProductTypeCode { get; set; }
        public string ProductTypeName { get; set; }
        public string ProductTypeDescription { get; set; }
 }
</code>```
```<code>public class FileType
    {
        public long FileTypeID {get;set}
        public string FileTypeCode { get; set; }
        public string FileTypeName { get; set; }
        public string FileTypeDescription { get; set; }
 }
</code>```

im trying to create a Dynamic Map with Automapper

in the example below is the normal way to map a ProductType but im trying to avoid to create a lot of Mappings

```<code>var config = new MapperConfiguration(cgg => cgg.CreateMap<TypeTableUpsertModel, ProductType>().ForMember(dest =>dest.ProductTypeDescription,
                    opt => opt.MapFrom(src => src.TypeDescription)));
</code>```

im trying do something like that but im getting an errors

```<code>// im getting the Type Correctly
Type myType = Assamblies.ExportedTypes.SingleOrDefault(types => types.Name == typeModel.TypeTableName);

// here is were im getting the error using MyType
var config = new MapperConfiguration(cgg => cgg.CreateMap<TypeTableUpsertModel, myType>()
.ForMember(dest=> dest.GetType().GetProperties().Where(p=>p.Name.Contains("TypeDescription")).FirstOrDefault(), opt => opt.MapFrom(src => src.TypeDescription));

</code>```

//i Got the next Error

```<code>AutoMapper.AutoMapperConfigurationException
  HResult=0x80131500
  Message=Custom configuration for members is only supported for top-level individual members on a type.
  Source=AutoMapper
  StackTrace:
   at AutoMapper.Internal.ReflectionHelper.FindProperty(LambdaExpression lambdaExpression)
   at AutoMapper.Configuration.MappingExpression`2.ForMember[TMember](Expression`1 destinationMember, Action`1 memberOptions)
   at StewartConnect.Admin.Profiles.TypeTableProfile..ctor() in D:\Repos\StewartRepos\StewartConnect.Admin.APIs\StewartConnect.Admin\Profiles\TypeTableProfile.cs:line 43

</code>```

im already tried in different ways but i cant make it work

Body:
im trying to use the AutoMapper dynamically
i have more than 20 TypeClasses that i receive from another library Project and it can be added more in a future (i dont control that)

Im using
Automapper 8.1
.Net 3.1
C# 8

in this case i have a DTO called TypeTableUpsert

public class TypeTableUpsert
    {

        public string TypeName { get; set; }
        public long TypeID { get; set; }
        public string TypeCode { get; set; }
        public string TypeDescription { get; set; }
}

and the tables which comes from the library call like ProductType, FileType

public class ProductType
    {
        public long ProductTypeID {get;set}
        public string ProductTypeCode { get; set; }
        public string ProductTypeName { get; set; }
        public string ProductTypeDescription { get; set; }
 }

public class FileType
    {
        public long FileTypeID {get;set}
        public string FileTypeCode { get; set; }
        public string FileTypeName { get; set; }
        public string FileTypeDescription { get; set; }
 }

im trying to create a Dynamic Map with Automapper

in the example below is the normal way to map a ProductType but im trying to avoid to create a lot of Mappings

var config = new MapperConfiguration(cgg => cgg.CreateMap<TypeTableUpsertModel, ProductType>().ForMember(dest =>dest.ProductTypeDescription,
                    opt => opt.MapFrom(src => src.TypeDescription)));

im trying do something like that but im getting an errors

// im getting the Type Correctly
Type myType = Assamblies.ExportedTypes.SingleOrDefault(types => types.Name == typeModel.TypeTableName);

// here is were im getting the error using MyType
var config = new MapperConfiguration(cgg => cgg.CreateMap<TypeTableUpsertModel, myType>()
.ForMember(dest=> dest.GetType().GetProperties().Where(p=>p.Name.Contains("TypeDescription")).FirstOrDefault(), opt => opt.MapFrom(src => src.TypeDescription));

//i Got the next Error

AutoMapper.AutoMapperConfigurationException
  HResult=0x80131500
  Message=Custom configuration for members is only supported for top-level individual members on a type.
  Source=AutoMapper
  StackTrace:
   at AutoMapper.Internal.ReflectionHelper.FindProperty(LambdaExpression lambdaExpression)
   at AutoMapper.Configuration.MappingExpression`2.ForMember[TMember](Expression`1 destinationMember, Action`1 memberOptions)
   at StewartConnect.Admin.Profiles.TypeTableProfile..ctor() in D:\Repos\StewartRepos\StewartConnect.Admin.APIs\StewartConnect.Admin\Profiles\TypeTableProfile.cs:line 43

im already tried in different ways but i cant make it work


问:
Flir Lepton 3.5 Banana pi zero Armbian I2C issue
I have (I believed succesfully) enabled the spi and i2c on armbian to communicate with the lepton. Using the LEPTON FLIR libraries (e.g. https://github.com/Myzhar/Lepton3_Jetson/tree/master/grabber_lib/Lepton_SDK) I can communicate with the camera (set output etc. returns LEP_OK). However when I try to reboot the camera (using the LEP_RunOemReboot( &port )) I get I2C error. I tried to check in the file linux_I2C.c and I know that in function DEV_I2C_MasterReadData(...)  the check  if(bbb_result != 0 || bytesActuallyRead != bytesToRead) fails with values bbb_result = -1; bytesActuallyRead = 0 and bytesToRead = 2. As the settings otherwise returns OK (I have no way to check it, as the camera seems to get stuck after one frame. I want to reboot it and I get to this loop).

Any idea what is going on?
[EDIT] does not seem to be this issue as sleeps around the write function did nothing.
(the issue seems to be the write int DEV_I2C_MasterReadData(...)  returning -1)


问:
Font Troubles with SVGs in img tags
I'm working on an animated image series using SVGs + CSS keyframes. My issue is with the fonts not displaying correctly, specifically in Safari.

I have added an import URL to use the font from Google Fonts:

@import url('https://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic');

But when the SVG is displayed in an img tag, the font does not render correctly. (it does however render correctly on its own (view image source), or in an embed or object tag).

I'm wondering if anyone has struggled with the same issue and is aware of what I could change/fix to have this SVG render correctly while still in a img tag.

Here's a sample of what's happening:
https://a4c.ca/proofs/animation-proofs/example-for-help.svg

Expecting the fonts to display in Roboto in Safari.

I've tried:

Encoding the URL

Using third party services like https://vecta.io/nano to embed the fonts (which mostly works, but causes some odd breakages)

*I know I can outline the text so that it's not live text.  But that adds a considerable amount of bloat. So Ideally I'd like to find a way to embed the fonts so they work in the img tag.

Thanks in advance to anyone who has a look. My brain is dead...

Title: Font Troubles with SVGs in img tags


问:
Is it possible to have a timer during a CMake build?
I need to measure the time spent by different steps during a CMake build.

Currently my build logs look like this :

```<code>Scanning dependencies of target TARGET1
[ 75%] Building TARGET1
[ 75%] Generating TARGET1 description file
[ 75%] Built target TARGET1
Scanning dependencies of target TARGET2
[ 75%] Building TARGET2
[ 75%] Generating TARGET2 description file
[ 75%] Built target TARGET2
Scanning dependencies of target TARGET3
[ 75%] Building TARGET3
[ 75%] Generating TARGET3 description file
[ 75%] Built target TARGET3
Scanning dependencies of target TARGET4
[ 75%] Building TARGET4
[ 75%] Generating TARGET4 description file
[ 75%] Built target TARGET4
</code>```

What I would like to do is having something like that :

```<code>[build] [770/1170  64% :: 44.419] Building TARGET1
[build] [771/1170  64% :: 44.431] Building TARGET2
[build] [772/1170  64% :: 44.745] Building TARGET3
[build] [773/1170  64% :: 44.873] Generating TARGET1
[build] [774/1170  64% :: 44.934] Building TARGET4
</code>```

Here we see a timer on the right which is very helpful to see which steps takes more time etc... The last logs come from the CMake plugin of VScode but I don't know how to display the same timer with a classical use of CMake.

Anyone knows how to do this ? Is there just an option to activate of something like that ?

Thx !

Body:
I need to measure the time spent by different steps during a CMake build.

Currently my build logs look like this :

Scanning dependencies of target TARGET1
[ 75%] Building TARGET1
[ 75%] Generating TARGET1 description file
[ 75%] Built target TARGET1
Scanning dependencies of target TARGET2
[ 75%] Building TARGET2
[ 75%] Generating TARGET2 description file
[ 75%] Built target TARGET2
Scanning dependencies of target TARGET3
[ 75%] Building TARGET3
[ 75%] Generating TARGET3 description file
[ 75%] Built target TARGET3
Scanning dependencies of target TARGET4
[ 75%] Building TARGET4
[ 75%] Generating TARGET4 description file
[ 75%] Built target TARGET4

What I would like to do is having something like that :

[build] [770/1170  64% :: 44.419] Building TARGET1
[build] [771/1170  64% :: 44.431] Building TARGET2
[build] [772/1170  64% :: 44.745] Building TARGET3
[build] [773/1170  64% :: 44.873] Generating TARGET1
[build] [774/1170  64% :: 44.934] Building TARGET4

Here we see a timer on the right which is very helpful to see which steps takes more time etc... The last logs come from the CMake plugin of VScode but I don't know how to display the same timer with a classical use of CMake.

Anyone knows how to do this ? Is there just an option to activate of something like that ?

Thx !


问:
CakePHP 4.1 ORM many-to-many contain works one way but not the other
I'm facing an odd issue where a many-to-many relationship allows me to contain in one direction but not the other. I've managed to boil it down to a one-line example. In a controller,

this works as expected: $this->MarketplaceCategoryOptions->find()->contain(['Users'])->all()->toArray()

while this throws: $this->Users->find()->contain(['MarketplaceCategoryOptions'])->all()->toArray()

and the error is: Error: [RuntimeException] "_joinData" is missing from the belongsToMany results. Results cannot be created. in /application/vendor/cakephp/cakephp/src/ORM/Association/Loader/SelectWithPivotLoader.php on line 179.

Here are the models:

UsersTable.php

```<code>        $this->belongsToMany('MarketplaceCategoryOptions')
            ->setThrough(MarketplaceCategoryOptionsUsersTable::class)
            ->setClassName('MarketplaceCategoryOptions')
            ->setForeignKey('user_id')
            ->setTargetForeignKey('marketplace_category_option_id');
</code>```

and on the other side:

MarketplaceCategoryOptionsTable.php

```<code>        $this->belongsToMany('Users')
            ->setThrough(MarketplaceCategoryOptionsUsersTable::class)
            ->setClassName('Users')
            ->setForeignKey('marketplace_category_option_id')
            ->setTargetForeignKey('user_id');
</code>```

The join table:

MarketplaceCategoryOptionsUsersTable.php

```<code>        $this->belongsTo('MarketplaceCategoryOptions')
            ->setForeignKey('marketplace_category_option_id')
            ->setJoinType('INNER');

        $this->belongsTo('Users')
            ->setForeignKey('user_id')
            ->setJoinType('INNER');
</code>```

The setup appears fully symmetrical to me so I really don't understand how it's possible for these  two to behave differently. As far as I'm aware I'm following all cake conventions. I also have a bunch of other many-to-many associations just like this one in the same codebase and they work fine. I've also manually removed all cache from the tmp directory, just in case. Any ideas what could be the reason?

Body:
I'm facing an odd issue where a many-to-many relationship allows me to contain in one direction but not the other. I've managed to boil it down to a one-line example. In a controller,

this works as expected: $this->MarketplaceCategoryOptions->find()->contain(['Users'])->all()->toArray()

while this throws: $this->Users->find()->contain(['MarketplaceCategoryOptions'])->all()->toArray()

and the error is: Error: [RuntimeException] "_joinData" is missing from the belongsToMany results. Results cannot be created. in /application/vendor/cakephp/cakephp/src/ORM/Association/Loader/SelectWithPivotLoader.php on line 179.

Here are the models:

UsersTable.php

        $this->belongsToMany('MarketplaceCategoryOptions')
            ->setThrough(MarketplaceCategoryOptionsUsersTable::class)
            ->setClassName('MarketplaceCategoryOptions')
            ->setForeignKey('user_id')
            ->setTargetForeignKey('marketplace_category_option_id');

and on the other side:

MarketplaceCategoryOptionsTable.php

        $this->belongsToMany('Users')
            ->setThrough(MarketplaceCategoryOptionsUsersTable::class)
            ->setClassName('Users')
            ->setForeignKey('marketplace_category_option_id')
            ->setTargetForeignKey('user_id');

The join table:

MarketplaceCategoryOptionsUsersTable.php

        $this->belongsTo('MarketplaceCategoryOptions')
            ->setForeignKey('marketplace_category_option_id')
            ->setJoinType('INNER');

        $this->belongsTo('Users')
            ->setForeignKey('user_id')
            ->setJoinType('INNER');

The setup appears fully symmetrical to me so I really don't understand how it's possible for these  two to behave differently. As far as I'm aware I'm following all cake conventions. I also have a bunch of other many-to-many associations just like this one in the same codebase and they work fine. I've also manually removed all cache from the tmp directory, just in case. Any ideas what could be the reason?


问:
Model not loading after using plyer filechooser
I have a trained model which is loading in the main python file. It is working and giving predictions when I choose kivy's FileChooseListView but I wanted to make it better so I used plyer filechooser which did load images but the problem is now my model is not loading. Its not giving any error either. Can anyone tell what the problem is?

I have tried correcting it and debugging but nothing is happening.

main.py

```<code>class UploadScreen(Screen):
    def file_chooser(self):
        filechooser.open_file(on_selection=self.selected)

    def selected(self, filename):
        try:
            self.ids.my_image.source = filename[0]
            print(filename[0])

            CATEGORIES = ['Diving Side',  # 1.
                          'Golf-Swing-Front',  # 2.
                          'Golf-Swing-Side',  # 3.
                          'Kicking-Front',  # 4.
                          'Kicking-Side',  # 5.
                          'Lifting',  # 6
                          'Riding-Horse',  # 7
                          'Run-Side',  # 8.
                          'SkateBoarding-Front',  # 9
                          'Swing-Bench',  # 10.
                          'Swing-SideAngle',  # 11
                          'Walk-Front'  # 12.
                          ]
            model = tf.keras.models.load_model("./model/model") /// Model is not loading
            size = (90, 90)
            img_array = cv2.imread(filename[0])
            pd_array = []
            im = cv2.resize(img_array, size, cv2.INTER_AREA)
            im = im.astype('float32')
            pd_array.append(im)

            np_image = np.array(pd_array)
            print("NP array ")
            print(np_image.shape)
            predictions = model.predict(np_image)
            top = np.argmax(predictions)
            print(predictions)
            # top=top-1
            print(top)
            print("prediction is "+CATEGORIES[top])

            results = CATEGORIES[top]
            print(results)
            name = results
            # Update the label
            self.ids.name_label.text = name
            print("Captured")
        except:
            pass
</code>```

.kv

```<code><UploadScreen>:
    name: 'upload'
    id: upload
    orientation: 'vertical'
    canvas:
        Color:
            # rgba: 0.439,0.501,0.564,1
            rgb: 0.662, 0.662, 0.662, 1
        Rectangle:
            size: self.size
            pos: self.pos
    MDGridLayout:
        rows:5
        cols:1
        spacing: 25
        padding: 25
        MDLabel:
            id: name_label
            text: "Results"
            bold: True
            font_size: 35
            color: 0.137, 0.156, 0.419, 1
            halign: 'center'
            size_hint_y: None
            height: self.texture_size[1]

        MDRaisedButton:
            text: 'Select Image'
            font_size: 18
            size_hint: None, None
            width: root.width*1
            height: root.height*0.1
            md_bg_color: 0.258, 0.372, 0.921, 1
            text_color: 1,1,1,1
            pos_hint: {'center_x':0.5,'center_y':0.3}
            on_press: root.file_chooser()

        BoxLayout:
            orientation: "vertical"
            size: root.width, root.height
            padding: 50
            spacing: 20

            Image:
                id: my_image
                source: ""

        MDRaisedButton:
            text: 'Back'
            font_size: 18
            size_hint: None, None
            width: root.width*1
            height: root.height*0.1
            md_bg_color: 0.258, 0.372, 0.921, 1
            text_color: 1,1,1,1
            pos_hint: {'center_x':0.5,'center_y':0.3}
            on_press: root.manager.current = 'main'
</code>```

Body:
I have a trained model which is loading in the main python file. It is working and giving predictions when I choose kivy's FileChooseListView but I wanted to make it better so I used plyer filechooser which did load images but the problem is now my model is not loading. Its not giving any error either. Can anyone tell what the problem is?

I have tried correcting it and debugging but nothing is happening.

main.py

class UploadScreen(Screen):
    def file_chooser(self):
        filechooser.open_file(on_selection=self.selected)

    def selected(self, filename):
        try:
            self.ids.my_image.source = filename[0]
            print(filename[0])

            CATEGORIES = ['Diving Side',  # 1.
                          'Golf-Swing-Front',  # 2.
                          'Golf-Swing-Side',  # 3.
                          'Kicking-Front',  # 4.
                          'Kicking-Side',  # 5.
                          'Lifting',  # 6
                          'Riding-Horse',  # 7
                          'Run-Side',  # 8.
                          'SkateBoarding-Front',  # 9
                          'Swing-Bench',  # 10.
                          'Swing-SideAngle',  # 11
                          'Walk-Front'  # 12.
                          ]
            model = tf.keras.models.load_model("./model/model") /// Model is not loading
            size = (90, 90)
            img_array = cv2.imread(filename[0])
            pd_array = []
            im = cv2.resize(img_array, size, cv2.INTER_AREA)
            im = im.astype('float32')
            pd_array.append(im)

            np_image = np.array(pd_array)
            print("NP array ")
            print(np_image.shape)
            predictions = model.predict(np_image)
            top = np.argmax(predictions)
            print(predictions)
            # top=top-1
            print(top)
            print("prediction is "+CATEGORIES[top])

            results = CATEGORIES[top]
            print(results)
            name = results
            # Update the label
            self.ids.name_label.text = name
            print("Captured")
        except:
            pass

.kv

<UploadScreen>:
    name: 'upload'
    id: upload
    orientation: 'vertical'
    canvas:
        Color:
            # rgba: 0.439,0.501,0.564,1
            rgb: 0.662, 0.662, 0.662, 1
        Rectangle:
            size: self.size
            pos: self.pos
    MDGridLayout:
        rows:5
        cols:1
        spacing: 25
        padding: 25
        MDLabel:
            id: name_label
            text: "Results"
            bold: True
            font_size: 35
            color: 0.137, 0.156, 0.419, 1
            halign: 'center'
            size_hint_y: None
            height: self.texture_size[1]

        MDRaisedButton:
            text: 'Select Image'
            font_size: 18
            size_hint: None, None
            width: root.width*1
            height: root.height*0.1
            md_bg_color: 0.258, 0.372, 0.921, 1
            text_color: 1,1,1,1
            pos_hint: {'center_x':0.5,'center_y':0.3}
            on_press: root.file_chooser()

        BoxLayout:
            orientation: "vertical"
            size: root.width, root.height
            padding: 50
            spacing: 20

            Image:
                id: my_image
                source: ""

        MDRaisedButton:
            text: 'Back'
            font_size: 18
            size_hint: None, None
            width: root.width*1
            height: root.height*0.1
            md_bg_color: 0.258, 0.372, 0.921, 1
            text_color: 1,1,1,1
            pos_hint: {'center_x':0.5,'center_y':0.3}
            on_press: root.manager.current = 'main'


问:
I am trying to run a simple plural code in a PDF custom action using JavaScript
I am attempting to create what I thought would be a simple Plural code however it is not working any help would be greatly appreciated thank you.

```<code><span class="counter b">2 <span id="PLURAL"></span></span>

<script type="text/javascript">
var a = Number(this.getField("Total QTY").valueAsString);
myFunction(parseFloat(q[0].innerHTML)); // first span, convert to number
document.getElementById("PLURAL").innerHTML = x;

function myFunction(a) {
if (a > 1) {
        x = "CLAMPS";
    } else {
        x = "CLAMP";
    }
}
</script>
</code>```

If it helps this is in the value calculation custom action of a form field inside PDF xchange editor

Body:
I am attempting to create what I thought would be a simple Plural code however it is not working any help would be greatly appreciated thank you.

2

If it helps this is in the value calculation custom action of a form field inside PDF xchange editor


问:
Trouble creating a line perpendicular to player -> cursor line
I am trying raycasting methods and want to simply draw a triangle in the direction of my cursor, with that triangle having a 90 degree angle at the cursor, so that it is a right angle triangle.

I am currently using solely the player's coordinates and the mouse's coordenates to calculate a coordinate of the point of the triangle. I use pygame to draw the lines and create this app.

Here is my existing python code :

import pygame as pg, sys, time, math, numpy as np

class RayCast:

  def calc_bearing(
    self, charX, charY, charW, charH
  ):  # take position of character and mouse, calculate distance using pythagoras and then angle using sohcahtoa -> "toa" tan-1(change in y , change in x)
    mouseX, mouseY = pg.mouse.get_pos()
    charX = charX + charW // 2
    charY = charY + charH // 2
    deltaY = charY - mouseY
    deltaX = -1 * (charX - mouseX)
    distance = math.sqrt(((deltaY**2) + (deltaX**2)))

    #print(f"{deltaX} <-- DeltaX | DeltaY --> {deltaY}")
    if deltaY != 0:

      ANGLE = abs(math.degrees(math.atan(deltaX / deltaY)))
      if deltaY < 0 and deltaX > 0:
        ANGLE = 180 - ANGLE
      elif deltaX == 0 and deltaY < 0:
        ANGLE = 180
      elif deltaY < 0 and deltaX < 0:
        ANGLE += 180
      elif deltaY > 0 and deltaX < 0:`your text`
        ANGLE = 360 - ANGLE

    else:
      if deltaX > 0:
        ANGLE = 90
      elif deltaX < 0:
        ANGLE = 270

    #print(
    #   ANGLE
    #)  # PROBLEM, if both are negative, then angle is positive and vice versa // SOLVED

# finds bearing of mouse relative to player - works

class Game(RayCast):

  def __init__(self):

    pg.init()
    #clock = pg.time.Clock()
    self.WIDTH, self.HEIGHT = 800, 800
    self.charWidth, self.charHeight = 50, 50

    self.character = pg.Rect(
      (self.WIDTH // 2 - self.charWidth // 2),
      (self.HEIGHT // 2 - self.charHeight // 2), self.charWidth,
      self.charHeight)  # left,top,width,height , start in center

    self.WIN = pg.display.set_mode((self.WIDTH, self.HEIGHT))
    pg.display.set_caption("Ray Cast")
    self.start_time = time.time()
    self.raycast = RayCast()

    self.WHITE = (255, 255, 255)
    while True:

      self.mainLoop()

  def mainLoop(self):
    self.updateScreen()
    self.handleMove()
    self.raycast.calc_bearing(self.character.x, self.character.y,
                              self.charWidth, self.charHeight)
    self.deltaTime = self.calcDeltaTime(
      self.start_time)  #calc delta time (change in time)
    self.start_time = self.calcFPS(self.start_time)
    for event in pg.event.get():
      if event.type == pg.QUIT:
        pg.quit()
        sys.exit(0)

  def calcFPS(self, start):
    if time.time() - start != 0:

      fps = 1 / (time.time() - start)
      #print(f"FPS --> {fps}")
    return time.time()

  def updateScreen(self):
    self.WIN.fill((0, 0, 0))
    pg.draw.rect(self.WIN, self.WHITE, self.character)
    self.draw_line()
    self.draw_triangle()
    pg.display.update()

  def handleMove(self):
    keys = pg.key.get_pressed()
    if keys[pg.K_w]:
      self.character.y -= 0.75 * self.deltaTime
    if keys[pg.K_a]:
      self.character.x -= 0.75 * self.deltaTime
    if keys[pg.K_s]:
      self.character.y += 1 * self.deltaTime
    if keys[pg.K_d]:
      self.character.x += 1 * self.deltaTime

  def calcDeltaTime(self, start):
    #print(f"DeltaTime -->  {(time.time() - start) + 1}")
    return ((time.time() - start) + 1)

  def draw_line(self):
    point1 = tuple([
      self.character.x + self.charWidth // 2,
      self.character.y + self.charHeight // 2
    ])
    point2 = pg.mouse.get_pos()
    #print(f"{point1} <-- POINT1 | POINT2 --> {point2}")

    # surface, colour, start, end, width

    pg.draw.line(self.WIN, self.WHITE, point1, point2, width=2)

  def draw_triangle(self):
    charX, charY = self.character.x + self.charWidth//2, self.character.y + self.charHeight//2
    mouseX, mouseY = pg.mouse.get_pos()

    deltax = abs(mouseX) - abs(charX)
    deltay = abs(mouseY) - abs(charY)
    if (deltax!= 0) and (deltay != 0):

      # sqrt((sqrt(x1^2 + y1^2)^2) + 100^2) * (sin((sin-1(100/ sqrt(x1^2 + y1^2)^2 + 100^2))) + (180 - (tan-1(x/y)) - 90))

      r = math.sqrt(math.sqrt((deltax**2) + (deltay**2))+100**2)
      theta1 = np.arcsin((100/r))
      z = (np.arctan(deltax / deltay))
      theta2 = 90 - z
      o = r * (np.sin(theta1 + theta2))
      a = r * (np.cos(theta1 + theta2))
      point1 = (mouseX + o, mouseY + a)
      playerPos = (charX,charY)
      pg.draw.line(self.WIN, self.WHITE, point1, pg.mouse.get_pos(), width=2)
      pg.draw.line(self.WIN, self.WHITE, point1,playerPos, width = 2 )

      #r2 = np.sqrt((deltax**2 + deltay**2))
     # r1 = np.sqrt(r2**2 + 100**2)

      #theta2 = math.degrees(np.arccos(deltax / r2)) # in radians
      #theta1 = math.degrees(np.arccos(r2/r1)) # in radians

      #o = r1 * np.sin(theta1 + theta2)
      #a = r1 * np.cos(theta1 + theta2)
      #point1 = (mouseX + o, mouseY + a)

      #pg.draw.line(self.WIN, self.WHITE, point1, pg.mouse.get_pos(), width = 2 )

    else:
      if (charX - mouseX == 0 and mouseY > charY):  # is below the player
        pass
      elif (charX - mouseX == 0) and (mouseY < charY):  # above player
        pass
      elif (charY - mouseY == 0):  # left of player
        #pg.draw.line(self.WIN, self.WHITE,
        #             (self.character.x, self.character.y - oppLength // 2),
        #             (self.character.x, self.character.y + oppLength // 2))
        pass

      elif (charY - mouseY == 0):  # right of player
        #pg.draw.line(self.WIN, self.WHITE,
        #             (self.character.x, self.character.y - oppLength // 2),
        #             (self.character.x, self.character.y + oppLength // 2))
        pass

    #print(m)

game = Game()

```
<p>the error is in the <code>draw_triangle()</code> function. Please help me figure this out.</p>
<p>I tried a few different equations but the one I decided to use was :</p>
<pre class="lang-py prettyprint-override"><code>a = sqrt((sqrt(x1^2 + y1^2)^2) + 100^2) * (sin((sin-1(100/ sqrt(x1^2 + y1^2)^2 + 100^2))) + (180 - (tan-1(x/y)) - 90))

pg.drawline(self.WIN,self.WHITE,(playerposX + a, playerposY), mousePos, width = 2)
</code>```

but this draws a line in the complete wrong place.

Body:
I am trying raycasting methods and want to simply draw a triangle in the direction of my cursor, with that triangle having a 90 degree angle at the cursor, so that it is a right angle triangle.

I am currently using solely the player's coordinates and the mouse's coordenates to calculate a coordinate of the point of the triangle. I use pygame to draw the lines and create this app.

Here is my existing python code :

import pygame as pg, sys, time, math, numpy as np

class RayCast:

  def calc_bearing(
    self, charX, charY, charW, charH
  ):  # take position of character and mouse, calculate distance using pythagoras and then angle using sohcahtoa -> "toa" tan-1(change in y , change in x)
    mouseX, mouseY = pg.mouse.get_pos()
    charX = charX + charW // 2
    charY = charY + charH // 2
    deltaY = charY - mouseY
    deltaX = -1 * (charX - mouseX)
    distance = math.sqrt(((deltaY**2) + (deltaX**2)))

    #print(f"{deltaX} <-- DeltaX | DeltaY --> {deltaY}")
    if deltaY != 0:

      ANGLE = abs(math.degrees(math.atan(deltaX / deltaY)))
      if deltaY < 0 and deltaX > 0:
        ANGLE = 180 - ANGLE
      elif deltaX == 0 and deltaY < 0:
        ANGLE = 180
      elif deltaY < 0 and deltaX < 0:
        ANGLE += 180
      elif deltaY > 0 and deltaX < 0:`your text`
        ANGLE = 360 - ANGLE

    else:
      if deltaX > 0:
        ANGLE = 90
      elif deltaX < 0:
        ANGLE = 270

    #print(
    #   ANGLE
    #)  # PROBLEM, if both are negative, then angle is positive and vice versa // SOLVED

# finds bearing of mouse relative to player - works

class Game(RayCast):

  def __init__(self):

    pg.init()
    #clock = pg.time.Clock()
    self.WIDTH, self.HEIGHT = 800, 800
    self.charWidth, self.charHeight = 50, 50

    self.character = pg.Rect(
      (self.WIDTH // 2 - self.charWidth // 2),
      (self.HEIGHT // 2 - self.charHeight // 2), self.charWidth,
      self.charHeight)  # left,top,width,height , start in center

    self.WIN = pg.display.set_mode((self.WIDTH, self.HEIGHT))
    pg.display.set_caption("Ray Cast")
    self.start_time = time.time()
    self.raycast = RayCast()

    self.WHITE = (255, 255, 255)
    while True:

      self.mainLoop()

  def mainLoop(self):
    self.updateScreen()
    self.handleMove()
    self.raycast.calc_bearing(self.character.x, self.character.y,
                              self.charWidth, self.charHeight)
    self.deltaTime = self.calcDeltaTime(
      self.start_time)  #calc delta time (change in time)
    self.start_time = self.calcFPS(self.start_time)
    for event in pg.event.get():
      if event.type == pg.QUIT:
        pg.quit()
        sys.exit(0)

  def calcFPS(self, start):
    if time.time() - start != 0:

      fps = 1 / (time.time() - start)
      #print(f"FPS --> {fps}")
    return time.time()

  def updateScreen(self):
    self.WIN.fill((0, 0, 0))
    pg.draw.rect(self.WIN, self.WHITE, self.character)
    self.draw_line()
    self.draw_triangle()
    pg.display.update()

  def handleMove(self):
    keys = pg.key.get_pressed()
    if keys[pg.K_w]:
      self.character.y -= 0.75 * self.deltaTime
    if keys[pg.K_a]:
      self.character.x -= 0.75 * self.deltaTime
    if keys[pg.K_s]:
      self.character.y += 1 * self.deltaTime
    if keys[pg.K_d]:
      self.character.x += 1 * self.deltaTime

  def calcDeltaTime(self, start):
    #print(f"DeltaTime -->  {(time.time() - start) + 1}")
    return ((time.time() - start) + 1)

  def draw_line(self):
    point1 = tuple([
      self.character.x + self.charWidth // 2,
      self.character.y + self.charHeight // 2
    ])
    point2 = pg.mouse.get_pos()
    #print(f"{point1} <-- POINT1 | POINT2 --> {point2}")

    # surface, colour, start, end, width

    pg.draw.line(self.WIN, self.WHITE, point1, point2, width=2)

  def draw_triangle(self):
    charX, charY = self.character.x + self.charWidth//2, self.character.y + self.charHeight//2
    mouseX, mouseY = pg.mouse.get_pos()

    deltax = abs(mouseX) - abs(charX)
    deltay = abs(mouseY) - abs(charY)
    if (deltax!= 0) and (deltay != 0):

      # sqrt((sqrt(x1^2 + y1^2)^2) + 100^2) * (sin((sin-1(100/ sqrt(x1^2 + y1^2)^2 + 100^2))) + (180 - (tan-1(x/y)) - 90))

      r = math.sqrt(math.sqrt((deltax**2) + (deltay**2))+100**2)
      theta1 = np.arcsin((100/r))
      z = (np.arctan(deltax / deltay))
      theta2 = 90 - z
      o = r * (np.sin(theta1 + theta2))
      a = r * (np.cos(theta1 + theta2))
      point1 = (mouseX + o, mouseY + a)
      playerPos = (charX,charY)
      pg.draw.line(self.WIN, self.WHITE, point1, pg.mouse.get_pos(), width=2)
      pg.draw.line(self.WIN, self.WHITE, point1,playerPos, width = 2 )

      #r2 = np.sqrt((deltax**2 + deltay**2))
     # r1 = np.sqrt(r2**2 + 100**2)

      #theta2 = math.degrees(np.arccos(deltax / r2)) # in radians
      #theta1 = math.degrees(np.arccos(r2/r1)) # in radians

      #o = r1 * np.sin(theta1 + theta2)
      #a = r1 * np.cos(theta1 + theta2)
      #point1 = (mouseX + o, mouseY + a)

      #pg.draw.line(self.WIN, self.WHITE, point1, pg.mouse.get_pos(), width = 2 )

    else:
      if (charX - mouseX == 0 and mouseY > charY):  # is below the player
        pass
      elif (charX - mouseX == 0) and (mouseY < charY):  # above player
        pass
      elif (charY - mouseY == 0):  # left of player
        #pg.draw.line(self.WIN, self.WHITE,
        #             (self.character.x, self.character.y - oppLength // 2),
        #             (self.character.x, self.character.y + oppLength // 2))
        pass

      elif (charY - mouseY == 0):  # right of player
        #pg.draw.line(self.WIN, self.WHITE,
        #             (self.character.x, self.character.y - oppLength // 2),
        #             (self.character.x, self.character.y + oppLength // 2))
        pass

    #print(m)

game = Game()

the error is in the draw_triangle() function. Please help me figure this out.

I tried a few different equations but the one I decided to use was :

a = sqrt((sqrt(x1^2 + y1^2)^2) + 100^2) * (sin((sin-1(100/ sqrt(x1^2 + y1^2)^2 + 100^2))) + (180 - (tan-1(x/y)) - 90))

pg.drawline(self.WIN,self.WHITE,(playerposX + a, playerposY), mousePos, width = 2)

but this draws a line in the complete wrong place.


问:
React Native Image Component showing white blank
Hi I am new to react native and have been playing around some components on the doc.

I wrote some code for an Image component, but it shows white blank even though I can check the path to the image stored in Firestore. Uploading and storing an image is successfully done, and I can see the path in the Firebase console (also, I can see the path on the screen).

Here is the code Image component placed in.

import {
  Image,
  ImageBackground,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { useAuthContext } from "../../contexts/AuthContext";
import { NotYetVerified } from "./NotYetVerified";
import { SignoutBtn } from "./SignoutBtn";
import { useFirestoreContext } from "../../contexts/FirestoreContext";
import { ImagePickerBtn } from "./ImagePickerBtn";
import { useEffect } from "react";

export const UserProfile = () => {
  const { currUser } = useAuthContext();
  const { getUserInfo, userInfo } = useFirestoreContext();

  useEffect(() => {
    getUserInfo(currUser.email);
  }, []);

  console.log("UserProfile.js userInfo: ", userInfo.photoUrl, currUser.photoURL);
  return (
    <>
      {/* remove the ! mark when publishing */}
      {currUser.emailVerified ? (
        <View
          style={{
            flex: 1,
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <TouchableOpacity onPress={() => getUserInfo(currUser.email)}>
            <Text>Get user info</Text>
          </TouchableOpacity>
          <Text>{userInfo?.email}</Text>
          <Text>{userInfo?.photoUrl}</Text>
          <ImagePickerBtn />
          <Image
            style={styles.photo}
            source={{
              uri: userInfo.photoUrl,
            }}
            resizeMethod="resize"
            resizeMode="contain"
          />
        </View>
      ) : (
        <NotYetVerified />
      )}
      <SignoutBtn />
    </>
  );
};

const styles = StyleSheet.create({
  photo: {
    width: 100,
    height: 100,
    borderRadius: 50,
    borderColor: "black",
    borderWidth: 1,
  },
});
```
<h2>I don't think it's necessary, but just in case, code below is for uploading a file.</h2>
<pre class="lang-js prettyprint-override"><code>import React, { useState, useEffect } from "react";
import { Button, Image, View, Platform } from "react-native";
import * as ImagePicker from "expo-image-picker";
import {getDownloadURL, getStorage, ref, uploadBytes} from 'firebase/storage'
import { useAuthContext } from "../../contexts/AuthContext";
import { doc, setDoc, updateDoc } from "firebase/firestore";
import { db } from "../../firebase.config";
import { updateProfile } from "firebase/auth";
export const ImagePickerBtn = () => {
  const [image, setImage] = useState(null);

  const {currUser} = useAuthContext()
  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result);

    if (!result.canceled) {
      const storage = getStorage(); // the storage itself
      const fileRef = ref(storage, currUser.uid + '.png'); // how the image will be addressed inside the storage

      // convert image to array of bytes.
      const img = await fetch(result.uri);
      const blob = await img.blob();

      await uploadBytes(fileRef, result.uri); // upload the image
      const url = await getDownloadURL(fileRef); // get the url of the image
      console.log(url); // print the url of the image
      await updateDoc(doc(db, "users", currUser.uid), {photoUrl: url}); // set the url of the image in the database
      await updateProfile(currUser, {photoURL: url}); // set the url of the image in the database})
    }
  };

  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && (
        <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
      )}
    </View>
  );
}
</code>```

Body:
Hi I am new to react native and have been playing around some components on the doc.

I wrote some code for an Image component, but it shows white blank even though I can check the path to the image stored in Firestore. Uploading and storing an image is successfully done, and I can see the path in the Firebase console (also, I can see the path on the screen).

Here is the code Image component placed in.

import {
  Image,
  ImageBackground,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { useAuthContext } from "../../contexts/AuthContext";
import { NotYetVerified } from "./NotYetVerified";
import { SignoutBtn } from "./SignoutBtn";
import { useFirestoreContext } from "../../contexts/FirestoreContext";
import { ImagePickerBtn } from "./ImagePickerBtn";
import { useEffect } from "react";

export const UserProfile = () => {
  const { currUser } = useAuthContext();
  const { getUserInfo, userInfo } = useFirestoreContext();

  useEffect(() => {
    getUserInfo(currUser.email);
  }, []);

  console.log("UserProfile.js userInfo: ", userInfo.photoUrl, currUser.photoURL);
  return (
    <>
      {/* remove the ! mark when publishing */}
      {currUser.emailVerified ? (
        <View
          style={{
            flex: 1,
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <TouchableOpacity onPress={() => getUserInfo(currUser.email)}>
            <Text>Get user info</Text>
          </TouchableOpacity>
          <Text>{userInfo?.email}</Text>
          <Text>{userInfo?.photoUrl}</Text>
          <ImagePickerBtn />
          <Image
            style={styles.photo}
            source={{
              uri: userInfo.photoUrl,
            }}
            resizeMethod="resize"
            resizeMode="contain"
          />
        </View>
      ) : (
        <NotYetVerified />
      )}
      <SignoutBtn />
    </>
  );
};

const styles = StyleSheet.create({
  photo: {
    width: 100,
    height: 100,
    borderRadius: 50,
    borderColor: "black",
    borderWidth: 1,
  },
});

I don't think it's necessary, but just in case, code below is for uploading a file.

import React, { useState, useEffect } from "react";
import { Button, Image, View, Platform } from "react-native";
import * as ImagePicker from "expo-image-picker";
import {getDownloadURL, getStorage, ref, uploadBytes} from 'firebase/storage'
import { useAuthContext } from "../../contexts/AuthContext";
import { doc, setDoc, updateDoc } from "firebase/firestore";
import { db } from "../../firebase.config";
import { updateProfile } from "firebase/auth";
export const ImagePickerBtn = () => {
  const [image, setImage] = useState(null);

  const {currUser} = useAuthContext()
  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result);

    if (!result.canceled) {
      const storage = getStorage(); // the storage itself
      const fileRef = ref(storage, currUser.uid + '.png'); // how the image will be addressed inside the storage

      // convert image to array of bytes.
      const img = await fetch(result.uri);
      const blob = await img.blob();

      await uploadBytes(fileRef, result.uri); // upload the image
      const url = await getDownloadURL(fileRef); // get the url of the image
      console.log(url); // print the url of the image
      await updateDoc(doc(db, "users", currUser.uid), {photoUrl: url}); // set the url of the image in the database
      await updateProfile(currUser, {photoURL: url}); // set the url of the image in the database})
    }
  };

  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && (
        <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
      )}
    </View>
  );
}


问:
How to "reset" concatMap in rxjs?
Im attempting to call a function that dispatches an action that in turn triggers an effect that calls a service as many times as there are pages, starting from page 1. The issue that im having is that, after I call the function, it triggers as many times as I need, but the "pageIndex" isnt resetting back to 0.

```<code>    this.store.dispatch(fromStore.getAllUsersByFilters({ filters: this.searchFilters.value, pageIndex: 0 }));

</code>```

Inside the effect:

```<code> @Effect()
    // other stuff
    concatMap(([{ filters }, groupNumbers], pageIndex) =>
      this.userService.getUsersByFilters(filters, groupNumbers, pageIndex).pipe(
        map((res: UserSearchResponse) => {
          if (res.success) {
            if(pageIndex < res.totalResults / res.pageSize){
              this.store.dispatch(userActions.getAllUsersByFilters({filters: filters, pageIndex: res.pageIndex++}));
            }
            return userActions.getAllUsersSuccess({ users: res.results });
          }
          this.message.showErrorMessage('Failed to Retrieve Enrollments')
          return userActions.getAllUsersFailure();
        })
      )
    )
  )
</code>```

When I run the search again, It doesnt start from 0 again, but instead from the next number after pageIndex. I dont understand why this is happening, as I was under the impression that if im passing a '0' into the dispatch function, it would start over. I'm aware that concatMap returns all the values from each subscription but I cant find a way to reset it without touching the state (if that would even work at this point). I'd appreciate any help on this issue.

If anyone can even propose another a better way to go about doing this i would like to hear that also

Title: How to "reset" concatMap in rxjs?

Body:
Im attempting to call a function that dispatches an action that in turn triggers an effect that calls a service as many times as there are pages, starting from page 1. The issue that im having is that, after I call the function, it triggers as many times as I need, but the "pageIndex" isnt resetting back to 0.

    this.store.dispatch(fromStore.getAllUsersByFilters({ filters: this.searchFilters.value, pageIndex: 0 }));

Inside the effect:

 @Effect()
    // other stuff
    concatMap(([{ filters }, groupNumbers], pageIndex) =>
      this.userService.getUsersByFilters(filters, groupNumbers, pageIndex).pipe(
        map((res: UserSearchResponse) => {
          if (res.success) {
            if(pageIndex < res.totalResults / res.pageSize){
              this.store.dispatch(userActions.getAllUsersByFilters({filters: filters, pageIndex: res.pageIndex++}));
            }
            return userActions.getAllUsersSuccess({ users: res.results });
          }
          this.message.showErrorMessage('Failed to Retrieve Enrollments')
          return userActions.getAllUsersFailure();
        })
      )
    )
  )

When I run the search again, It doesnt start from 0 again, but instead from the next number after pageIndex. I dont understand why this is happening, as I was under the impression that if im passing a '0' into the dispatch function, it would start over. I'm aware that concatMap returns all the values from each subscription but I cant find a way to reset it without touching the state (if that would even work at this point). I'd appreciate any help on this issue.

If anyone can even propose another a better way to go about doing this i would like to hear that also


问:
Adding deeplearning4j as dependency in build.gradle yields "Cannot be resolved". Why is this happening?
So I have a basic Gradle project. The build.gradle looks like this

```<code>/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java application project to get you started.
 * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
 * User Manual available at https://docs.gradle.org/7.5.1/userguide/building_java_projects.html
 */

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    // Use JUnit test framework.
    testImplementation 'junit:junit:4.13.2'

    // This dependency is used by the application.
    implementation 'com.google.guava:guava:31.0.1-jre'

    implementation 'org.deeplearning4j:deeplearning4j-core:1.0.0-M2.1'
    implementation 'org.deeplearning4j:deeplearning4j-data:1.0.0-M2.1'
    implementation 'org.deeplearning4j:deeplearning4j-ui:1.0.0-M2.1'
}

application {
    // Define the main class for the application.
    mainClass = 'entry.App'
}

</code>```

As you can see I add 3 deeplearning4j dependencies. When typing these out I get suggestions for the deeplearning4j. And after adding these to the build file. The Gradle project does build successfully. However, I can't refer to org.deeplearning4j. Says "cannot be resolved". What is going on here?

Body:
So I have a basic Gradle project. The build.gradle looks like this

/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java application project to get you started.
 * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
 * User Manual available at https://docs.gradle.org/7.5.1/userguide/building_java_projects.html
 */

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    // Use JUnit test framework.
    testImplementation 'junit:junit:4.13.2'

    // This dependency is used by the application.
    implementation 'com.google.guava:guava:31.0.1-jre'

    implementation 'org.deeplearning4j:deeplearning4j-core:1.0.0-M2.1'
    implementation 'org.deeplearning4j:deeplearning4j-data:1.0.0-M2.1'
    implementation 'org.deeplearning4j:deeplearning4j-ui:1.0.0-M2.1'
}

application {
    // Define the main class for the application.
    mainClass = 'entry.App'
}

As you can see I add 3 deeplearning4j dependencies. When typing these out I get suggestions for the deeplearning4j. And after adding these to the build file. The Gradle project does build successfully. However, I can't refer to org.deeplearning4j. Says "cannot be resolved". What is going on here?


问:
Using Follium to Add Markers to Leaflet Map from Data Stored in Array
I'm attempting to use Folium to create a web map using Leaflet with data stored in an array. However, the markers are not being added to the map.

I'm using the code below.

```<code>centerX = 34.2104
centerY = -77.8868
def Map():
    coord = [centerX, centerY]
    m = folium.Map(coord, zoom_start=13)
    m.save("index.html")
    # Parse CSV
    marker = []
    with open(userInFile, 'r') as ds:
        i=0
        for line in ds:
            i+=1
            strippedLine = line.strip()
            lineList = strippedLine.split(',')

            if i > 1:
                x = lineList[16]
                y = lineList[17]
                marker.append(x)
                marker.append(y)
    # Add markers to map
    print(marker)
    i = 0
    while i < len(marker)-1:
        folium.Marker([float(marker[i]), float(marker[i+1])], popup="new location", icon=folium.Icon(color="green")).add_to(m)
        print(marker[i], marker[i+1])
        i+=2
</code>```

I wanted to make sure the data was being added to array correctly, below is the output of the print statements.

But none of the markers are being added to the map, only the basemap shows up. Could anyone help me find where my error is?

Body:
I'm attempting to use Folium to create a web map using Leaflet with data stored in an array. However, the markers are not being added to the map.

I'm using the code below.

centerX = 34.2104
centerY = -77.8868
def Map():
    coord = [centerX, centerY]
    m = folium.Map(coord, zoom_start=13)
    m.save("index.html")
    # Parse CSV
    marker = []
    with open(userInFile, 'r') as ds:
        i=0
        for line in ds:
            i+=1
            strippedLine = line.strip()
            lineList = strippedLine.split(',')

            if i > 1:
                x = lineList[16]
                y = lineList[17]
                marker.append(x)
                marker.append(y)
    # Add markers to map
    print(marker)
    i = 0
    while i < len(marker)-1:
        folium.Marker([float(marker[i]), float(marker[i+1])], popup="new location", icon=folium.Icon(color="green")).add_to(m)
        print(marker[i], marker[i+1])
        i+=2

I wanted to make sure the data was being added to array correctly, below is the output of the print statements.

But none of the markers are being added to the map, only the basemap shows up. Could anyone help me find where my error is?


问:
Starting RabbitMQ in K8s with Pre-defined Topics
This might be a dumb question but I've never used RabbitMQ in K8s before and am trying to figure out the best way to accomplish what I'm about to ask. I also haven't been able to find as part of my searching any results that address this particular question.

I have a series of deployments/pods, of which a few need to communicate using RabbitMQ via a topic (or topics). Is there any way to spin up a RabbitMQ cluster such that, when it starts up, it auto-creates the specified topics, exchanges, etc.?

I've yet to see any way to actually do this, which leads me to believe that the "best" way to accomplish this is to use an init container (or some other startup script elsewhere) that programmatically uses the RabbitMQ API to create and configure the topics. I could use pre-determined topic names to avoid having to update things at runtime.


问:
Convert the Stress and Gender field with Yes = 1 and No = 0 for Stress and Male = 1 and Female = 0 for Gender field. Produce a cross table
I have a Df with

```<code>$ Gender      : Factor w/ 2 levels "0","1": 2 2 1 1 1 2 2 2 1 1 ...

$ Stress      : Factor w/ 2 levels "No","Yes": 2 2 1 1 2 2 1 2 1 1 ...
</code>```

I am trying to convert Stress to

Yes = 1 and No = 0

and Gender to

Male =1 and Female = 0

so i can put the result of this in a Cross table with distribution between gender and stress in percentage

Body:
I have a Df with

$ Gender      : Factor w/ 2 levels "0","1": 2 2 1 1 1 2 2 2 1 1 ...

$ Stress      : Factor w/ 2 levels "No","Yes": 2 2 1 1 2 2 1 2 1 1 ...

I am trying to convert Stress to

Yes = 1 and No = 0

and Gender to

Male =1 and Female = 0

so i can put the result of this in a Cross table with distribution between gender and stress in percentage


问:
Optimal angle for 3D plot visualization
Is there any rule of thumb, or criterion based on research, regarding what is the best angle for displaying 3D plots? The angle is defined by a vector (a,b) where a and b are numbers between 0 and 180.

I know this is obviously context specific: different shapes of the plane (x,y,z) will have different optimal angles. But there might be some rule-of-thumb/criterion for specific cases such as a linear plane, or a convex one.

Title: Optimal angle for 3D plot visualization