问:
SQLAlchemy Async: How to synchronise the columns of a declarative model with its underlying table after metadata reflection?
I have also asked this question in sqlalchemy discussion group.

I am using alembic to apply a migration for a postgresql view using an async engine. This is successfully applied to the database.

I have the following declarative mapped class to  the view, defined as:

class MailingListView(Base):
    """View for mailing labels.
    After metata reflection from db -> model expecting columns to
    be available on this class.
    """
    __tablename__ = "mailing_list_view"

    # Specify the column override from the underlying view that is the primary key
    id = Column(UUID(as_uuid=True), primary_key=True)

    # Expecting  these columns  below to be mapped in this class after
    # metadata reflection. Currently have to uncomment these
    # to manually synchronise with view!
    #
    # addressee = Column(String)
    # street = Column(String)
    # town = Column(String)
    # county = Column(String)
    # postcode = Column(String)
    # cursor = Column(String)
```
<p>I am reflecting the views using the following:</p>
<pre class="lang-py prettyprint-override"><code>      def use_inspector(conn):
            inspector = inspect(conn)
            return inspector.get_view_names()

        views = await connection.run_sync(use_inspector)

        # I can see the table columns in __table__.c.keys()
        # after the reflection below has run
        await connection.run_sync(
            target_metadata.reflect,
            only=views,
            views=True,
            extend_existing=True,
        )
</code>```

After applying migrations and performing the above reflection I can see that my mapped model has the underlying table columns updated with those defined in the underlying view.

obj = MailingListView()
obj.__table__.c.keys()
```
<p>However, the properties of my mapped class are not updated after reflection, raising an exception:</p>
```obj = MailingListView()
obj.town = "town" # this raises an exception with unavailable property
```

How is it possible for a postgresql db (asyncpg) + async sqlalchemy to:

Synchronise the columns of a declarative model with its underlying table after metadata reflection?

Currently, I have to manually specify the columns in the declarative model.

Body:
I have also asked this question in sqlalchemy discussion group.

I am using alembic to apply a migration for a postgresql view using an async engine. This is successfully applied to the database.

I have the following declarative mapped class to  the view, defined as:

class MailingListView(Base):
    """View for mailing labels.
    After metata reflection from db -> model expecting columns to
    be available on this class.
    """
    __tablename__ = "mailing_list_view"

    # Specify the column override from the underlying view that is the primary key
    id = Column(UUID(as_uuid=True), primary_key=True)

    # Expecting  these columns  below to be mapped in this class after
    # metadata reflection. Currently have to uncomment these
    # to manually synchronise with view!
    #
    # addressee = Column(String)
    # street = Column(String)
    # town = Column(String)
    # county = Column(String)
    # postcode = Column(String)
    # cursor = Column(String)

I am reflecting the views using the following:

      def use_inspector(conn):
            inspector = inspect(conn)
            return inspector.get_view_names()

        views = await connection.run_sync(use_inspector)

        # I can see the table columns in __table__.c.keys()
        # after the reflection below has run
        await connection.run_sync(
            target_metadata.reflect,
            only=views,
            views=True,
            extend_existing=True,
        )

After applying migrations and performing the above reflection I can see that my mapped model has the underlying table columns updated with those defined in the underlying view.

obj = MailingListView()
obj.__table__.c.keys()

However, the properties of my mapped class are not updated after reflection, raising an exception:

obj = MailingListView()
obj.town = "town" # this raises an exception with unavailable property

How is it possible for a postgresql db (asyncpg) + async sqlalchemy to:

Synchronise the columns of a declarative model with its underlying table after metadata reflection?

Currently, I have to manually specify the columns in the declarative model.


来源: stackexchange

问:
class DataBank python modbus
I would like help to interpret the DataBank. If there was an update. I don't know how to apply it.

```<code>from servidormodbus2 import ServidorMODBUS

s = ServidorMODBUS('127.0.0.1',502)
s.run()
</code>```
```<code>from pyModbusTCP.server import DataBank, ModbusServer
from time import sleep
import random

class ServidorMODBUS():
    """
    Classe Servidor MODBUS
    """
    def __init__(self, host_ip,port):
        """
        Construtor
        """
        self._server =  ModbusServer(host=host_ip, port=port, no_block=True)
        self._db = DataBank

    def run(self):
        """
         Execução do servidor
        """
        self._server.start()
        setpoint = self._db.set_words(2000,25)
        print("Servidor em execução")
        while True:
            if self._db.get_bits(1000,[0]):
                setpoint = self._db.get_words(2000,0)
            self._db.set_words(1000,[random.randrange(int(0.95*setpoint),int(1.05*setpoint))])
            print('=====================')
            print(f'Tabela MODBUS')
            print(f'Holding Registers\r\n R1000: {self._db.get_words(1000)}\r\n R2000: {self._db.get_words(2000)}')
            print(f'Coils \r\n R1000: {self._db.get_bits(1000)}')
            print('=====================')
            sleep(1)
</code>```

The error TypeError: unsupported operand type(s) for *: 'float' and 'NoneType' was expected. But, DataBank says it is obsolete.

ContentLicense: CC BY-SA 4.0

Title: class DataBank python modbus

Body:
I would like help to interpret the DataBank. If there was an update. I don't know how to apply it.

from servidormodbus2 import ServidorMODBUS

s = ServidorMODBUS('127.0.0.1',502)
s.run()

from pyModbusTCP.server import DataBank, ModbusServer
from time import sleep
import random

class ServidorMODBUS():
    """
    Classe Servidor MODBUS
    """
    def __init__(self, host_ip,port):
        """
        Construtor
        """
        self._server =  ModbusServer(host=host_ip, port=port, no_block=True)
        self._db = DataBank

    def run(self):
        """
         Execução do servidor
        """
        self._server.start()
        setpoint = self._db.set_words(2000,25)
        print("Servidor em execução")
        while True:
            if self._db.get_bits(1000,[0]):
                setpoint = self._db.get_words(2000,0)
            self._db.set_words(1000,[random.randrange(int(0.95*setpoint),int(1.05*setpoint))])
            print('=====================')
            print(f'Tabela MODBUS')
            print(f'Holding Registers\r\n R1000: {self._db.get_words(1000)}\r\n R2000: {self._db.get_words(2000)}')
            print(f'Coils \r\n R1000: {self._db.get_bits(1000)}')
            print('=====================')
            sleep(1)

The error TypeError: unsupported operand type(s) for *: 'float' and 'NoneType' was expected. But, DataBank says it is obsolete.


问:
Service-to-service authentication in Asp.Net via OWIN
I am working on a stateless ServiceFabric application that listens to some events and performs some business logic. I am looking at extending this application to expose web apis. But I am struggling to figure out how to authentication these web apis.

In the scenario, the caller of the web apis is an AAD application which runs as a background/daemon service without any user footprint. I want to pre-authorize this background application to call the web apis exposed by ServiceFabric application.

Can I get some sample code / documentation that describes such scenario. Planning to use OWIN to setup authentication and use JWT token, but all documentation talks about user token scenario.


问:
Webview leaving residual images
I wonder if anyone had problems with webview showing something like "ghost" images:
My butons, text, radio buttons etc look like they were dragged down and left this residual image.
Android version here is 2.2

ContentLicense: CC BY-SA 3.0

Title: Webview leaving residual images


问:
How to update the Python interpreter call for terminal
I have wrote a program using the new 3.10 syntax, specifically, match case statements. Now I need to run the program using terminal.

python3 main.py gives back this error

```<code>    match str(i):
          ^
SyntaxError: invalid syntax
</code>```

Any ideas how to solve this issue?
I suppose the interpreter my terminal uses is of old version (<3.10), but I have no idea how to update it.

Thank you in advance!

Body:
I have wrote a program using the new 3.10 syntax, specifically, match case statements. Now I need to run the program using terminal.

python3 main.py gives back this error

    match str(i):
          ^
SyntaxError: invalid syntax

Any ideas how to solve this issue?
I suppose the interpreter my terminal uses is of old version (<3.10), but I have no idea how to update it.

Thank you in advance!


问:
cgo calling a cpp function: producing error for _stprintf_s
On Windows, from a go code using CGO, I am calling a function from a cpp file.
The function (from the cpp file) calls _stprintf_s. When I comment call to this function, the go code builds fine.
But in presence of this call i get followin error
error: 'sprintf_s' was not declared in this scope

I have included the required <stdio.h> & <tchar.h> in cgo.

Not sure why _stprintf_s is producing this error. any help/pointers are welcome.


问:
Unable to install nodejs on ubuntu 22 some files are common as the error describes and i dont know how to solve this?
it was working nice previously but when i tried to update node.js with 18 version then error occurred

error while installing


问:
what user or users are querying a postgres db table
Is there any way to identify what users are querying a specific table in a Postgres db?  Looking to audit a table and who is querying it.</p>


问:
Is there a way to obtain the same results of numpy function with tensorflow tensors?
I want to create a custom keras layer that compute the "predict" of a Self Organizing Map.
Here is my implementation of the layer
`

```<code>class SOMLayer(keras.layers.Layer):
    def __init__(self, X_train, y_train, w, n=50, input_shape=265):
        super(SOMLayer, self).__init__()
        self.inputs = None
        self.X_train = X_train
        self.y_train = y_train
        self._input_len = input_shape

        # weights of pre-trained SOM, two versions: _weights is a tensor, _weights_nc is a numpy array
        self._weights = tf.convert_to_tensor(w, dtype=tf.float32)
        self._weights_nc = w

        self._activation_map = zeros((n, n))

        # activation distance calc., lblmap version works with numpy arrays, the other one with tf tensors
        self._activation_distance = self._manhattan_distance
        self._activation_distance_lblmap = self._manhattan_distance_lblmap

        self.winmap = self.labels_map(X_train, y_train)

        self.default_class = sum(list(self.winmap.values())).most_common()[0][0]

    @tf.function
    def call(self, inputs):
        ret_arr = np.array(np.full(6, 0.01), ndmin=2)
        win_position = self.winner(inputs)
        if win_position.ref() in self.winmap:
            ret_arr[0][self.winmap[win_position.ref()].most_common()[0][0]] = 0.95

        else:
            ret_arr[0][self.default_class] = 0.95
        return ret_arr

    def _activate(self, x):
        """Updates matrix activation_map, in this matrix
           the element i,j is the response of the neuron i,j to x."""
        self._activation_map = self._activation_distance(x, self._weights)

    def _activate_lblmap(self, x):
        """Updates matrix activation_map, in this matrix
           the element i,j is the response of the neuron i,j to x."""
        self._activation_map = self._activation_distance_lblmap(x, self._weights_nc)

    def _manhattan_distance(self, x, w):
        return tf.linalg.norm(tf.subtract(x, w), ord=1, axis=-1)

    def _manhattan_distance_lblmap(self, x, w):
        return linalg.norm(subtract(x, w), ord=1, axis=-1)

    def _check_input_len(self, data):
        """Checks that the data in input is of the correct shape."""
        data_len = len(data[0])
        if self._input_len != data_len:
            msg = 'Received %d features, expected %d.' % (data_len,
                                                          self._input_len)
            raise ValueError(msg)

    @tf.function
    def winner(self, x):
        """Computes the coordinates of the winning neuron for the sample x."""
        self._activate(x)
        return tf.unravel_index(tf.argmin(self._activation_map, output_type=tf.int32),
                                tf.shape(self._activation_map))

    def winner_lblmap(self, x):
        """Computes the coordinates of the winning neuron for the sample x."""
        self._activate_lblmap(x)
        return unravel_index(self._activation_map.argmin(),
                             self._activation_map.shape)

    def labels_map(self, data, labels):
        """Returns a dictionary wm where wm[(i,j)] is a dictionary
        that contains the number of samples from a given label
        that have been mapped in position i,j.

        Parameters
        ----------
        data : np.array or list
            Data matrix.

        label : np.array or list
            Labels for each sample in data.
        """
        self._check_input_len(data)
        if not len(data) == len(labels):
            raise ValueError('data and labels must have the same length.')
        winmap = defaultdict(list)
        for x, l in zip(data, labels):
            winmap[self.winner_lblmap(x)].append(l)
        for position in winmap:
            winmap[position] = Counter(winmap[position])
        return winmap
</code>```

`
There are two implementation of the same method for methods like "activate", "manhattan_distance" and "winner".

The implementation with "_lblmap" in the name works with numpy arrays (is the impl. of the minisom python library) and the other impl. uses tensorflow tensors because the input of the layer when the model execute is a tensor and i was not able to convert that tensor in a numpy array.

The problem is in the "winner" method, the winner method that works with numpy array return this:

```<code>self.winner_lblmap numpy array implementation
(0, 2)
</code>```

that is the position (like x,y coordinates) of the Best Matching Unit that will determine the class of the input, and its called inside "labels_map" method.

The winner method called inside "call" method works with tensorflow tensors because it will manage the input passed when you use model.predict(...) and this input is a tensor.
The output of this implementation is:

```<code>self.winner tensorflow tensors implementation
Tensor("UnravelIndex:0", shape=(2, 50), dtype=int32)
</code>```

And looking the shape it's easy to see that is not the correct shape of the desired output, and also i'm not able to directly access the data inside this tensor (or previuos calculated ones).

I tried to force "eager evaluation" in different ways to try to visualize the data but without success.
I tried also to tune the "tf.linalg.norm" parameters but the shape of the result is (0,).

Is there a way to access the data inside the tensor and obtain tha same result of the "winner_lblmap" method that works with numpy arrays?

Body:
I want to create a custom keras layer that compute the "predict" of a Self Organizing Map.
Here is my implementation of the layer
`

class SOMLayer(keras.layers.Layer):
    def __init__(self, X_train, y_train, w, n=50, input_shape=265):
        super(SOMLayer, self).__init__()
        self.inputs = None
        self.X_train = X_train
        self.y_train = y_train
        self._input_len = input_shape

        # weights of pre-trained SOM, two versions: _weights is a tensor, _weights_nc is a numpy array
        self._weights = tf.convert_to_tensor(w, dtype=tf.float32)
        self._weights_nc = w

        self._activation_map = zeros((n, n))

        # activation distance calc., lblmap version works with numpy arrays, the other one with tf tensors
        self._activation_distance = self._manhattan_distance
        self._activation_distance_lblmap = self._manhattan_distance_lblmap

        self.winmap = self.labels_map(X_train, y_train)

        self.default_class = sum(list(self.winmap.values())).most_common()[0][0]

    @tf.function
    def call(self, inputs):
        ret_arr = np.array(np.full(6, 0.01), ndmin=2)
        win_position = self.winner(inputs)
        if win_position.ref() in self.winmap:
            ret_arr[0][self.winmap[win_position.ref()].most_common()[0][0]] = 0.95

        else:
            ret_arr[0][self.default_class] = 0.95
        return ret_arr

    def _activate(self, x):
        """Updates matrix activation_map, in this matrix
           the element i,j is the response of the neuron i,j to x."""
        self._activation_map = self._activation_distance(x, self._weights)

    def _activate_lblmap(self, x):
        """Updates matrix activation_map, in this matrix
           the element i,j is the response of the neuron i,j to x."""
        self._activation_map = self._activation_distance_lblmap(x, self._weights_nc)

    def _manhattan_distance(self, x, w):
        return tf.linalg.norm(tf.subtract(x, w), ord=1, axis=-1)

    def _manhattan_distance_lblmap(self, x, w):
        return linalg.norm(subtract(x, w), ord=1, axis=-1)

    def _check_input_len(self, data):
        """Checks that the data in input is of the correct shape."""
        data_len = len(data[0])
        if self._input_len != data_len:
            msg = 'Received %d features, expected %d.' % (data_len,
                                                          self._input_len)
            raise ValueError(msg)

    @tf.function
    def winner(self, x):
        """Computes the coordinates of the winning neuron for the sample x."""
        self._activate(x)
        return tf.unravel_index(tf.argmin(self._activation_map, output_type=tf.int32),
                                tf.shape(self._activation_map))

    def winner_lblmap(self, x):
        """Computes the coordinates of the winning neuron for the sample x."""
        self._activate_lblmap(x)
        return unravel_index(self._activation_map.argmin(),
                             self._activation_map.shape)

    def labels_map(self, data, labels):
        """Returns a dictionary wm where wm[(i,j)] is a dictionary
        that contains the number of samples from a given label
        that have been mapped in position i,j.

        Parameters
        ----------
        data : np.array or list
            Data matrix.

        label : np.array or list
            Labels for each sample in data.
        """
        self._check_input_len(data)
        if not len(data) == len(labels):
            raise ValueError('data and labels must have the same length.')
        winmap = defaultdict(list)
        for x, l in zip(data, labels):
            winmap[self.winner_lblmap(x)].append(l)
        for position in winmap:
            winmap[position] = Counter(winmap[position])
        return winmap

`
There are two implementation of the same method for methods like "activate", "manhattan_distance" and "winner".

The implementation with "_lblmap" in the name works with numpy arrays (is the impl. of the minisom python library) and the other impl. uses tensorflow tensors because the input of the layer when the model execute is a tensor and i was not able to convert that tensor in a numpy array.

The problem is in the "winner" method, the winner method that works with numpy array return this:

self.winner_lblmap numpy array implementation
(0, 2)

that is the position (like x,y coordinates) of the Best Matching Unit that will determine the class of the input, and its called inside "labels_map" method.

The winner method called inside "call" method works with tensorflow tensors because it will manage the input passed when you use model.predict(...) and this input is a tensor.
The output of this implementation is:

self.winner tensorflow tensors implementation
Tensor("UnravelIndex:0", shape=(2, 50), dtype=int32)

And looking the shape it's easy to see that is not the correct shape of the desired output, and also i'm not able to directly access the data inside this tensor (or previuos calculated ones).

I tried to force "eager evaluation" in different ways to try to visualize the data but without success.
I tried also to tune the "tf.linalg.norm" parameters but the shape of the result is (0,).

Is there a way to access the data inside the tensor and obtain tha same result of the "winner_lblmap" method that works with numpy arrays?


问:
How can my rendered RMarkdown/Quarto document with html widgets be linked to a live csv?
Correct me if I'm wrong: The examples online are generally for a static data set. The executed R code reads data into an R data frame and creates the html widgets to plot it.  Upon rendering the .Rmd or .qmd, that data set is baked into the html document.  If you wanted the document to show some new data, you'd have to run the R code again.

Is there a way to create a rendered .html with html widgets that's linked to a live .csv or SQL database?  Perhaps there are some R tools that upon rendering the document, create the html/js instructions to read a .csv or .json file?

Looking to have an .html file that can be shared or hosted that doesn't require an R interpreter.


问:
Error when running Jupyter Lab in Anacodna Navigator : Application Error in Python 3.8
I just created a new environnement in anaconda Python 3.8 and I got this error when I run Jupyter :

Traceback (most recent call last):
File "C:\Users\arsta\Anaconda3\envs\Python381\Scripts\jupyter-lab-script.py", line 6, in
from jupyterlab.labapp import main
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\jupyterlab\labapp.py", line 13, in
from jupyter_server.serverapp import flags
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\jupyter_server\serverapp.py", line 60, in
from jupyter_client import KernelManager
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\jupyter_client_init_.py", line 8, in
from .asynchronous import AsyncKernelClient # noqa
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\jupyter_client\asynchronous_init_.py", line 1, in
from .client import AsyncKernelClient # noqa
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\jupyter_client\asynchronous\client.py", line 6, in
from jupyter_client.channels import HBChannel
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\jupyter_client\channels.py", line 12, in
import zmq.asyncio
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\zmq_init_.py", line 103, in
from zmq import backend
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\zmq\backend_init_.py", line 31, in
raise original_error from None
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\zmq\backend_init_.py", line 26, in
ns = select_backend(first)
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\zmq\backend\select.py", line 31, in select_backend
mod = import_module(name)
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\importlib_init.py", line 127, in import_module
return _bootstrap.gcd_import(name[level:], package, level)
File "C:\Users\arsta\Anaconda3\envs\Python381\lib\site-packages\zmq\backend\cython_init.py", line 6, in
from . import (
ImportError: DLL load failed while importing _device: %1 n’est pas une application Win32 valide.

I really don't why it won't run, my environnement in 3.7 in fine but in 3.8 it just doesn't work. I alreadyu uninstalled python 3.8 (64bits) and reinstall in it (32bits)

Do you have any idea? Running Jupyter on anaconda in 3.8.


问:
Read only Spring Boot App- NoUniqueBeanDefinitionException: No qualifying bean of type available: expected single matching bean but found 2
I'm creating a read only REST API using Spring Boot 2.7 and Java 19

I followed the idea posted here: https://www.baeldung.com/spring-data-read-only-repository

I've created a read only generic repository:

```<code>package com.scope.mdm.domain;

import java.util.List;

import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

@NoRepositoryBean
public interface ReadOnlyRepository<T, ID> extends Repository<T, ID> {
    List<T> findAll();
}
</code>```

This is a simplify view of the entity definition:

```<code>package com.scope.mdm.domain;

import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.hibernate.annotations.Immutable;

@Entity
@Immutable
@Table(name = "v_LegalEntity", schema = "entity_reference")
public class LegalEntity {
    @Id
    @Column(name = "LegalEntityId")
    Integer legalEntityId;
    @Column(name = "SO_Id")
    String soId;
    @Column(name = "Source_LegalEntityId")
</code>```

I implemented a read only repository as follows:

```<code>package com.scope.mdm.domain;

import java.util.List;
import java.util.Optional;

public interface LegalEntityReadOnlyRepository extends ReadOnlyRepository<LegalEntity, Integer> {

    // Fetch legal entities by Scope One Id
    Optional<LegalEntity> findBySoId(String soId);

    // Fetch legal entities by its data source provided ID
    LegalEntity findByLegalEntityId(String legalEntityId);

    // Legal entities containing the name
    List<LegalEntity> findByLegalEntityNameLike(String legalEntityName);

}
</code>```

This is the controller:

```<code>package com.scope.mdm.web;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;

import com.scope.mdm.domain.LegalEntity;
import com.scope.mdm.domain.LegalEntityReadOnlyRepository;

@RestController
public class LegalEntityController {
    @Autowired
    private LegalEntityReadOnlyRepository repository;

    @RequestMapping(value="/legalEntities", method=RequestMethod.GET)
    public Iterable<LegalEntity> getLegalEntity() {
        return repository.findAll();
    }
}
</code>```

I want to do a simple unit test like this:

```<code>package com.scope.mdm;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.scope.mdm.domain.LegalEntityReadOnlyRepository;
import com.scope.mdm.domain.LegalEntityRepository;

import org.junit.jupiter.api.Assertions;

@SpringBootTest(classes = mdmWebAPIApplication.class)
public class legalEntitySearchTest {
    @Autowired
    private LegalEntityRepository repository;
    @Autowired
    private LegalEntityReadOnlyRepository repositoryReadOnly;

    @Test
    public void contextLoads() {
        Assertions.assertNotNull(repositoryReadOnly);
        Assertions.assertNotNull(repository);
    }
</code>```

}

When running the test from VSCODE I get this error:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
qualifying bean of type
'com.scope.mdm.domain.LegalEntityReadOnlyRepository' available:
expected single matching bean but found 2:
legalEntityRepository,legalEntityReadOnlyRepository

I tried with the @Qualifier annotation to explicitly specify the bean but the result is the same.

Body:
I'm creating a read only REST API using Spring Boot 2.7 and Java 19

I followed the idea posted here: https://www.baeldung.com/spring-data-read-only-repository

I've created a read only generic repository:

package com.scope.mdm.domain;

import java.util.List;

import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

@NoRepositoryBean
public interface ReadOnlyRepository<T, ID> extends Repository<T, ID> {
    List<T> findAll();
}

This is a simplify view of the entity definition:

package com.scope.mdm.domain;

import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.hibernate.annotations.Immutable;

@Entity
@Immutable
@Table(name = "v_LegalEntity", schema = "entity_reference")
public class LegalEntity {
    @Id
    @Column(name = "LegalEntityId")
    Integer legalEntityId;
    @Column(name = "SO_Id")
    String soId;
    @Column(name = "Source_LegalEntityId")

I implemented a read only repository as follows:

package com.scope.mdm.domain;

import java.util.List;
import java.util.Optional;

public interface LegalEntityReadOnlyRepository extends ReadOnlyRepository<LegalEntity, Integer> {

    // Fetch legal entities by Scope One Id
    Optional<LegalEntity> findBySoId(String soId);

    // Fetch legal entities by its data source provided ID
    LegalEntity findByLegalEntityId(String legalEntityId);

    // Legal entities containing the name
    List<LegalEntity> findByLegalEntityNameLike(String legalEntityName);

}

This is the controller:

package com.scope.mdm.web;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;

import com.scope.mdm.domain.LegalEntity;
import com.scope.mdm.domain.LegalEntityReadOnlyRepository;

@RestController
public class LegalEntityController {
    @Autowired
    private LegalEntityReadOnlyRepository repository;

    @RequestMapping(value="/legalEntities", method=RequestMethod.GET)
    public Iterable<LegalEntity> getLegalEntity() {
        return repository.findAll();
    }
}

I want to do a simple unit test like this:

package com.scope.mdm;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.scope.mdm.domain.LegalEntityReadOnlyRepository;
import com.scope.mdm.domain.LegalEntityRepository;

import org.junit.jupiter.api.Assertions;

@SpringBootTest(classes = mdmWebAPIApplication.class)
public class legalEntitySearchTest {
    @Autowired
    private LegalEntityRepository repository;
    @Autowired
    private LegalEntityReadOnlyRepository repositoryReadOnly;

    @Test
    public void contextLoads() {
        Assertions.assertNotNull(repositoryReadOnly);
        Assertions.assertNotNull(repository);
    }

}

When running the test from VSCODE I get this error:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
qualifying bean of type
'com.scope.mdm.domain.LegalEntityReadOnlyRepository' available:
expected single matching bean but found 2:
legalEntityRepository,legalEntityReadOnlyRepository

I tried with the @Qualifier annotation to explicitly specify the bean but the result is the same.


问:
JSONDecodeError: Unterminated string starting at: How to find the difference between two lines
I am trying to extract data from the text file written by a location tracking app. Some lines parse perfectly, but then everything comes to a halt with the error json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 317 (char 316)

I tracked down the offending line in the file. That line and the line before (which parses fine) are:

```<code>2020-01-11 05:18:03.000000 {"type":"Feature","geometry":{"type":"Point","coordinates":[-6.242419339685425,53.424301141597915]},"properties":{"motion":[],"speed":-1,"battery_level":0.4000000059604645,"altitude":65,"battery_state":"unplugged","horizontal_accuracy":65,"vertical_accuracy":10,"timestamp":"2020-01-11T05:18:03Z","wifi":""}}
2020-01-11 05:18:17.000000 {"type":"Feature","geometry":{"type":"Point","coordinates":[-6.242454479088605,53.424276709505094]},"properties":{"motion":["stationary"],"speed":-1,"battery_level":0.4000000059604645,"altitude":65,"battery_state":"unplugged","horizontal_accuracy":65,"vertical_accuracy":10,"timestamp":"2020-01-11T05:18:17Z","wifi":"Dublin Airport Free WiFi"}}
</code>```

The code I am using is:

```<code>with open(InputFile, 'r') as f:
    myresponse = f.readlines() # a list of strings

for item in myresponse:
    dataparts = []
    dataparts = item.split(' ') # a list of three elements
    geodata = json.loads(dataparts[2]) # Convert it to a dictionary of 3 elements, strings
</code>```

The error occurs in other files too, and is always at roughly the same point in the line, around the information for WiFi. I have examined the lines as much as possible, looking for invisibles, etc etc and cannot see anything wrong with them.

How can I fix this?

Body:
I am trying to extract data from the text file written by a location tracking app. Some lines parse perfectly, but then everything comes to a halt with the error json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 317 (char 316)

I tracked down the offending line in the file. That line and the line before (which parses fine) are:

2020-01-11 05:18:03.000000 {"type":"Feature","geometry":{"type":"Point","coordinates":[-6.242419339685425,53.424301141597915]},"properties":{"motion":[],"speed":-1,"battery_level":0.4000000059604645,"altitude":65,"battery_state":"unplugged","horizontal_accuracy":65,"vertical_accuracy":10,"timestamp":"2020-01-11T05:18:03Z","wifi":""}}
2020-01-11 05:18:17.000000 {"type":"Feature","geometry":{"type":"Point","coordinates":[-6.242454479088605,53.424276709505094]},"properties":{"motion":["stationary"],"speed":-1,"battery_level":0.4000000059604645,"altitude":65,"battery_state":"unplugged","horizontal_accuracy":65,"vertical_accuracy":10,"timestamp":"2020-01-11T05:18:17Z","wifi":"Dublin Airport Free WiFi"}}

The code I am using is:

with open(InputFile, 'r') as f:
    myresponse = f.readlines() # a list of strings

for item in myresponse:
    dataparts = []
    dataparts = item.split(' ') # a list of three elements
    geodata = json.loads(dataparts[2]) # Convert it to a dictionary of 3 elements, strings

The error occurs in other files too, and is always at roughly the same point in the line, around the information for WiFi. I have examined the lines as much as possible, looking for invisibles, etc etc and cannot see anything wrong with them.

How can I fix this?


问:
Leaflet Library: Map container is being reused by another instance
Initially, for the first time, everything works.
Now if the user enters a valid IP address it works, again and again if the user enters a valid IP address it works.

The problem is if the user entered an invalid IP address(any value other than a valid IP address), It's okay I caught the error but now after this, now if the user enters a valid IP address, the error shows "Uncaught Error: Map container is being reused by another instance"

```<code>const button = document.querySelector(".tracker__search--button");
const searchInput = document.querySelector(".tracker__search--input");
const errorElement = document.querySelector(".tracker__search--error");
const ipField = document.querySelector(".tracker__data--ip");
const locationField = document.querySelector(".tracker__data--location");
const timezoneField = document.querySelector(".tracker__data--timezone");
const ispField = document.querySelector(".tracker__data--isp");

let map;

// (IIFE function) helps to render map and data based on the user's current IP address
const getUserIpAddress = (async function () {
  try {
    const fetchIP = await fetch("https://api.ipify.org/?format=json");
    const userIP = await fetchIP.json();
    renderMap(userIP.ip);
  } catch (error) {
    errorElement.textContent = "Unable to fetch your ip address";
  }
})();

const renderData = function (data) {
  // Destructuring
  const {
    ip,
    location: { city, region, postalCode, timezone },
    isp,
  } = data;

  ipField.textContent = ip;
  locationField.textContent = `${city}, ${region} ${postalCode}`;
  timezoneField.textContent = `UTC ${timezone}`;
  ispField.textContent = isp;
};

const createMap = function (lat, lng) {
  // Initialize Map object
  map = L.map("map", { zoomControl: false }).setView([lat, lng], 13);

  L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
    maxZoom: 19,
  }).addTo(map);
};

const renderMarker = function (lat, lng) {
  const locationIcon = L.icon({
    iconUrl: require("../images/icon-location.svg"),
    iconSize: [36, 48],
  });

  L.marker([lat, lng], {
    icon: locationIcon,
  }).addTo(map);
};

const renderMap = async function (ip) {
  try {
    const fetchUserInfo = await fetch(
      `https://geo.ipify.org/api/v2/country,city?apiKey=at_zhl5fqzTyMPwPPeCqS9cHPq3W1HIJ&ipAddress=${ip}`
    );
    const retrievedData = await fetchUserInfo.json();

    // This function helps to display the retrieved data on the UI
    renderData(retrievedData);

    const {
      location: { lat, lng },
    } = retrievedData;

    // Creates a new map object
    createMap(lat, lng);

    // Add marker on the UI
    renderMarker(lat, lng);
  } catch (error) {
    errorElement.textContent = "Invalid IP address or Domain name";
  }
};

button.addEventListener("click", function (e) {
  // Remove Error element text
  errorElement.textContent = "";

  // Remove map object
  map.remove();

  // render the map
  renderMap(searchInput.value);
});
</code>```

This error happened to a few people here on StackOverflow, but for some reason, the solution provided isn't working for me.

I just want the user to render the map whenever the user enters a valid IP address, even if previously the user entered an invalid IP address.

Project hosted link, it have cross-origin-request problem so open it with chrome

Body:
Initially, for the first time, everything works.
Now if the user enters a valid IP address it works, again and again if the user enters a valid IP address it works.

The problem is if the user entered an invalid IP address(any value other than a valid IP address), It's okay I caught the error but now after this, now if the user enters a valid IP address, the error shows "Uncaught Error: Map container is being reused by another instance"

const button = document.querySelector(".tracker__search--button");
const searchInput = document.querySelector(".tracker__search--input");
const errorElement = document.querySelector(".tracker__search--error");
const ipField = document.querySelector(".tracker__data--ip");
const locationField = document.querySelector(".tracker__data--location");
const timezoneField = document.querySelector(".tracker__data--timezone");
const ispField = document.querySelector(".tracker__data--isp");

let map;

// (IIFE function) helps to render map and data based on the user's current IP address
const getUserIpAddress = (async function () {
  try {
    const fetchIP = await fetch("https://api.ipify.org/?format=json");
    const userIP = await fetchIP.json();
    renderMap(userIP.ip);
  } catch (error) {
    errorElement.textContent = "Unable to fetch your ip address";
  }
})();

const renderData = function (data) {
  // Destructuring
  const {
    ip,
    location: { city, region, postalCode, timezone },
    isp,
  } = data;

  ipField.textContent = ip;
  locationField.textContent = `${city}, ${region} ${postalCode}`;
  timezoneField.textContent = `UTC ${timezone}`;
  ispField.textContent = isp;
};

const createMap = function (lat, lng) {
  // Initialize Map object
  map = L.map("map", { zoomControl: false }).setView([lat, lng], 13);

  L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
    maxZoom: 19,
  }).addTo(map);
};

const renderMarker = function (lat, lng) {
  const locationIcon = L.icon({
    iconUrl: require("../images/icon-location.svg"),
    iconSize: [36, 48],
  });

  L.marker([lat, lng], {
    icon: locationIcon,
  }).addTo(map);
};

const renderMap = async function (ip) {
  try {
    const fetchUserInfo = await fetch(
      `https://geo.ipify.org/api/v2/country,city?apiKey=at_zhl5fqzTyMPwPPeCqS9cHPq3W1HIJ&ipAddress=${ip}`
    );
    const retrievedData = await fetchUserInfo.json();

    // This function helps to display the retrieved data on the UI
    renderData(retrievedData);

    const {
      location: { lat, lng },
    } = retrievedData;

    // Creates a new map object
    createMap(lat, lng);

    // Add marker on the UI
    renderMarker(lat, lng);
  } catch (error) {
    errorElement.textContent = "Invalid IP address or Domain name";
  }
};

button.addEventListener("click", function (e) {
  // Remove Error element text
  errorElement.textContent = "";

  // Remove map object
  map.remove();

  // render the map
  renderMap(searchInput.value);
});

This error happened to a few people here on StackOverflow, but for some reason, the solution provided isn't working for me.

I just want the user to render the map whenever the user enters a valid IP address, even if previously the user entered an invalid IP address.

Project hosted link, it have cross-origin-request problem so open it with chrome


问:
Fastapi webservice responds with 422 response when parsing payload from Jira webhook
I'm building out an automated process, one part involves firing a webhook using Jira Automation when a Jira Service Management ticket is created. On creation a Jira automation rule is in place to send a webhook to a fastapi webservice I have created. I'm new to fastapi (have used flask previously) so I think I may be getting something wrong with Response Models.

The issue I'm having is the fastapi service returns 422 Unprocessable Entity when receiving the payload from Jira. I narrowed it down to be the description field and built out a super stripped down fastapi webservice to debug this further, running it with uvicorn main:app --reload. Here's the full code:

```<code>from fastapi import FastAPI, Request
from pydantic import BaseModel

app = FastAPI()

class Data(BaseModel):
    description: str

@app.post("/desc")
def read_desc(data: Data):
    webhook = data
    print(webhook)
    return {"Data": webhook}
</code>```

The details of the request that comes from Jira are as follows:

Request

POST
https://random-ngrok-url/desc

Headers

Accept: */*

Content-Type: application/json

Payload

{ "description" : "Application review requested |Project link|https://develop.test.com/app/dashboard/| |User name|MTest| |User e-mail|test@test.com| |SDK version|SDK_V2| 1234 " }

Response

422 Unprocessable Entity

Content-Length: 417

Content-Type: application/json

Date: Wed, 14 Dec 2022 13:09:55 GMT

Ngrok-Trace-Id: random-ngrok-trace-id

Server: uvicorn

Payload

```<code>{
  "detail": [
    {
      "loc": [
        "body",
        47
      ],
      "msg": "Invalid control character at: line 2 column 46 (char 47)",
      "type": "value_error.jsondecode",
      "ctx": {
        "msg": "Invalid control character at",
        "doc": "{\n\"description\" : \"Application review requested\n|Project link|https://develop.test.com/app/dashboard/|\n|User name|MTest|\n|User e-mail|test@test.com|\n|SDK version|SDK_V2|\n\n1234\n\"\n}",
        "pos": 47,
        "lineno": 2,
        "colno": 46
      }
    }
  ]
}
</code>```

I feel like there's some encoding or editing being made to the request from Jira, but I can't figure out what. Position 47 just appears to be a standard character?

Note: it works with other fields in the Jira tickets, with the payload being like this:

```<code>{
  "summary": "Review Application Test"
}
</code>```

Other things to note

If I perform this exact request from postman the fastapi service responds as expected with 200 returning the description.

Here's the curl output from postman of such a successful request.

```<code>curl --location --request POST 'https://random-ngrok-url/desc' \
--header 'Content-Type: application/json' \
--data-raw '{ "description" : "Application review requested |Project link|https://develop.test.com/app/dashboard/| |User name|MTest| |User e-mail|test@test.com| |SDK version|SDK_V2| 1234 " }'
</code>```

I also did a test by sending the request from Jira to a request inspector and saw the following request details:

```<code>POST /inspect/from-jira HTTP/1.1
requestinspector.com
User-Agent: Automation for Jira AC app/1.0
Accept-Encoding: gzip
Accept: */*
Content-Type: application/json
Content-Length: 190
</code>```

With the payload body being:

```<code>{
"description" : "Application review requested
|Project link|https://develop.test.com/app/dashboard/|
|User name|MTest|
|User e-mail|mtest@test.com|
|SDK version|SDK_V2|

1234
"
}
</code>```

From Postman it's

```<code>POST /inspect/from-postman HTTP/1.1
requestinspector.com
User-Agent: PostmanRuntime/7.29.2
Content-Type: application/json
Content-Length: 189
Accept: */*
Accept-Encoding: gzip
Postman-Token: random-postman-token
</code>```

payload body:

```<code>{ "description" : "Application review requested |Project link|https://develop.test.com/app/dashboard/| |User name|MTest| |User e-mail|test@test.com| |SDK version|SDK_V2| 1234 " }
</code>```

Body:
I'm building out an automated process, one part involves firing a webhook using Jira Automation when a Jira Service Management ticket is created. On creation a Jira automation rule is in place to send a webhook to a fastapi webservice I have created. I'm new to fastapi (have used flask previously) so I think I may be getting something wrong with Response Models.

The issue I'm having is the fastapi service returns 422 Unprocessable Entity when receiving the payload from Jira. I narrowed it down to be the description field and built out a super stripped down fastapi webservice to debug this further, running it with uvicorn main:app --reload. Here's the full code:

from fastapi import FastAPI, Request
from pydantic import BaseModel

app = FastAPI()

class Data(BaseModel):
    description: str

@app.post("/desc")
def read_desc(data: Data):
    webhook = data
    print(webhook)
    return {"Data": webhook}

The details of the request that comes from Jira are as follows:

Request

POST
https://random-ngrok-url/desc

Headers

Accept: */*

Content-Type: application/json

Payload

{ "description" : "Application review requested |Project link|https://develop.test.com/app/dashboard/| |User name|MTest| |User e-mail|test@test.com| |SDK version|SDK_V2| 1234 " }

Response

422 Unprocessable Entity

Content-Length: 417

Content-Type: application/json

Date: Wed, 14 Dec 2022 13:09:55 GMT

Ngrok-Trace-Id: random-ngrok-trace-id

Server: uvicorn

Payload

{
  "detail": [
    {
      "loc": [
        "body",
        47
      ],
      "msg": "Invalid control character at: line 2 column 46 (char 47)",
      "type": "value_error.jsondecode",
      "ctx": {
        "msg": "Invalid control character at",
        "doc": "{\n\"description\" : \"Application review requested\n|Project link|https://develop.test.com/app/dashboard/|\n|User name|MTest|\n|User e-mail|test@test.com|\n|SDK version|SDK_V2|\n\n1234\n\"\n}",
        "pos": 47,
        "lineno": 2,
        "colno": 46
      }
    }
  ]
}

I feel like there's some encoding or editing being made to the request from Jira, but I can't figure out what. Position 47 just appears to be a standard character?

Note: it works with other fields in the Jira tickets, with the payload being like this:

{
  "summary": "Review Application Test"
}

Other things to note

If I perform this exact request from postman the fastapi service responds as expected with 200 returning the description.

Here's the curl output from postman of such a successful request.

curl --location --request POST 'https://random-ngrok-url/desc' \
--header 'Content-Type: application/json' \
--data-raw '{ "description" : "Application review requested |Project link|https://develop.test.com/app/dashboard/| |User name|MTest| |User e-mail|test@test.com| |SDK version|SDK_V2| 1234 " }'

I also did a test by sending the request from Jira to a request inspector and saw the following request details:

POST /inspect/from-jira HTTP/1.1
requestinspector.com
User-Agent: Automation for Jira AC app/1.0
Accept-Encoding: gzip
Accept: */*
Content-Type: application/json
Content-Length: 190

With the payload body being:

{
"description" : "Application review requested
|Project link|https://develop.test.com/app/dashboard/|
|User name|MTest|
|User e-mail|mtest@test.com|
|SDK version|SDK_V2|

1234
"
}

From Postman it's

POST /inspect/from-postman HTTP/1.1
requestinspector.com
User-Agent: PostmanRuntime/7.29.2
Content-Type: application/json
Content-Length: 189
Accept: */*
Accept-Encoding: gzip
Postman-Token: random-postman-token

payload body:

{ "description" : "Application review requested |Project link|https://develop.test.com/app/dashboard/| |User name|MTest| |User e-mail|test@test.com| |SDK version|SDK_V2| 1234 " }


问:
using open-source code under the apache license
Im using part of the rootbeer source-code to determine if the user OS is rooted or not.

I overlooked the license, and it says i have to give credit to the original authors.
Does this mean commenting on top where i got the code from and who the authors are or what?
Can I just use part of the code and go on with my life?

I dont understand this, how am I supposed to give credit to the authors? My project manager said that this is a problem, I dont understand how is this a problem?


问:
How do I update my X axis header title on highcharts?
I am using Datatables to create Highcharts. Everything functions as intended, however I am not sure how to extract the X axis title from Column 1. (Data1, Data2, Data3, Data4, Data5 etc.). I am not sure what am I missing in my code. Any advice would be appreciated because I don't know much about Javascript. Thanks in advance.

The chart should look like this.
See screenshot below.

Link to code - http://live.datatables.net/muvoyacu/2/edit

$(document).ready(function() {
    var table = $("#example_full2").DataTable({
  searching:false,
lengthChange: false,
ordering: false,
info: false,
paging: false,

} );

    //var salary = getSalaries(table);

    var salary = getRow(table,0);
var salary2 = getRow(table, 1);
 var salary3 = getRow(table, 2);
  var salary4 = getRow(table, 3);
  var salary5 = getRow(table, 4);

    // Declare axis for the column graph
    var axis = {
        id: "salary",
        min: 0,
        title: {
            text: "Number"
        }
    };

    // Declare inital series with the values from the getSalaries function
   var series = {
name: "2012",
data: Object.values(salary)
};
var series2 = {
name: "2013",
data: Object.values(salary2)
};
  var series3 = {
name: "2014",
data: Object.values(salary3)
};
  var series4 = {
name: "2015",
data: Object.values(salary4)
};
    var series5 = {
name: "2016",
data: Object.values(salary5)
};

   var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: Object.keys(salary)
},
yAxis: axis,
series: [series, series2, series3, series4, series5]

});

// On draw, get updated salaries and refresh axis and series
table.on("draw", function() {
salary = getSalaries(table);
myChart.axes[0].categories = Object.keys(salary);
myChart.series[0].setData(Object.values(salary));
});
});

function getSalaries(table) {
var salaryCounts = {};
var salary = {};

}

function getRow(table, row) {
var chart = {};
var data = table.row(row).data();

for (i=1; i<data.length; i++) {
var x = $( table.column( i ).header() ).html();
var y = data[i].replace(/[^0-9.]/g, "") * 1;

chart[x] = y;
}
return chart;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
 <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
    <meta charset=utf-8 />

  </head>
  <body>

<div id="container" style=" width: 100%; height: 400px;"></div>

<div class="container">
<table id="example_full2" class="display nowrap" width="100%"><thead>
<tr><th>Year</th><th>2012</th><th>2013</th><th>2014</th><th>2015</th><th>2016</th><th>2017</th><th>2018</th><th>2019</th><th>2020</th><th>2021</th></tr></thead>

 <tr ><td> Data1</td><td>3,823</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
   <tr ><td> Data2</td><td>800</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
   <tr ><td> Data3</td><td>900</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
   <tr ><td> Data4</td><td>200</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
   <tr ><td> Data5</td><td>300</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
   <tr ><td> Data6</td><td>400</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
  </tbody></table></code>```

Body:
I am using Datatables to create Highcharts. Everything functions as intended, however I am not sure how to extract the X axis title from Column 1. (Data1, Data2, Data3, Data4, Data5 etc.). I am not sure what am I missing in my code. Any advice would be appreciated because I don't know much about Javascript. Thanks in advance.

The chart should look like this.
See screenshot below.

Link to code - http://live.datatables.net/muvoyacu/2/edit

$(document).ready(function() {
    var table = $("#example_full2").DataTable({
  searching:false,
lengthChange: false,
ordering: false,
info: false,
paging: false,

} );

    //var salary = getSalaries(table);

    var salary = getRow(table,0);
var salary2 = getRow(table, 1);
 var salary3 = getRow(table, 2);
  var salary4 = getRow(table, 3);
  var salary5 = getRow(table, 4);

    // Declare axis for the column graph
    var axis = {
        id: "salary",
        min: 0,
        title: {
            text: "Number"
        }
    };

    // Declare inital series with the values from the getSalaries function
   var series = {
name: "2012",
data: Object.values(salary)
};
var series2 = {
name: "2013",
data: Object.values(salary2)
};
  var series3 = {
name: "2014",
data: Object.values(salary3)
};
  var series4 = {
name: "2015",
data: Object.values(salary4)
};
    var series5 = {
name: "2016",
data: Object.values(salary5)
};

   var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: Object.keys(salary)
},
yAxis: axis,
series: [series, series2, series3, series4, series5]

});

// On draw, get updated salaries and refresh axis and series
table.on("draw", function() {
salary = getSalaries(table);
myChart.axes[0].categories = Object.keys(salary);
myChart.series[0].setData(Object.values(salary));
});
});

function getSalaries(table) {
var salaryCounts = {};
var salary = {};

}

function getRow(table, row) {
var chart = {};
var data = table.row(row).data();

for (i=1; i<data.length; i++) {
var x = $( table.column( i ).header() ).html();
var y = data[i].replace(/[^0-9.]/g, "") * 1;

chart[x] = y;
}
return chart;
}

<!DOCTYPE html>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />

    <meta charset=utf-8 />

Year	2012	2013	2014	2015	2016	2017	2018	2019	2020	2021

 Data1	3,823	3,823	3,954	3,959	3,955	3,956	3,843	3,699	3,472	3,551

 Data2	800	3,823	3,954	3,959	3,955	3,956	3,843	3,699	3,472	3,551

 Data3	900	3,823	3,954	3,959	3,955	3,956	3,843	3,699	3,472	3,551

 Data4	200	3,823	3,954	3,959	3,955	3,956	3,843	3,699	3,472	3,551

 Data5	300	3,823	3,954	3,959	3,955	3,956	3,843	3,699	3,472	3,551

 Data6	400	3,823	3,954	3,959	3,955	3,956	3,843	3,699	3,472	3,551


问:
How to create a DataStore?
```<code>local DataStoreService = game:GetService('DataStoreService')
local playerData = DataStoreService:GetDataStore('PlayerData')

-- Erstellt Leaderboard
local function onPlayerJoin(player)

    local leaderstats = Instance.new('Folder')
    leaderstats.Name = 'leaderstats'
    leaderstats.Parent = player

    local clicks = Instance.new('IntValue')
    clicks.Name = 'Clicks'
    clicks.Value = 0
    clicks.Parent = leaderstats

    local rebirths = Instance.new('IntValue')
    rebirths.Name = 'Rebirths'
    rebirths.Value = 0
    rebirths.Parent = leaderstats

    -- Wenn ein Nutzer verlassen hat das die daten gespeichert wurden
    local playerUserId = 'Player_'..player.UserId
    local data = playerData:GetAsync(playerUserId)
    if data then
        clicks.Value = data['Clicks']
        rebirths.Value = data['Rebirths']
    else  -- Wenn user das erste mal joint das value 0 ist
        clicks.Value = 0
        rebirths.Value = 0
    end
end

local function create_table(player)
    local player_stats = {}
    for _, stat in pairs(player.leaderstats:GetChildren()) do
        player_stats[stat.Name] = stat.Value
    end
    return player_stats
end

local function onPlayerExit(player)
    local player_stats = create_table(player)
    local success, err = pcall(function ()
        local playerUserId = 'Player_'..player.UserId
        playerData:SetAsync(playerUserId, player_stats)
    end)

    if not success then
        warn('Could not save data')
    end
end

game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)
</code>```

I tried to make a DataStore that stores the values of the leaderboard into a data that returns everytime if i rejoin. But it doesnt work and idk why. Im kinda new into lua programming but u guys can help me :D thanks.

Title: How to create a DataStore?

Body:
local DataStoreService = game:GetService('DataStoreService')
local playerData = DataStoreService:GetDataStore('PlayerData')

-- Erstellt Leaderboard
local function onPlayerJoin(player)

    local leaderstats = Instance.new('Folder')
    leaderstats.Name = 'leaderstats'
    leaderstats.Parent = player

    local clicks = Instance.new('IntValue')
    clicks.Name = 'Clicks'
    clicks.Value = 0
    clicks.Parent = leaderstats

    local rebirths = Instance.new('IntValue')
    rebirths.Name = 'Rebirths'
    rebirths.Value = 0
    rebirths.Parent = leaderstats

    -- Wenn ein Nutzer verlassen hat das die daten gespeichert wurden
    local playerUserId = 'Player_'..player.UserId
    local data = playerData:GetAsync(playerUserId)
    if data then
        clicks.Value = data['Clicks']
        rebirths.Value = data['Rebirths']
    else  -- Wenn user das erste mal joint das value 0 ist
        clicks.Value = 0
        rebirths.Value = 0
    end
end

local function create_table(player)
    local player_stats = {}
    for _, stat in pairs(player.leaderstats:GetChildren()) do
        player_stats[stat.Name] = stat.Value
    end
    return player_stats
end

local function onPlayerExit(player)
    local player_stats = create_table(player)
    local success, err = pcall(function ()
        local playerUserId = 'Player_'..player.UserId
        playerData:SetAsync(playerUserId, player_stats)
    end)

    if not success then
        warn('Could not save data')
    end
end

game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)

I tried to make a DataStore that stores the values of the leaderboard into a data that returns everytime if i rejoin. But it doesnt work and idk why. Im kinda new into lua programming but u guys can help me :D thanks.


问:
mongoose app crashing giving const err = new MongooseError(message);
i m writing code for a basic node js api and connecting to mongodb from mongoose to test if the data base is geting created and it keeps giving me this err

this is the code

```<code>const express = require('express')
const mongoose = require("mongoose")
const app = express()
const port = 3000

// mongoose.set('strictQuery', true);
// mongoose.connect('mongodb://localhost:27017/tst',()=> console.log("db connected"));
const conn = mongoose.connect('mongodb://localhost:27017/test')
conn.readyState;

const aviSchema = new mongoose.Schema({
  name : String,
  awsLink : String
})

const avi = mongoose.model("avi",aviSchema)

const Avi = new avi({
  name:"zahab",
  awsLink:"aws"
})
Avi.save()

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
</code>```

this is the err
const err = new MongooseError(message);
^

```<code>MongooseError: Operation `avis.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Users\as comp\Desktop\node aws check\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158:23)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

Node.js v18.12.1
</code>```

Body:
i m writing code for a basic node js api and connecting to mongodb from mongoose to test if the data base is geting created and it keeps giving me this err

this is the code

const express = require('express')
const mongoose = require("mongoose")
const app = express()
const port = 3000

// mongoose.set('strictQuery', true);
// mongoose.connect('mongodb://localhost:27017/tst',()=> console.log("db connected"));
const conn = mongoose.connect('mongodb://localhost:27017/test')
conn.readyState;

const aviSchema = new mongoose.Schema({
  name : String,
  awsLink : String
})

const avi = mongoose.model("avi",aviSchema)

const Avi = new avi({
  name:"zahab",
  awsLink:"aws"
})
Avi.save()

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

this is the err
const err = new MongooseError(message);
^

MongooseError: Operation `avis.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Users\as comp\Desktop\node aws check\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158:23)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

Node.js v18.12.1


问:
Alter composite type that used in column as array of composite type
I have composite type in postgres

```<code>composite_type(numeric(10, 2), numeric(10, 3))
</code>```

Table example

id(serial)
comp(composite_type[])

...
...

I need to alter first attribute to numeric(12, 2). If I try to alter type manually, i have error:

```<code>Type can't be alter because it used in column
</code>```

How I can alter this type without data loss?

P.S. I use doctrine and symfony

I try to alter type as in documentation

May be I need to create new type, then cast my column to it and then delete old type and rename new, but I don't know how to cast array of composite type.

Body:
I have composite type in postgres

composite_type(numeric(10, 2), numeric(10, 3))

Table example

id(serial)
comp(composite_type[])

...
...

I need to alter first attribute to numeric(12, 2). If I try to alter type manually, i have error:

Type can't be alter because it used in column

How I can alter this type without data loss?

P.S. I use doctrine and symfony

I try to alter type as in documentation

May be I need to create new type, then cast my column to it and then delete old type and rename new, but I don't know how to cast array of composite type.


问:
"pinentry did not return a PID" on gpg4win
I'm using Gpg4win-4.0.4 and a smartcard with PIN. It used to work well, but I think due to a windows update, pinentry no longer works:

```<code>2022-12-14 22:03:09 gpg-agent[11500] starting a new PIN Entry
2022-12-14 22:03:09 gpg-agent[11500] DBG: connection to PIN entry established
2022-12-14 22:03:09 gpg-agent[11500] pinentry did not return a PID
2022-12-14 22:03:10 gpg-agent[11500] DBG: error calling pinentry: Operation cancelled <Pinentry>
</code>```

I've tried the one that comes with Gpg4win and a custom one, both of them give the same error. I've also tried re-installing gpg, which doesn't work either.

Any ideas?

Body:
I'm using Gpg4win-4.0.4 and a smartcard with PIN. It used to work well, but I think due to a windows update, pinentry no longer works:

2022-12-14 22:03:09 gpg-agent[11500] starting a new PIN Entry
2022-12-14 22:03:09 gpg-agent[11500] DBG: connection to PIN entry established
2022-12-14 22:03:09 gpg-agent[11500] pinentry did not return a PID
2022-12-14 22:03:10 gpg-agent[11500] DBG: error calling pinentry: Operation cancelled <Pinentry>

I've tried the one that comes with Gpg4win and a custom one, both of them give the same error. I've also tried re-installing gpg, which doesn't work either.

Any ideas?


问:
SGX psw faced issue
I am installing SGX psw when I run make psw I get error

```<code> error: ‘SGX_XFRM_PKRU’ was not declared in this scope; did you mean ‘SGX_XFRM_AVX’?
  121 |         se_misc_attr->secs_attr.xfrm &= ~(SGX_XFRM_PKRU);
</code>```

I have to mention that I have run source /opt/intel/sgxsdk/environment after installing SGX sdk.

Title: SGX psw faced issue

Body:
I am installing SGX psw when I run make psw I get error

 error: ‘SGX_XFRM_PKRU’ was not declared in this scope; did you mean ‘SGX_XFRM_AVX’?
  121 |         se_misc_attr->secs_attr.xfrm &= ~(SGX_XFRM_PKRU);

I have to mention that I have run source /opt/intel/sgxsdk/environment after installing SGX sdk.


问:
In Runbook Automation the IP Address are in dynamic nature need to whitelist the IP's
In Runbook Automation the IP Address are in dynamic nature need to whitelist the IP's.

I tried whitelisting the IP that i get in the error message but it seems this IP is dynamic in nature and changes very frequently. Hence my solution is breaking.

How to whitelist Dynamic IP address for Runbook In automation


问:
Why is bundle received from Firebase Clound Messaging notification empty?
With many of our customers, especially on Xiaomi and Huawei devices, we see an 'empty' Bundle after the FCM notification is tapped by the user.
The problem is not reproducible for us.

We have a straight-forward implementation of FCM in our Android application. The app is pure Kotlin and we're using this FCM dependency:

```<code>com.google.firebase:firebase-messaging-ktx:23.0.3
</code>```

(latest is 23.1.1).

Out backend sends the data for a notification to FCM.
The notification appears properly on the user's device. This works regardless the app is in foreground or background.

With many of our customers, especially on Xiaomi and Huawei devices, we see an 'empty' Bundle after the notification is tapped by the user.
We retrieve the Bundle in our Activity like this:

```<code>override fun onCreate(...) {
    ...
    intent.extras?.let {
        val value = it.getString("ourKey")
        // Proceed with value ...
    }
    ...
}
</code>```

The Bundle 'it' in the let block looks like this in our customer's app:

Bundle[{profile=UserHandle{0}}]

Bundle[{startFromLauncher=shortcut}]

Bundle[{user=0}]

When we test the app, the Bundle looks like this:
Bundle[{mobileservices.notificationId=881832c4-5d9d-4489-a33f-3d2c742b5266, google.delivered_priority=normal, google.sent_time=1661335657647, google.ttl=2419200, google.original_priority=normal, gcm.notification.e=1, gcm.n.dnp=1, gcm.notification.sound=default, gcm.notification.title=Titel, data={ourKey="...", ...}, from=751691358542, gcm.notification.sound2=sound, alert={"title" : "Title", "body":"Message"} ... ]

Does anyone have an idea what might be the reason for these 'empty' Bundles?

Body:
With many of our customers, especially on Xiaomi and Huawei devices, we see an 'empty' Bundle after the FCM notification is tapped by the user.
The problem is not reproducible for us.

We have a straight-forward implementation of FCM in our Android application. The app is pure Kotlin and we're using this FCM dependency:

com.google.firebase:firebase-messaging-ktx:23.0.3

(latest is 23.1.1).

Out backend sends the data for a notification to FCM.
The notification appears properly on the user's device. This works regardless the app is in foreground or background.

With many of our customers, especially on Xiaomi and Huawei devices, we see an 'empty' Bundle after the notification is tapped by the user.
We retrieve the Bundle in our Activity like this:

override fun onCreate(...) {
    ...
    intent.extras?.let {
        val value = it.getString("ourKey")
        // Proceed with value ...
    }
    ...
}

The Bundle 'it' in the let block looks like this in our customer's app:

Bundle[{profile=UserHandle{0}}]

Bundle[{startFromLauncher=shortcut}]

Bundle[{user=0}]

When we test the app, the Bundle looks like this:
Bundle[{mobileservices.notificationId=881832c4-5d9d-4489-a33f-3d2c742b5266, google.delivered_priority=normal, google.sent_time=1661335657647, google.ttl=2419200, google.original_priority=normal, gcm.notification.e=1, gcm.n.dnp=1, gcm.notification.sound=default, gcm.notification.title=Titel, data={ourKey="...", ...}, from=751691358542, gcm.notification.sound2=sound, alert={"title" : "Title", "body":"Message"} ... ]

Does anyone have an idea what might be the reason for these 'empty' Bundles?


问:
Joining Two Tables in BigQuery Without Common Column and Different Amount of Rows
I'm trying to create a table in BigQuery by joining two tables without a common column and differing row totals. Please help me update the query below or let me know if the logic doesn't make sense.

Table 1 = 180M rows
Table 2 = 65M rows

```<code>CREATE OR REPLACE TABLE `myproject.mydataset_joinedtable` AS
(SELECT
t1.column1 AS column1
t2.column2 AS column2
t1.column3 AS column3
t1.column4 AS column4

FROM `myproject.mydataset_table1` t1,`myproject.mydataset_table2` t2):
</code>```

Body:
I'm trying to create a table in BigQuery by joining two tables without a common column and differing row totals. Please help me update the query below or let me know if the logic doesn't make sense.

Table 1 = 180M rows
Table 2 = 65M rows

CREATE OR REPLACE TABLE `myproject.mydataset_joinedtable` AS
(SELECT
t1.column1 AS column1
t2.column2 AS column2
t1.column3 AS column3
t1.column4 AS column4

FROM `myproject.mydataset_table1` t1,`myproject.mydataset_table2` t2):


问:
How to find databricks cluster owner has permission for secrets?
i am facing below error while executing databricks notebook.

```<code>INVALID_ARGUMENT(CLIENT_ERROR): databricks_error_message:Cannot fetch secrets referred in the Spark configuration. Please check that the secrets exists and the cluster's owner has the read permission.
</code>```

i know below cmd will give permission details for the user but i don't know how to get cluster's owner details. and the cluster creator has already access to the cluster.

```<code>>>databricks secrets get-acl --scope scope_name --principal username
</code>```

how to check the databricks cluster's owner details and resolve this issue?

i have granted access to cluster created but still facing same error.

Body:
i am facing below error while executing databricks notebook.

INVALID_ARGUMENT(CLIENT_ERROR): databricks_error_message:Cannot fetch secrets referred in the Spark configuration. Please check that the secrets exists and the cluster's owner has the read permission.

i know below cmd will give permission details for the user but i don't know how to get cluster's owner details. and the cluster creator has already access to the cluster.

>>databricks secrets get-acl --scope scope_name --principal username

how to check the databricks cluster's owner details and resolve this issue?

i have granted access to cluster created but still facing same error.


问:
Mappings field empty in elasticsearch
I am trying to create elasticsearch index using Java API  ,
if we see below index mappings filed is coming as empty .

```<code># curl -XGET localhost:9200/initest2
{"initest2":{"aliases":{},**"mappings":{}**,"settings":{"index":{"keyspace":"keyspace_test","number_of_shards":"5","provided_name":"initest2","max_result_window":"10000000","creation_date":"1671025346350","analysis":{"normalizer":{"testnormalizer":{"filter":["asciifolding"],"type":"custom","char_filter":[]}}},"number_of_replicas":"0","uuid":"BK9oTTKETZeWqiuR_tGd8w","version":{"created":"6080499"}}}}}
</code>```

JAVA code :

```<code>String indexQuery = "";
        StringBuilder indexString = new StringBuilder("");
        String test = "{\"settings\": {\"max_result_window\":10000000,\"keyspace\":\""+keyspaceName+'\u0022' +",\"analysis\": "
                + "{\"normalizer\":{\"testnormalizer\": {\"type\": \"custom\",\"char_filter\": [],\"filter\": [\"asciifolding\"]}}}},"
                + "\"mappings\":{\""+tableName+"\":{\"discover\" : \".*\",\"properties\":{";
        indexString.append(test);

        for (String i : indexColumns)
        {
            indexString.append('\u0022'+i+'\u0022' +":" +"{ \"type\": \"keyword\",\"normalizer\": \"testnormalizer\"}" + ",");

        }
        indexString.delete(indexString.length()-1, indexString.length()).append("}}}}");

        indexQuery = indexString.toString();
        logger.info("index query is " + indexQuery);
        CreateIndexRequest request = new CreateIndexRequest(tableName);
        request.source(indexQuery, XContentType.JSON);

        CreateIndexResponse createIndexResponse= restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
</code>```

while printing the query before calling restHighLevel client :

index query is

```<code>{"settings": {"max_result_window":10000000,"keyspace":"ndl","analysis": {"normalizer":{"testnormalizer": {"type": "custom","char_filter": [],"filter": ["asciifolding"]}}}},"mappings":{"initest2":{"discover" : ".*","properties":{"name":{ "type": "keyword","normalizer": "testnormalizer"}}}}}
</code>```

Please assist if any method to be updated in java code / any properties to be updated in elassandra

Current versrion of elasticsearch : 6.8.4

Note : tried using request.settings() & request.mappings() but it didnt help

Title: Mappings field empty in elasticsearch

Body:
I am trying to create elasticsearch index using Java API  ,
if we see below index mappings filed is coming as empty .

# curl -XGET localhost:9200/initest2
{"initest2":{"aliases":{},**"mappings":{}**,"settings":{"index":{"keyspace":"keyspace_test","number_of_shards":"5","provided_name":"initest2","max_result_window":"10000000","creation_date":"1671025346350","analysis":{"normalizer":{"testnormalizer":{"filter":["asciifolding"],"type":"custom","char_filter":[]}}},"number_of_replicas":"0","uuid":"BK9oTTKETZeWqiuR_tGd8w","version":{"created":"6080499"}}}}}

JAVA code :

String indexQuery = "";
        StringBuilder indexString = new StringBuilder("");
        String test = "{\"settings\": {\"max_result_window\":10000000,\"keyspace\":\""+keyspaceName+'\u0022' +",\"analysis\": "
                + "{\"normalizer\":{\"testnormalizer\": {\"type\": \"custom\",\"char_filter\": [],\"filter\": [\"asciifolding\"]}}}},"
                + "\"mappings\":{\""+tableName+"\":{\"discover\" : \".*\",\"properties\":{";
        indexString.append(test);

        for (String i : indexColumns)
        {
            indexString.append('\u0022'+i+'\u0022' +":" +"{ \"type\": \"keyword\",\"normalizer\": \"testnormalizer\"}" + ",");

        }
        indexString.delete(indexString.length()-1, indexString.length()).append("}}}}");

        indexQuery = indexString.toString();
        logger.info("index query is " + indexQuery);
        CreateIndexRequest request = new CreateIndexRequest(tableName);
        request.source(indexQuery, XContentType.JSON);

        CreateIndexResponse createIndexResponse= restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);

while printing the query before calling restHighLevel client :

index query is

{"settings": {"max_result_window":10000000,"keyspace":"ndl","analysis": {"normalizer":{"testnormalizer": {"type": "custom","char_filter": [],"filter": ["asciifolding"]}}}},"mappings":{"initest2":{"discover" : ".*","properties":{"name":{ "type": "keyword","normalizer": "testnormalizer"}}}}}

Please assist if any method to be updated in java code / any properties to be updated in elassandra

Current versrion of elasticsearch : 6.8.4

Note : tried using request.settings() & request.mappings() but it didnt help


问:
setAttribute doesn't affect input element. Even though if I put the value manually it works, but block the input
I wrote a calculator on pure JS using DOM. And the problem I've faced was that if I input an expression using buttons and push "=" button, everything works great. I mean the expression is being replaced by result. But if I paste expression to input using CTRL-V, then nothing happens. Expression remains in input form and is not replaced by result. Even though I can console the result.
Here's the code

```<code>class Calculator extends HTMLElement {
  constructor() {
    super()
    this.defaultValue = 0
    this.root = document.getElementById('root')
    this.calcContainer = document.createElement('div')
    this.calcContainer.setAttribute('class', 'calculator card border border-dark')
    this.root.appendChild(this.calcContainer)

    this.addInput()

    this.onClickButton = (e, button) => {
      e.preventDefault()
      const newValue =
        this.input.value == this.defaultValue ? button : `${this.input.value}${button}`
      this.input.setAttribute('value', newValue)
    }
    this.addSpecialSymbols()
    this.addNumbers()
    this.addOperators()
  }

  addInput() {
    let value = this.defaultValue
    this.input = document.createElement('input')
    this.input.setAttribute('value', value)
    this.calcContainer.appendChild(this.input)
  }
  addSpecialSymbols() {
    specialSymbolsArr.map((item) => {
      const button = document.createElement('button')
      const { className, innerHtml, action } = item
      button.setAttribute('class', className)
      button.innerHTML = innerHtml
      button.addEventListener('click', action.bind(this))
      this.calcContainer.appendChild(button)
    })
  }
  addNumbers() {
    const numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    numbers.forEach((num) => {
      const button = document.createElement('button')
      button.innerText = num
      button.setAttribute('type', 'button')
      button.setAttribute('class', 'btn btn-outline-info')
      if (num === 0) {
        button.setAttribute('class', 'zero btn btn-outline-secondary')
      }
      button.addEventListener('click', (e) => {
        this.onClickButton(e, num)
      })
      this.calcContainer.appendChild(button)
    })
  }

  addOperators() {
    ids.forEach((id) => {
      const button = document.createElement('button')
      const { className, innerHtml, operator } = entities[id]

      button.innerHTML = innerHtml
      button.setAttribute('type', 'button')
      button.setAttribute('class', className)

      if (operator !== '=') {
        button.addEventListener('click', (e) => {
          this.onClickButton(e, operator)
        })
      } else {
        button.addEventListener('click', () => {
          console.log(this.input.value)
          this.input.setAttribute('value', `${getResult(this.input.value)}`)
          // this.input.value = getResult(this.input.value)
          console.log(this.input.value)
        })
      }

      this.calcContainer.appendChild(button)
    })
  }
}
</code>```

In this part of code I logged values of input and it showed expression both times. Even though setAttribute had to change expression for result.

```<code>          console.log(this.input.value)
          this.input.setAttribute('value', `${getResult(this.input.value)}`)
          console.log(this.input.value)
        })
</code>```

If I change initialisation of value manually then it works fine. But afterwards inout becomes 'blocked', buttons doesn't affect input.

```<code>button.addEventListener('click', () => {
          console.log(this.input.value)
          this.input.value = getResult(this.input.value)
          console.log(this.input.value)
        })
</code>```

I guess this is conflict of setAttribute method and initialisation of of input value by browser while pasting something to input. Could somebody help please to solve this problem?

Body:
I wrote a calculator on pure JS using DOM. And the problem I've faced was that if I input an expression using buttons and push "=" button, everything works great. I mean the expression is being replaced by result. But if I paste expression to input using CTRL-V, then nothing happens. Expression remains in input form and is not replaced by result. Even though I can console the result.
Here's the code

class Calculator extends HTMLElement {
  constructor() {
    super()
    this.defaultValue = 0
    this.root = document.getElementById('root')
    this.calcContainer = document.createElement('div')
    this.calcContainer.setAttribute('class', 'calculator card border border-dark')
    this.root.appendChild(this.calcContainer)

    this.addInput()

    this.onClickButton = (e, button) => {
      e.preventDefault()
      const newValue =
        this.input.value == this.defaultValue ? button : `${this.input.value}${button}`
      this.input.setAttribute('value', newValue)
    }
    this.addSpecialSymbols()
    this.addNumbers()
    this.addOperators()
  }

  addInput() {
    let value = this.defaultValue
    this.input = document.createElement('input')
    this.input.setAttribute('value', value)
    this.calcContainer.appendChild(this.input)
  }
  addSpecialSymbols() {
    specialSymbolsArr.map((item) => {
      const button = document.createElement('button')
      const { className, innerHtml, action } = item
      button.setAttribute('class', className)
      button.innerHTML = innerHtml
      button.addEventListener('click', action.bind(this))
      this.calcContainer.appendChild(button)
    })
  }
  addNumbers() {
    const numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    numbers.forEach((num) => {
      const button = document.createElement('button')
      button.innerText = num
      button.setAttribute('type', 'button')
      button.setAttribute('class', 'btn btn-outline-info')
      if (num === 0) {
        button.setAttribute('class', 'zero btn btn-outline-secondary')
      }
      button.addEventListener('click', (e) => {
        this.onClickButton(e, num)
      })
      this.calcContainer.appendChild(button)
    })
  }

  addOperators() {
    ids.forEach((id) => {
      const button = document.createElement('button')
      const { className, innerHtml, operator } = entities[id]

      button.innerHTML = innerHtml
      button.setAttribute('type', 'button')
      button.setAttribute('class', className)

      if (operator !== '=') {
        button.addEventListener('click', (e) => {
          this.onClickButton(e, operator)
        })
      } else {
        button.addEventListener('click', () => {
          console.log(this.input.value)
          this.input.setAttribute('value', `${getResult(this.input.value)}`)
          // this.input.value = getResult(this.input.value)
          console.log(this.input.value)
        })
      }

      this.calcContainer.appendChild(button)
    })
  }
}

In this part of code I logged values of input and it showed expression both times. Even though setAttribute had to change expression for result.

          console.log(this.input.value)
          this.input.setAttribute('value', `${getResult(this.input.value)}`)
          console.log(this.input.value)
        })

If I change initialisation of value manually then it works fine. But afterwards inout becomes 'blocked', buttons doesn't affect input.

button.addEventListener('click', () => {
          console.log(this.input.value)
          this.input.value = getResult(this.input.value)
          console.log(this.input.value)
        })

I guess this is conflict of setAttribute method and initialisation of of input value by browser while pasting something to input. Could somebody help please to solve this problem?


问:
Unwanted top margin when using ViewPager2 with TabLayout
I have a TabLayout with a ViewPager2 attached.
I attach my fragments to it like normal but I have an odd behaviour.

Between the TabLayout and the TextView there is some kind of gap although my Textview should be in the very top left corner. I cannot figure out where this extra margin is coming from (It does not matter what kind of view I place into the fragment it seems the whole fragment is shifted down (But the actual background of my fragment covers the entire ViewPager area)

This is the code for the viewPager und TabLayout.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    tools:background="?attr/colorPrimary"
    app:tabGravity="fill"
    app:tabIndicatorColor="?attr/colorSecondary"
    app:tabIndicatorFullWidth="false"
    app:tabIndicatorHeight="3dp"
    app:tabMinWidth="48dp"
    app:tabMode="fixed"
    app:tabSelectedTextColor="?attr/colorOnPrimary"
    app:tabTextAppearance="@style/App.Tab.Text"
    app:tabTextColor="?attr/colorPrimaryLight"/>

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:background="@color/lightRed"
    android:layout_height="0dp"
    android:layout_weight="1" />
</LinearLayout>
</code>```

I only added the background color to see which view is "below" the margin

This is the code for the fragment.

```<code><androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/lightOrange"
android:fitsSystemWindows="true">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="NO MARGIN TOP LEFT"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Where does my margin come from? It drives me nuts. I do not change margins inside the code whatsoever.

I use a custom FragmentStateAdapter which might be the culprit? On a sidenot the first click on a tab after the app opens will not switch the page, I could not make this work yet any idea why?

Here is the Adapter I use:

```<code>public class TabAdapter extends FragmentStateAdapter {
private static final String TAG = "TabAdapter";
private final List<TabFragment> mFragments;
private final String prefix;
private final ViewPager2 mViewPager;
private final TabLayout mTabLayout;
private final OnPageChangeCallback callback;

public interface OnPageChangeCallback {
    void onPageSelected(int position);
}

public TabAdapter(BaseFragment fragment, TabLayout tabLayout, ViewPager2 viewPager, TabFragment... fragments) {
    this(fragment, tabLayout, viewPager, Arrays.asList(fragments), null);
}

public TabAdapter(BaseFragment fragment, TabLayout tabLayout, ViewPager2 viewPager, List<TabFragment> fragments) {
    this(fragment, tabLayout, viewPager, fragments, null);
}

public TabAdapter(BaseFragment fragment, TabLayout tabLayout, ViewPager2 viewPager, List<TabFragment> fragments, OnPageChangeCallback listener) {
    super(fragment);
    this.mFragments = fragments;
    this.prefix = fragment.TAG;
    this.mViewPager = viewPager;
    this.mTabLayout = tabLayout;
    this.callback = listener;
    initTabLayout();

}

@Override
@NonNull
public BaseFragment<?> createFragment(int position) {
    return mFragments.get(position).getFragment();
}

@Override
public long getItemId(int position) {
    return Objects.hash(mFragments.get(position));
}

@Override
public boolean containsItem(long itemId) {
    for (TabFragment fragment : mFragments) {
        if (Objects.hash(fragment) == itemId) return true;
    }
    return false;
}

@Override
public int getItemCount() {
    return mFragments.size();
}

private void initTabLayout() {
    mViewPager.setAdapter(this);
    mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);

            if (callback != null) callback.onPageSelected(position);
            TabStateProvider.saveTab(prefix, position);
        }
    });
    int startTab = TabStateProvider.getTab(prefix, false, 0);

    new TabLayoutMediator(mTabLayout, mViewPager, (tab, position) -> {
        tab.setText(mFragments.get(position).getTabTitle());
    }).attach();

    selectPage(startTab);

}

void selectPage(int pageIndex) {
    mViewPager.post(() -> {
        mViewPager.setCurrentItem(pageIndex, false);
    });
}

}
</code>```

Body:
I have a TabLayout with a ViewPager2 attached.
I attach my fragments to it like normal but I have an odd behaviour.

Between the TabLayout and the TextView there is some kind of gap although my Textview should be in the very top left corner. I cannot figure out where this extra margin is coming from (It does not matter what kind of view I place into the fragment it seems the whole fragment is shifted down (But the actual background of my fragment covers the entire ViewPager area)

This is the code for the viewPager und TabLayout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    tools:background="?attr/colorPrimary"
    app:tabGravity="fill"
    app:tabIndicatorColor="?attr/colorSecondary"
    app:tabIndicatorFullWidth="false"
    app:tabIndicatorHeight="3dp"
    app:tabMinWidth="48dp"
    app:tabMode="fixed"
    app:tabSelectedTextColor="?attr/colorOnPrimary"
    app:tabTextAppearance="@style/App.Tab.Text"
    app:tabTextColor="?attr/colorPrimaryLight"/>

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:background="@color/lightRed"
    android:layout_height="0dp"
    android:layout_weight="1" />
</LinearLayout>

I only added the background color to see which view is "below" the margin

This is the code for the fragment.

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/lightOrange"
android:fitsSystemWindows="true">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="NO MARGIN TOP LEFT"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Where does my margin come from? It drives me nuts. I do not change margins inside the code whatsoever.

I use a custom FragmentStateAdapter which might be the culprit? On a sidenot the first click on a tab after the app opens will not switch the page, I could not make this work yet any idea why?

Here is the Adapter I use:

public class TabAdapter extends FragmentStateAdapter {
private static final String TAG = "TabAdapter";
private final List<TabFragment> mFragments;
private final String prefix;
private final ViewPager2 mViewPager;
private final TabLayout mTabLayout;
private final OnPageChangeCallback callback;

public interface OnPageChangeCallback {
    void onPageSelected(int position);
}

public TabAdapter(BaseFragment fragment, TabLayout tabLayout, ViewPager2 viewPager, TabFragment... fragments) {
    this(fragment, tabLayout, viewPager, Arrays.asList(fragments), null);
}

public TabAdapter(BaseFragment fragment, TabLayout tabLayout, ViewPager2 viewPager, List<TabFragment> fragments) {
    this(fragment, tabLayout, viewPager, fragments, null);
}

public TabAdapter(BaseFragment fragment, TabLayout tabLayout, ViewPager2 viewPager, List<TabFragment> fragments, OnPageChangeCallback listener) {
    super(fragment);
    this.mFragments = fragments;
    this.prefix = fragment.TAG;
    this.mViewPager = viewPager;
    this.mTabLayout = tabLayout;
    this.callback = listener;
    initTabLayout();

}

@Override
@NonNull
public BaseFragment<?> createFragment(int position) {
    return mFragments.get(position).getFragment();
}

@Override
public long getItemId(int position) {
    return Objects.hash(mFragments.get(position));
}

@Override
public boolean containsItem(long itemId) {
    for (TabFragment fragment : mFragments) {
        if (Objects.hash(fragment) == itemId) return true;
    }
    return false;
}

@Override
public int getItemCount() {
    return mFragments.size();
}

private void initTabLayout() {
    mViewPager.setAdapter(this);
    mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);

            if (callback != null) callback.onPageSelected(position);
            TabStateProvider.saveTab(prefix, position);
        }
    });
    int startTab = TabStateProvider.getTab(prefix, false, 0);

    new TabLayoutMediator(mTabLayout, mViewPager, (tab, position) -> {
        tab.setText(mFragments.get(position).getTabTitle());
    }).attach();

    selectPage(startTab);

}

void selectPage(int pageIndex) {
    mViewPager.post(() -> {
        mViewPager.setCurrentItem(pageIndex, false);
    });
}

}


问:
Replace the statement ON DUPLICATE KEY UPDATE
MySQL version 5.7, ONLY_FULL_GROUP_BY is enabled

Please tell me an effective way to solve the following problem: it is necessary to make an entry in the table only if there are no matches in the record for several fields. If there is a matching record, then we update it with new data.
The ON DUPLICATE KEY UPDATE statement does not suit me, because the type and uuid_session fields are not unique (for example, there may be several records with different type, but with the same uuid_session).

Here is an example of a fake-query to better understand my question:

```<code>INSERT INTO cameraStatus(time, uuid_session)
VALUES ('2022-12-14 16:01:00', '01234567-8901-2345-6789-012345678901')
ON DUPLICATE KEY UPDATE (type, uuid_session) = ("WORK", "55555555-8901-2345-6789-012345678901");
</code>```

My table:

```<code>CREATE TABLE `cameraStatus` (
  `id` int NOT NULL,
  `camera_id` int NOT NULL DEFAULT '0',
  `time` timestamp NOT NULL DEFAULT '2021-12-31 21:00:00',
  `type` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'INFO',
  `message` mediumtext COLLATE utf8_unicode_ci,
  `uuid_session` varchar(36) CHARACTER SET utf8mb3 COLLATE utf8_unicode_ci DEFAULT '01234567-8901-2345-6789-012345678901'
)
</code>```

Body:
MySQL version 5.7, ONLY_FULL_GROUP_BY is enabled

Please tell me an effective way to solve the following problem: it is necessary to make an entry in the table only if there are no matches in the record for several fields. If there is a matching record, then we update it with new data.
The ON DUPLICATE KEY UPDATE statement does not suit me, because the type and uuid_session fields are not unique (for example, there may be several records with different type, but with the same uuid_session).

Here is an example of a fake-query to better understand my question:

INSERT INTO cameraStatus(time, uuid_session)
VALUES ('2022-12-14 16:01:00', '01234567-8901-2345-6789-012345678901')
ON DUPLICATE KEY UPDATE (type, uuid_session) = ("WORK", "55555555-8901-2345-6789-012345678901");

My table:

CREATE TABLE `cameraStatus` (
  `id` int NOT NULL,
  `camera_id` int NOT NULL DEFAULT '0',
  `time` timestamp NOT NULL DEFAULT '2021-12-31 21:00:00',
  `type` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'INFO',
  `message` mediumtext COLLATE utf8_unicode_ci,
  `uuid_session` varchar(36) CHARACTER SET utf8mb3 COLLATE utf8_unicode_ci DEFAULT '01234567-8901-2345-6789-012345678901'
)


问:
Change the HOSTNAME and PORT NUMBER for existing system DSN
How to change the Host name and Portnumber for above sytem dsn

How to change the HOSTNAME and Portnumber for existing system dsn