问:
Can't instantiate factories after updating to Springboot 3 and SpringFramework 6
Everything compiles, but I'm getting an error with the spring framework cloud configuration. The errors are all within the compiled dependencies, so I'm not sure what I am missing here. Any ideas?

I'm getting this error in particular.

```<code>ERROR org.springframework.boot.SpringApplication - Application run failed
java.lang.IllegalArgumentException: Unable to instantiate factory class [org.springframework.cloud.config.client.ConfigServerConfigDataLocationResolver] for factory type [org.springframework.boot.context.config.ConfigDataLocationResolver]
    at org.springframework.core.io.support.SpringFactoriesLoader$FailureHandler.lambda$throwing$0(SpringFactoriesLoader.java:650)
    at org.springframework.core.io.support.SpringFactoriesLoader$FailureHandler.lambda$handleMessage$3(SpringFactoriesLoader.java:674)
    at org.springframework.core.io.support.SpringFactoriesLoader.instantiateFactory(SpringFactoriesLoader.java:231)
    at org.springframework.core.io.support.SpringFactoriesLoader.load(SpringFactoriesLoader.java:206)
    at org.springframework.core.io.support.SpringFactoriesLoader.load(SpringFactoriesLoader.java:160)
    at org.springframework.boot.context.config.ConfigDataLocationResolvers.<init>(ConfigDataLocationResolvers.java:66)
    at org.springframework.boot.context.config.ConfigDataEnvironment.createConfigDataLocationResolvers(ConfigDataEnvironment.java:160)
    at org.springframework.boot.context.config.ConfigDataEnvironment.<init>(ConfigDataEnvironment.java:148)
    at org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor.getConfigDataEnvironment(ConfigDataEnvironmentPostProcessor.java:101)
    at org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor.postProcessEnvironment(ConfigDataEnvironmentPostProcessor.java:96)
    at org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor.postProcessEnvironment(ConfigDataEnvironmentPostProcessor.java:89)
    at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEnvironmentPreparedEvent(EnvironmentPostProcessorApplicationListener.java:109)
    at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEvent(EnvironmentPostProcessorApplicationListener.java:94)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
    at org.springframework.boot.context.event.EventPublishingRunListener.multicastInitialEvent(EventPublishingRunListener.java:136)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:81)
    at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:64)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:118)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:112)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:63)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:352)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:150)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:197)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:114)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:77)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
    at org.springframework.boot.context.event.EventPublishingRunListener.multicastInitialEvent(EventPublishingRunListener.java:136)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:81)
    at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:64)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:118)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:112)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:63)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:352)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at navy.chino.fields.FieldsApp.main(FieldsApp.java:68)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalArgumentException: Log types cannot be injected, please use DeferredLogFactory
    at org.springframework.boot.context.config.ConfigDataLocationResolvers.lambda$new$0(ConfigDataLocationResolvers.java:64)
    at org.springframework.core.io.support.SpringFactoriesLoader$ArgumentResolver.lambda$ofSupplied$3(SpringFactoriesLoader.java:585)
    at org.springframework.core.io.support.SpringFactoriesLoader$ArgumentResolver$1.resolve(SpringFactoriesLoader.java:601)
    at org.springframework.core.io.support.SpringFactoriesLoader$ArgumentResolver.lambda$and$0(SpringFactoriesLoader.java:551)
    at org.springframework.core.io.support.SpringFactoriesLoader$ArgumentResolver$1.resolve(SpringFactoriesLoader.java:601)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:992)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:575)
    at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:616)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:622)
    at org.springframework.core.io.support.SpringFactoriesLoader$FactoryInstantiator.resolveArgs(SpringFactoriesLoader.java:387)
    at org.springframework.core.io.support.SpringFactoriesLoader$FactoryInstantiator.instantiate(SpringFactoriesLoader.java:377)
    at org.springframework.core.io.support.SpringFactoriesLoader.instantiateFactory(SpringFactoriesLoader.java:228)
    ... 46 common frames omitted

Process finished with exit code 0

</code>```

Trying to upgrade an application to use Spring Framework 6 and all of the other updates needed along the way.

Body:
Everything compiles, but I'm getting an error with the spring framework cloud configuration. The errors are all within the compiled dependencies, so I'm not sure what I am missing here. Any ideas?

I'm getting this error in particular.

ERROR org.springframework.boot.SpringApplication - Application run failed
java.lang.IllegalArgumentException: Unable to instantiate factory class [org.springframework.cloud.config.client.ConfigServerConfigDataLocationResolver] for factory type [org.springframework.boot.context.config.ConfigDataLocationResolver]
    at org.springframework.core.io.support.SpringFactoriesLoader$FailureHandler.lambda$throwing$0(SpringFactoriesLoader.java:650)
    at org.springframework.core.io.support.SpringFactoriesLoader$FailureHandler.lambda$handleMessage$3(SpringFactoriesLoader.java:674)
    at org.springframework.core.io.support.SpringFactoriesLoader.instantiateFactory(SpringFactoriesLoader.java:231)
    at org.springframework.core.io.support.SpringFactoriesLoader.load(SpringFactoriesLoader.java:206)
    at org.springframework.core.io.support.SpringFactoriesLoader.load(SpringFactoriesLoader.java:160)
    at org.springframework.boot.context.config.ConfigDataLocationResolvers.<init>(ConfigDataLocationResolvers.java:66)
    at org.springframework.boot.context.config.ConfigDataEnvironment.createConfigDataLocationResolvers(ConfigDataEnvironment.java:160)
    at org.springframework.boot.context.config.ConfigDataEnvironment.<init>(ConfigDataEnvironment.java:148)
    at org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor.getConfigDataEnvironment(ConfigDataEnvironmentPostProcessor.java:101)
    at org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor.postProcessEnvironment(ConfigDataEnvironmentPostProcessor.java:96)
    at org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor.postProcessEnvironment(ConfigDataEnvironmentPostProcessor.java:89)
    at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEnvironmentPreparedEvent(EnvironmentPostProcessorApplicationListener.java:109)
    at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEvent(EnvironmentPostProcessorApplicationListener.java:94)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
    at org.springframework.boot.context.event.EventPublishingRunListener.multicastInitialEvent(EventPublishingRunListener.java:136)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:81)
    at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:64)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:118)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:112)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:63)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:352)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:150)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:197)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:114)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:77)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
    at org.springframework.boot.context.event.EventPublishingRunListener.multicastInitialEvent(EventPublishingRunListener.java:136)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:81)
    at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:64)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:118)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:112)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:63)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:352)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at navy.chino.fields.FieldsApp.main(FieldsApp.java:68)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalArgumentException: Log types cannot be injected, please use DeferredLogFactory
    at org.springframework.boot.context.config.ConfigDataLocationResolvers.lambda$new$0(ConfigDataLocationResolvers.java:64)
    at org.springframework.core.io.support.SpringFactoriesLoader$ArgumentResolver.lambda$ofSupplied$3(SpringFactoriesLoader.java:585)
    at org.springframework.core.io.support.SpringFactoriesLoader$ArgumentResolver$1.resolve(SpringFactoriesLoader.java:601)
    at org.springframework.core.io.support.SpringFactoriesLoader$ArgumentResolver.lambda$and$0(SpringFactoriesLoader.java:551)
    at org.springframework.core.io.support.SpringFactoriesLoader$ArgumentResolver$1.resolve(SpringFactoriesLoader.java:601)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:992)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:575)
    at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:616)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:622)
    at org.springframework.core.io.support.SpringFactoriesLoader$FactoryInstantiator.resolveArgs(SpringFactoriesLoader.java:387)
    at org.springframework.core.io.support.SpringFactoriesLoader$FactoryInstantiator.instantiate(SpringFactoriesLoader.java:377)
    at org.springframework.core.io.support.SpringFactoriesLoader.instantiateFactory(SpringFactoriesLoader.java:228)
    ... 46 common frames omitted

Process finished with exit code 0

Trying to upgrade an application to use Spring Framework 6 and all of the other updates needed along the way.


来源: stackexchange

问:
Convert excel file to HTML Table Drag and drop
I want to develop a web page where I upload an excel file and it becomes an HTML table and that HTML table can be drag and drop to another destination table. For now I have the function to upload the file in excel and it works without problems.

This is my HTML:

```<code><!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8" />
    <title>Pronóstico</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
    <script>
    $( function() {
        $( "#sortable1, #sortable2" ).sortable({
            connectWith: ".connectedSortable"
        }).disableSelection();
    } );
  </script>
</head>
<body>
    <div class="container">
        <h2 class="text-center mt-4 mb-4">Page1</h2>
        <div class="card">
            <div class="card-header"><b>Upload Excel File</b></div>
            <div class="card-body">
                <input type="file" id="excel_file" />
            </div>
        </div>
        <div id="excel_data" class="mt-5"></div>
    </div>
    <div class="container">
        <div class="card">
            <div class="card-header text-center"><b>Destination Table</b></div>
            <div class="card-body">
                <table id="sortable2" class="container connectedSortable text-center">
                    <tr>
                        <th>Origin</th>
                        <th>Destination</th>
                        <th>start trip</th>
                        <th>Trip completion</th>
                        <th>Trip Duration</th>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
</code>```

This is the script for both uploading the excel file and converting the data to HTML table

```<code><script>

const excel_file = document.getElementById('excel_file');

excel_file.addEventListener('change', (event) => {

    if(!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type))
    {
        document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';

        excel_file.value = '';

        return false;
    }

    var reader = new FileReader();

    reader.readAsArrayBuffer(event.target.files[0]);

    reader.onload = function(event){

        var data = new Uint8Array(reader.result);

        var work_book = XLSX.read(data, {type:'array'});

        var sheet_name = work_book.SheetNames;

        var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {header:1});

        if(sheet_data.length > 0)
        {
            var table_output = '<table id="sortable1" class="table table-striped table-bordered connectedSortable">';

            for(var row = 0; row < sheet_data.length; row++)
            {

                table_output += '<tr>';

                for(var cell = 0; cell < sheet_data[row].length; cell++)
                {

                    if(row == 0)
                    {

                        table_output += '<th>'+sheet_data[row][cell]+'</th>';

                    }
                    else
                    {

                        table_output += '<td>'+sheet_data[row][cell]+'</td>';

                    }

                }

                table_output += '</tr>';

            }

            table_output += '</table>';

            document.getElementById('excel_data').innerHTML = table_output;
        }

        excel_file.value = '';

    }

});

</script>
</code>```

I tried this script (http://jqueryui.com/demos/sortable/#connect-lists) to transform the HTML table in Drag and Drop but without success:

```<code><script>
    $( function() {
        $( "#sortable1, #sortable2" ).sortable({
            connectWith: ".connectedSortable"
        }).disableSelection();
    } );
  </script>
</code>```

Any suggestions or another path I can take? Actually my experience is not front-end, I have basic knowledge.

Thanks in advance.

ContentLicense: CC BY-SA 4.0

Body:
I want to develop a web page where I upload an excel file and it becomes an HTML table and that HTML table can be drag and drop to another destination table. For now I have the function to upload the file in excel and it works without problems.

This is my HTML:

<!DOCTYPE HTML>

    <meta charset="utf-8" />
    <title>Pronóstico</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Page1

Upload Excel File

                <input type="file" id="excel_file" />

Destination Table

                        Origin
                        Destination
                        start trip
                        Trip completion
                        Trip Duration

This is the script for both uploading the excel file and converting the data to HTML table

I tried this script (http://jqueryui.com/demos/sortable/#connect-lists) to transform the HTML table in Drag and Drop but without success:

Any suggestions or another path I can take? Actually my experience is not front-end, I have basic knowledge.

Thanks in advance.


问:
embeddings distribution wrong
I'm having the code below which is supposed to plot word embeddings.

Since it creates a list of embeddings of identical words I would have expected a cluster of points - all embeddings at one point.
But they are scattered like this.
Any Idea what I am doing wrong?

```<code>input_strings=[
 # "king",
  #"queen",
  "castle",
  "castle",
  "castle",
  "castle",
  "castle",
  "castle",
  "castle"
  #"rocket",
  #"moon",
  #"accountant",
  #"finance"
]

def get_embeddings(strings):
  return_list=list()
  for string in strings:
    response = openai.Embedding.create(
      model="text-search-davinci-query-001",
      input=string
    )
    embeddings=response['data'][0]['embedding']
    #print(embeddings)
    return_list.append(embeddings)
  return (return_list)

embeddings_list=get_embeddings(input_strings)

tsne = TSNE(n_components=3)
reduced_embeddings = tsne.fit_transform(embeddings_list)

# create a figure and axis

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# loop through the list of reduced-dimensional embeddings
for embedding in reduced_embeddings:
    # plot the 3D embedding on the axis
    ax.scatter(embedding[0], embedding[1], embedding[2])

# show the plot
plt.show()
</code>```

Title: embeddings distribution wrong

Body:
I'm having the code below which is supposed to plot word embeddings.

Since it creates a list of embeddings of identical words I would have expected a cluster of points - all embeddings at one point.
But they are scattered like this.
Any Idea what I am doing wrong?

input_strings=[
 # "king",
  #"queen",
  "castle",
  "castle",
  "castle",
  "castle",
  "castle",
  "castle",
  "castle"
  #"rocket",
  #"moon",
  #"accountant",
  #"finance"
]

def get_embeddings(strings):
  return_list=list()
  for string in strings:
    response = openai.Embedding.create(
      model="text-search-davinci-query-001",
      input=string
    )
    embeddings=response['data'][0]['embedding']
    #print(embeddings)
    return_list.append(embeddings)
  return (return_list)

embeddings_list=get_embeddings(input_strings)

tsne = TSNE(n_components=3)
reduced_embeddings = tsne.fit_transform(embeddings_list)

# create a figure and axis

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# loop through the list of reduced-dimensional embeddings
for embedding in reduced_embeddings:
    # plot the 3D embedding on the axis
    ax.scatter(embedding[0], embedding[1], embedding[2])

# show the plot
plt.show()


问:
how to make sure that a child component gives value to parent component before it is destroyed in angular
i want to make sure that @output of a child component (basically an eventemitter) has passed the value to parent component before it is getting destroyed.

Will giving the event emitter on Ondestroy() a good practise.


问:
AWS SSO Login PowerShell
Due to security policy, connecting to AWS programmatically with PowerShell using an Access/Secret Key is not allowed at our organization anymore, and needs to be replaced with AWS SSO. But I didn't find any clear documentation on how to actually connect to AWS with PowerShell, using AWS SSO. On AWS official documentation for PowerShell Cmdlets, I can see a cmdlet named: Close-SSOSession, which is very straight forward about what is does. but which cmdlet is used to open the session in the first place? I would expect something like: Open-SSOSession. I also need to mention, that we are not allowed to install AWS CLI V2 on our Windows servers, as only the AWS PowerShell Module is approved to use by developers.</p>

Title: AWS SSO Login PowerShell


问:
Exclude a folder from step Get file names when include subfolders = Y in PENTAHO
I am trying to get the name of all .xlsx file in multiple subfolders with a root directory. I am wanting to exclude one or more subdirectories.

I have tried

File/Directory
Wildcard (RegExp)
Exclude wildcard
Required
Include subfolders

\\peace\vol2\Temp\Test
.*.xlsx
.*\bkup
N
Y

.+bkup.+

I want all files in all of the subfolders except for any files in the \\peace\vol2\Temp\Test\bkup subdfolder. I am using the Get file name step and it is working fine for the wildcard but the exclude is not excluding the directory.
I know I am close but can someone help with right syntax?


问:
Getting error 400 on the API end point runReport, the front end doesn't give me errors with same dimensions and metrics
I’m trying to use the API for GA4. Before December 5 I was able to do the following call: "url": "https://analyticsdata.googleapis.com/v1beta/properties/307276000:runReport", "method": "POST", "body": "{\n"dimensions":[\n{\n"name":"date"\n},\n{\n"name":"deviceCategory"\n},\n{\n"name":"pageLocation"\n},\n{\n"name":"pageTitle"\n},\n{\n"name":"sessionCampaignName"\n},\n{\n"name":"sessionSourceMedium"\n}\n],\n\ "metrics":[\n{\n"name":"screenPageViews"\n},\n{\n"name":"newUsers"\n},\n{\n"name":"engagedSessions"\n}\n],\n"dateRanges":[\n{\n"startDate":'2022-12-02',\n"endDate":'2022-12-12'\n}\n], \n"limit":"10000",\n"offset":0,\n"keepEmptyRows":true\n}" } And it was successful, but starting December 5, now I get the following error: { "error": { "code": 400, "message": "Please remove pageLocation to make the request compatible. The request's dimensions & metrics are incompatible. To learn more, see https://ga-dev-tools.web.app/ga4/dimensions-metrics-explorer/", "status": "INVALID_ARGUMENT" } } I get the results from the front end. Trying to understand what is the problem.

The front end gives me the results without an error, I keep getting the error since December 5.


问:
python sqlalchemy: get empty record if none
I have 2 tables:
User:  id, name
Phone: id, user_id, phone_num

When executing query:

```<code>Query([User, Phone].select_from(User).join(Phone, Phone.user_id == User.id).filter(User.id == the_user)
</code>```

It returns the record if exists.  My question is that when there are no record matches, how can I returns something like:
{'id': None, 'user_id': None, 'phone_num': None}

Body:
I have 2 tables:
User:  id, name
Phone: id, user_id, phone_num

When executing query:

Query([User, Phone].select_from(User).join(Phone, Phone.user_id == User.id).filter(User.id == the_user)

It returns the record if exists.  My question is that when there are no record matches, how can I returns something like:
{'id': None, 'user_id': None, 'phone_num': None}


问:
Not being able to use c# value in javascript in cshtml file for maps
I have some nullable values coming from my c# code. They are longitude and latitude.

I have this code

```<code><script>
    @if (Model.crisis.Longitude.HasValue)
    {
        var lng = Model.crisis.Longitude.Value;
        var lat = Model.crisis.Latitude.Value;
        <text>
            window.onload = function() {
                var myOptions = {
                    zoom: 13,
                    center: { lat: @(lat), lng: @(lng) },
                  //  center: { lat: -34.397, lng: 150.644 },
                    mapTypeId: google.maps.MapTypeId.roadmap,
                    disableDefaultUI: true
                };

                var map = new google.maps.Map(document.getElementById("map"), myOptions);
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(@lat, @lng),

                });

                marker.setMap(map);
            }
        </text>
    }
</script>
</code>```

Props from server

```<code>public double? Latitude { get; set; }
public double? Longitude { get; set; }
</code>```

My map doesn't show as it doesn't center at the given long and lat. If I hardcode values then it works like a charm. Am I missing something? For me it seems, that I cannot use nullable values here. Is it so?

Body:
I have some nullable values coming from my c# code. They are longitude and latitude.

I have this code

Props from server

public double? Latitude { get; set; }
public double? Longitude { get; set; }

My map doesn't show as it doesn't center at the given long and lat. If I hardcode values then it works like a charm. Am I missing something? For me it seems, that I cannot use nullable values here. Is it so?


问:
When my Android audio player is in background, how do I do stuff as the song progresses?
For example, I want to send a notification that the next line is coming up to an external device that shows lyrics.

I tried setting RemoteControlClient.setPlaybackPositionUpdateListener, but the listener is never called.


问:
Camel how to pass headers to parallelized routes
I'm working on parallelizing a camel route:

//...
.multicast(new GroupedMessageAggregationStrategy())
.parallelProcessing()
.to("direct:routeA")
.to("direct:routeB")
.end()
//...
```

But the routes that I run in parallel rely on some headers from the main route, that don't seem to be passed to the parallelized routes.

For context, I hope to wrangle all responses back to the main route as a list (currently using GroupedMessageAggregationStrategy, where I can iterate over responses to handle potential errors. The routes I am calling used to be part of the main route (leading from one to the next, sequentially).

How can I pass the route headers along to the parallelized routes?

Body:
I'm working on parallelizing a camel route:

//...
.multicast(new GroupedMessageAggregationStrategy())
.parallelProcessing()
.to("direct:routeA")
.to("direct:routeB")
.end()
//...

But the routes that I run in parallel rely on some headers from the main route, that don't seem to be passed to the parallelized routes.

For context, I hope to wrangle all responses back to the main route as a list (currently using GroupedMessageAggregationStrategy, where I can iterate over responses to handle potential errors. The routes I am calling used to be part of the main route (leading from one to the next, sequentially).

How can I pass the route headers along to the parallelized routes?


问:
Agora cloud recording could not find worker error when recording user, or video is black
In my application users can join one-one calls. What I'm trying to do, is add the ability to record the audio and video for one user (B), while only recording the audio for another (A). A initiates the recording, by calling my own API, who then calls Agora.

Right now, I'm facing one of two problems:
(i) Either user A isn't being being recorded at all, or
(ii) the resulting video is completely black, with no audio or video stream.

Despite the Agora docs stating that the uid sent to the acquire endpoint mustn't match an existing user id in the channel, I was doing it anyway because it was the only way to get something recorded. More concretely, I sent user A's id in that field. This worked for recording user B. In fact I was able to record audio and video for them. In order to avoid recording user A's video, I unsubscribed from that stream. However, their audio wasn't being recorded. In the end, something like this was being sent:

POST /apps/APPID/cloud_recording/resourceid/RESOURCEID/mode/mix/start
    {
      cname: # channel name #,
      uid: user_id.to_s, # user A's id
      clientRequest: {
        token:,
        streamTypes: STREAM_TYPES[:audio_and_video],
        recordingConfig: {
          unSubscribeVideoUids: [user_id.to_s],
          channelType: CHANNEL_TYPE[:communication],
          transcodingConfig: {
            width: 1920,
            height: 1080,
            fps: 30,
            bitrate: 4500
          }
        },
        recordingFileConfig: {
          avFileType: %w[hls mp4]
        },
        storageConfig: {
          vendor: STORAGE_VENDOR[:amazon_s3],
          region: ...,
          bucket: ...,
          accessKey: ...,
          secretKey: ...,
          fileNamePrefix: ['agora']
        }
      }
    }

```

I've also attempted to explicity subscribe to the streams I'd like to keep, in which case, the resulting video is just black.

On the other hand, when the documentation is heeded, and a different uid is sent, the stop recording endpoint returns error 404 with the message "worker not found".

Any help is greatly appreciated.

Body:
In my application users can join one-one calls. What I'm trying to do, is add the ability to record the audio and video for one user (B), while only recording the audio for another (A). A initiates the recording, by calling my own API, who then calls Agora.

Right now, I'm facing one of two problems:
(i) Either user A isn't being being recorded at all, or
(ii) the resulting video is completely black, with no audio or video stream.

Despite the Agora docs stating that the uid sent to the acquire endpoint mustn't match an existing user id in the channel, I was doing it anyway because it was the only way to get something recorded. More concretely, I sent user A's id in that field. This worked for recording user B. In fact I was able to record audio and video for them. In order to avoid recording user A's video, I unsubscribed from that stream. However, their audio wasn't being recorded. In the end, something like this was being sent:

POST /apps/APPID/cloud_recording/resourceid/RESOURCEID/mode/mix/start
    {
      cname: # channel name #,
      uid: user_id.to_s, # user A's id
      clientRequest: {
        token:,
        streamTypes: STREAM_TYPES[:audio_and_video],
        recordingConfig: {
          unSubscribeVideoUids: [user_id.to_s],
          channelType: CHANNEL_TYPE[:communication],
          transcodingConfig: {
            width: 1920,
            height: 1080,
            fps: 30,
            bitrate: 4500
          }
        },
        recordingFileConfig: {
          avFileType: %w[hls mp4]
        },
        storageConfig: {
          vendor: STORAGE_VENDOR[:amazon_s3],
          region: ...,
          bucket: ...,
          accessKey: ...,
          secretKey: ...,
          fileNamePrefix: ['agora']
        }
      }
    }

I've also attempted to explicity subscribe to the streams I'd like to keep, in which case, the resulting video is just black.

On the other hand, when the documentation is heeded, and a different uid is sent, the stop recording endpoint returns error 404 with the message "worker not found".

Any help is greatly appreciated.


问:
Testing redux dispatch action happened-Jest
I am new to testing redux and I am trying to test if a dispatch action is called on button press.

My component

```<code>export const Earnings: React.FC<Props> = ({ stats }) => {

  const { fetchEarnings } = useBindDispatch({
    fetchEarnings: EarningsActions.fetchEarnings
  }); // this is the dispatch action

function doStuffOnPress(){
   ..do stuff
   fetchEarnings()
}
 return (

<View/>
)

}`
</code>```

My Test

```<code>  const fetchEarnings = jest.fn();
  beforeEach(() => {
    useDispatch.mockImplementation(() => fetchEarnings);
  });

it("should fetch new stats", () => {

    const { queryByTestId } = render(
        <EarningsAndStatsView stats={stats} />
    );

    const button = queryByTestId(fetch-button);
    fireEvent.press(button);
    expect(fetchEarningsAndStats).toBeCalled();

  });

</code>```

The function doStuffOnPress is called and I was expecting fectchEarnings to get called, but it does not get called. What am I doing wrong?
test result

Body:
I am new to testing redux and I am trying to test if a dispatch action is called on button press.

My component

export const Earnings: React.FC<Props> = ({ stats }) => {

  const { fetchEarnings } = useBindDispatch({
    fetchEarnings: EarningsActions.fetchEarnings
  }); // this is the dispatch action

function doStuffOnPress(){
   ..do stuff
   fetchEarnings()
}
 return (

<View/>
)

}`

My Test

  const fetchEarnings = jest.fn();
  beforeEach(() => {
    useDispatch.mockImplementation(() => fetchEarnings);
  });

it("should fetch new stats", () => {

    const { queryByTestId } = render(
        <EarningsAndStatsView stats={stats} />
    );

    const button = queryByTestId(fetch-button);
    fireEvent.press(button);
    expect(fetchEarningsAndStats).toBeCalled();

  });

The function doStuffOnPress is called and I was expecting fectchEarnings to get called, but it does not get called. What am I doing wrong?
test result


问:
Requesting the facebook user_messenger_contact scope does not work with test users in facebook
In order to get the consent of a user to contact him via facebook messenger we need to ask the user for his consent during login with facebook. This can be done with the user_messenger_contact scope/permission. This works well with Admin Users of the corresponding facebook app but does not work with facebook test users for that app. The test users are never asked for consent to be contacted via facebook messenger.

We tried multiple settings in the facebook app.

We put the app in development mode

The default pages for the facebook messenger login connect experience is set

We followed all steps explained herehttps://developers.facebook.com/docs/facebook-login/login-connect/implementing

It works for Admin Accounts of the App but not for facebook accounts.


问:
Rust+SDL2 - How to store a texture in a struct
There are several questions on SO asking this same thing:

Is there a way to store a texture inside a struct using rust-sdl2?

Managing SDL2 (rust) Texture lifetime

And these were supposedly answered in:

Cannot infer an appropriate lifetime for autoref due to conflicting requirements

Why can't I store a value and a reference to that value in the same struct?

I also looked at the examples in the rust-sdl2 repo, but I still can't figure this out.

My goal is to have a struct that holds a canvas and a texture so I can repeatedly update the texture with new pixel data from a streaming camera. I got this to work but I was creating a new texture in every loop iteration which didn't seem right and also caused a memory leak. So I decided to hold the texture in a struct and just update it on every call to draw. This seemed like the right thing to do, but rust-sdl makes this seemingly impossible due to lifetime constraints on Texture. I followed the compiler suggestions about adding lifetimes and what not, but now I'm stuck. Here's what I have so far:

use sdl2::pixels::PixelFormatEnum;
use sdl2::render::{Canvas, Texture, TextureCreator};
use sdl2::video::{Window, WindowContext};

pub struct View<'tex> {
    canvas: Canvas<Window>,
    texture: &'tex Texture<'tex>,
}

impl<'tex> View<'tex> {
    fn new(width: u32, height: u32) -> Self {
        let sdl_context = sdl2::init().unwrap();
        let subsystem = sdl_context.video().unwrap();

        let window = subsystem
            .window("sdl2 - test", width, height)
            .position_centered()
            .build()
            .unwrap();

        let canvas = window.into_canvas().build().unwrap();
        let texture_creator: &'tex TextureCreator<WindowContext> = &canvas.texture_creator();
        let texture: &'tex Texture = &texture_creator
            .create_texture_streaming(PixelFormatEnum::ARGB8888, width as u32, width as u32)
            .map_err(|e| e.to_string()).unwrap();

        Self {
            canvas,
            texture,
        }
    }
}

fn main() {
    let view = View::new(500, 500);
}

```
<p>But I am stuck at this error:</p>
```error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:23:69
   |
11 | impl<'tex> View<'tex> {
   |      ---- lifetime `'tex` defined here
...
23 |         let texture_creator: &'tex TextureCreator<WindowContext> = &canvas.texture_creator();
   |                              -----------------------------------    ^^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
   |                              |
   |                              type annotation requires that borrow lasts for `'tex`
...
32 |     }
   |     - temporary value is freed at the end of this statement
```

I also thought about creating the canvas and the texture in main and passing them to new so that they &'static lifetime, but that goes down another rabbit hole where I need to also create the window in main and pretty much negates any kind of abstraction I was attempting.

How do I store a reference to the Texture so I can avoid repeatedly allocating it?

Body:
There are several questions on SO asking this same thing:

Is there a way to store a texture inside a struct using rust-sdl2?

Managing SDL2 (rust) Texture lifetime

And these were supposedly answered in:

Cannot infer an appropriate lifetime for autoref due to conflicting requirements

Why can't I store a value and a reference to that value in the same struct?

I also looked at the examples in the rust-sdl2 repo, but I still can't figure this out.

My goal is to have a struct that holds a canvas and a texture so I can repeatedly update the texture with new pixel data from a streaming camera. I got this to work but I was creating a new texture in every loop iteration which didn't seem right and also caused a memory leak. So I decided to hold the texture in a struct and just update it on every call to draw. This seemed like the right thing to do, but rust-sdl makes this seemingly impossible due to lifetime constraints on Texture. I followed the compiler suggestions about adding lifetimes and what not, but now I'm stuck. Here's what I have so far:

use sdl2::pixels::PixelFormatEnum;
use sdl2::render::{Canvas, Texture, TextureCreator};
use sdl2::video::{Window, WindowContext};

pub struct View<'tex> {
    canvas: Canvas<Window>,
    texture: &'tex Texture<'tex>,
}

impl<'tex> View<'tex> {
    fn new(width: u32, height: u32) -> Self {
        let sdl_context = sdl2::init().unwrap();
        let subsystem = sdl_context.video().unwrap();

        let window = subsystem
            .window("sdl2 - test", width, height)
            .position_centered()
            .build()
            .unwrap();

        let canvas = window.into_canvas().build().unwrap();
        let texture_creator: &'tex TextureCreator<WindowContext> = &canvas.texture_creator();
        let texture: &'tex Texture = &texture_creator
            .create_texture_streaming(PixelFormatEnum::ARGB8888, width as u32, width as u32)
            .map_err(|e| e.to_string()).unwrap();

        Self {
            canvas,
            texture,
        }
    }
}

fn main() {
    let view = View::new(500, 500);
}

But I am stuck at this error:

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:23:69
   |
11 | impl<'tex> View<'tex> {
   |      ---- lifetime `'tex` defined here
...
23 |         let texture_creator: &'tex TextureCreator<WindowContext> = &canvas.texture_creator();
   |                              -----------------------------------    ^^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
   |                              |
   |                              type annotation requires that borrow lasts for `'tex`
...
32 |     }
   |     - temporary value is freed at the end of this statement

I also thought about creating the canvas and the texture in main and passing them to new so that they &'static lifetime, but that goes down another rabbit hole where I need to also create the window in main and pretty much negates any kind of abstraction I was attempting.

How do I store a reference to the Texture so I can avoid repeatedly allocating it?


问:
What is causing a syntax error on last line of JAGS model?
I have created a model to investigate the effects of covariates on occupancy of different bird species at different points across different properties. However, when I try to run the model using rjags, I get this error: Error parsing model file: syntax error on line 115 near "#"

Here is my full model:

```<code>model{
#-----------------------------------------------------------------------------------------------------
# 1) Priors
#-----------------------------------------------------------------------------------------------------

  ######## Abundance ########
  mean_alpha0.psi ~ dnorm(0, 0.01)   # Mean intercept for occupancy probability for all species
  sd_alpha0 ~ dunif(0, 10)      # Standard deviation on mean abundance for all species
  prec_alpha0 <- 1 / (sd_alpha0 ^ 2)

  for (h in 1:nspecies) {
     alpha0.psi[h] ~ dnorm(mean_alpha0.psi, prec_alpha0) # Mean log abundance per point for species h

    # Uninformative priors on covariates
    alpha1[h] ~ dnorm(mu_alpha1, tau_alpha1) # Effect of fire frequency for each species
    alpha2[h] ~ dnorm(mu_alpha2, tau_alpha2) # Effect of ground cover for each species
    alpha3[h] ~ dnorm(mu_alpha3, tau_alpha3) # Effect of vegetation height for each species
    alpha4[h] ~ dnorm(mu_alpha4, tau_alpha4) # Effect of total basal area for each species
    alpha5[h] ~ dnorm(mu_alpha5, tau_alpha5) # Effect of % deciduous area for each species
  } # close h

  sd_eps ~ dexp(1) # Standard deviation for random property effect
  prec_eps <- 1 / (sd_eps ^ 2) # Precision for random property effect

  for (i in 1:nprops) {
    eps[i] ~ dnorm(0, prec_eps) # Random property effect
  } # close i

  mu_alpha1 ~ dnorm(0, 0.001)
  tau_alpha1 ~ dgamma(0.01, 0.01)

  mu_alpha2 ~ dnorm(0, 0.001)
  tau_alpha2 ~ dgamma(0.01, 0.01)

  mu_alpha3 ~ dnorm(0, 0.001)
  tau_alpha3 ~ dgamma(0.01, 0.01)

  mu_alpha4 ~ dnorm(0, 0.001)
  tau_alpha4 ~ dgamma(0.01, 0.01)

  mu_alpha5 ~ dnorm(0, 0.001)
  tau_alpha5 ~ dgamma(0.01, 0.01)

  ######## Availability #########
  for (h in 1:nspecies) {
    mean_phi0[h] ~ dnorm(0, 0.001)    # Mean availability for each species
    sd_phi0[h] ~ dexp(1)              # Standard deviation of availability for each species
    prec_phi0[h] <- 1 / (sd_phi0[h] ^ 2)

    for (i in 1:nprops) {
      for (j in 1:npoints_site[i]) {
        phi0[h, i, j] ~ dnorm(mean_phi0[h], prec_phi0[h]) # Mean availability for species h at property i and point j
      } # close j
    } # close i
  } # close h

  phi1 ~ dnorm(0, 0.001) # coefficient of day of year in availiabity linear model
  phi2 ~ dnorm(0, 0.001) # coefficient of day of year^2 in availiabity linear model
  phi3 ~ dnorm(0, 0.001) # coefficient of time after sunrise in availiabity linear model
  phi4 ~ dnorm(0, 0.001) # coefficient of temp in availiabity linear model
  phi5 ~ dnorm(0, 0.001) # coefficient of wind in availiabity linear model

#-----------------------------------------------------------------------------------------------------
# 2) Ecological process model
#-----------------------------------------------------------------------------------------------------

  for (h in 1:nspecies) {
    for (i in 1:nprops) {
      for (j in 1:npoints_site[i]) {
        z[h,i,j] ~ dbern(psi[h,i,j]) # True occupancy based on occupancy probability
        psi[h,i,j] <- 1 / (1 + exp(-lpsi.lim[h,i,j]))
        lpsi.lim[i] <- min(999, max(-999, lpsi[i]))
        lpsi[i] <- alpha0.psi[h] + alpha1[h] * fire[i, j] + alpha2[h] * ground[i, j] + alpha3[h] *
          height[i, j] + alpha4[h] * tba[i, j] + alpha5[h] * decid[i, j] + eps[i]

#-----------------------------------------------------------------------------------------------------
# 3) Observational process model
#-----------------------------------------------------------------------------------------------------

        ###### Availability with time removal ######
        for (v in 1:vh[i, j]) {
          # loop over each visit (v) to each site

          # Availability is a function of intercept + covariates

          y[h,i,j,v] ~ dbern(mu.p[h,i,j,v]) # Detection/non-detection
          mu.p[h,i,j,v] <- z[h,i,j] * pa[h,i,j,v]

          logit(p[h,i,j,v]) <- phi0[h, i, j] + phi1 * obs_date[i, j, v] + phi2 * obs_date[i, j, v] * obs_date[i, j, v] + phi3 * obs_time[i, j, v] + phi4 * obs_temp[i, j, v] + phi5 * obs_wind[i, j, v]

          for (z in 1:ntbins) {
            # Probability of being available in each time bin
            # pi_pa in time bin >1 conditional on not being detected before
            pi_pa[h, i, j, z, v] <-
              p[h, i, j, v] * pow(1 - p[h, i, j, v], (z - 1))
            pi_pa_normalized[h, i, j, z, v] <-
              pi_pa[h, i, j, z, v] / pa[h, i, j, v]
          } # close z

          # Probability ever available
          pa[h, i, j, v] <- sum(pi_pa[h, i, j, 1:ntbins, v])

          # Time data - when were detections mentally removed? NOT SURE ABOUT THIS LINE
          ytb[h, i, j, 1:ntbins, v] ~ dbern(pi_pa_normalized[h, i, j, 1:ntbins, v])

        } # close v
      } # close j
    } # close i
  } # close h
} # end model
</code>```

Line 115 of the model is the very last line and clearly there is nothing on that line that is wrong. I'm guessing there is some missing parenthesis or bracket or something. Could anybody help me figure out what is causing the issue here?

I looked through all the brackets to make sure there were the correct pairs of open and closed brackets, but I couldn't find anything wrong.

Body:
I have created a model to investigate the effects of covariates on occupancy of different bird species at different points across different properties. However, when I try to run the model using rjags, I get this error: Error parsing model file: syntax error on line 115 near "#"

Here is my full model:

model{
#-----------------------------------------------------------------------------------------------------
# 1) Priors
#-----------------------------------------------------------------------------------------------------

  ######## Abundance ########
  mean_alpha0.psi ~ dnorm(0, 0.01)   # Mean intercept for occupancy probability for all species
  sd_alpha0 ~ dunif(0, 10)      # Standard deviation on mean abundance for all species
  prec_alpha0 <- 1 / (sd_alpha0 ^ 2)

  for (h in 1:nspecies) {
     alpha0.psi[h] ~ dnorm(mean_alpha0.psi, prec_alpha0) # Mean log abundance per point for species h

    # Uninformative priors on covariates
    alpha1[h] ~ dnorm(mu_alpha1, tau_alpha1) # Effect of fire frequency for each species
    alpha2[h] ~ dnorm(mu_alpha2, tau_alpha2) # Effect of ground cover for each species
    alpha3[h] ~ dnorm(mu_alpha3, tau_alpha3) # Effect of vegetation height for each species
    alpha4[h] ~ dnorm(mu_alpha4, tau_alpha4) # Effect of total basal area for each species
    alpha5[h] ~ dnorm(mu_alpha5, tau_alpha5) # Effect of % deciduous area for each species
  } # close h

  sd_eps ~ dexp(1) # Standard deviation for random property effect
  prec_eps <- 1 / (sd_eps ^ 2) # Precision for random property effect

  for (i in 1:nprops) {
    eps[i] ~ dnorm(0, prec_eps) # Random property effect
  } # close i

  mu_alpha1 ~ dnorm(0, 0.001)
  tau_alpha1 ~ dgamma(0.01, 0.01)

  mu_alpha2 ~ dnorm(0, 0.001)
  tau_alpha2 ~ dgamma(0.01, 0.01)

  mu_alpha3 ~ dnorm(0, 0.001)
  tau_alpha3 ~ dgamma(0.01, 0.01)

  mu_alpha4 ~ dnorm(0, 0.001)
  tau_alpha4 ~ dgamma(0.01, 0.01)

  mu_alpha5 ~ dnorm(0, 0.001)
  tau_alpha5 ~ dgamma(0.01, 0.01)

  ######## Availability #########
  for (h in 1:nspecies) {
    mean_phi0[h] ~ dnorm(0, 0.001)    # Mean availability for each species
    sd_phi0[h] ~ dexp(1)              # Standard deviation of availability for each species
    prec_phi0[h] <- 1 / (sd_phi0[h] ^ 2)

    for (i in 1:nprops) {
      for (j in 1:npoints_site[i]) {
        phi0[h, i, j] ~ dnorm(mean_phi0[h], prec_phi0[h]) # Mean availability for species h at property i and point j
      } # close j
    } # close i
  } # close h

  phi1 ~ dnorm(0, 0.001) # coefficient of day of year in availiabity linear model
  phi2 ~ dnorm(0, 0.001) # coefficient of day of year^2 in availiabity linear model
  phi3 ~ dnorm(0, 0.001) # coefficient of time after sunrise in availiabity linear model
  phi4 ~ dnorm(0, 0.001) # coefficient of temp in availiabity linear model
  phi5 ~ dnorm(0, 0.001) # coefficient of wind in availiabity linear model

#-----------------------------------------------------------------------------------------------------
# 2) Ecological process model
#-----------------------------------------------------------------------------------------------------

  for (h in 1:nspecies) {
    for (i in 1:nprops) {
      for (j in 1:npoints_site[i]) {
        z[h,i,j] ~ dbern(psi[h,i,j]) # True occupancy based on occupancy probability
        psi[h,i,j] <- 1 / (1 + exp(-lpsi.lim[h,i,j]))
        lpsi.lim[i] <- min(999, max(-999, lpsi[i]))
        lpsi[i] <- alpha0.psi[h] + alpha1[h] * fire[i, j] + alpha2[h] * ground[i, j] + alpha3[h] *
          height[i, j] + alpha4[h] * tba[i, j] + alpha5[h] * decid[i, j] + eps[i]

#-----------------------------------------------------------------------------------------------------
# 3) Observational process model
#-----------------------------------------------------------------------------------------------------

        ###### Availability with time removal ######
        for (v in 1:vh[i, j]) {
          # loop over each visit (v) to each site

          # Availability is a function of intercept + covariates

          y[h,i,j,v] ~ dbern(mu.p[h,i,j,v]) # Detection/non-detection
          mu.p[h,i,j,v] <- z[h,i,j] * pa[h,i,j,v]

          logit(p[h,i,j,v]) <- phi0[h, i, j] + phi1 * obs_date[i, j, v] + phi2 * obs_date[i, j, v] * obs_date[i, j, v] + phi3 * obs_time[i, j, v] + phi4 * obs_temp[i, j, v] + phi5 * obs_wind[i, j, v]

          for (z in 1:ntbins) {
            # Probability of being available in each time bin
            # pi_pa in time bin >1 conditional on not being detected before
            pi_pa[h, i, j, z, v] <-
              p[h, i, j, v] * pow(1 - p[h, i, j, v], (z - 1))
            pi_pa_normalized[h, i, j, z, v] <-
              pi_pa[h, i, j, z, v] / pa[h, i, j, v]
          } # close z

          # Probability ever available
          pa[h, i, j, v] <- sum(pi_pa[h, i, j, 1:ntbins, v])

          # Time data - when were detections mentally removed? NOT SURE ABOUT THIS LINE
          ytb[h, i, j, 1:ntbins, v] ~ dbern(pi_pa_normalized[h, i, j, 1:ntbins, v])

        } # close v
      } # close j
    } # close i
  } # close h
} # end model

Line 115 of the model is the very last line and clearly there is nothing on that line that is wrong. I'm guessing there is some missing parenthesis or bracket or something. Could anybody help me figure out what is causing the issue here?

I looked through all the brackets to make sure there were the correct pairs of open and closed brackets, but I couldn't find anything wrong.


问:
how to calculate the formula for lenses to calculate the ray path?
I want to get a formula for creating rays in unity. specifically, I need a calculation for vector2.
if the ray falls from top to bottom on the lens - everything works, but how to make it possible to turn the lens?

```<code>Vector3 startingPosition = position;
RaycastHit2D hit = Physics2D.Raycast(position, direction, maxStepDistance);
if (hit.collider != null)
{
    a = Vector2.SignedAngle(direction, hit.normal);
    if (hit.collider.gameObject.name == "Circle")
    {
        float sin = Mathf.Sin(a * Mathf.Deg2Rad) * (koef1);
        float cos = Mathf.Sqrt(1 - sin * sin);
        direction = new Vector2(sin, -cos);
    }
    else if (hit.collider.gameObject.name == "Circleup")
    {
        a2 = a;
        float sin = Mathf.Sin(a * Mathf.Deg2Rad) * (1 / koef1);
        float cos = Mathf.Sqrt(1 - sin * sin);
        direction = new Vector2(-sin, -cos);
    }
    else direction = Vector2.Reflect(direction, hit.normal);
    position = new Vector2(hit.point.x -0.0001f, hit.point.y -0.0003f);
</code>```

I tried to replace the formulas for the upper and lower collider, but again, it only works one way

Body:
I want to get a formula for creating rays in unity. specifically, I need a calculation for vector2.
if the ray falls from top to bottom on the lens - everything works, but how to make it possible to turn the lens?

Vector3 startingPosition = position;
RaycastHit2D hit = Physics2D.Raycast(position, direction, maxStepDistance);
if (hit.collider != null)
{
    a = Vector2.SignedAngle(direction, hit.normal);
    if (hit.collider.gameObject.name == "Circle")
    {
        float sin = Mathf.Sin(a * Mathf.Deg2Rad) * (koef1);
        float cos = Mathf.Sqrt(1 - sin * sin);
        direction = new Vector2(sin, -cos);
    }
    else if (hit.collider.gameObject.name == "Circleup")
    {
        a2 = a;
        float sin = Mathf.Sin(a * Mathf.Deg2Rad) * (1 / koef1);
        float cos = Mathf.Sqrt(1 - sin * sin);
        direction = new Vector2(-sin, -cos);
    }
    else direction = Vector2.Reflect(direction, hit.normal);
    position = new Vector2(hit.point.x -0.0001f, hit.point.y -0.0003f);

I tried to replace the formulas for the upper and lower collider, but again, it only works one way


问:
Error while cloning Thunderbird's Mercurial repository
I wanted to clone the Mozilla Thunderbird repository to my PC.

I used the official guide (here) and tried to clone several times, but after a few minutes it always throws an error.

there is always the same following error message:

```<code>abort: An existing connection was forcibly closed by the remote host
transaction abort!
rollback completed
[Code 255]
</code>```

I used this command for cloning:

hg clone --verbose https://hg.mozilla.org/mozilla-central "C:\Users\...\source\"

(userpath shortened)

Body:
I wanted to clone the Mozilla Thunderbird repository to my PC.

I used the official guide (here) and tried to clone several times, but after a few minutes it always throws an error.

there is always the same following error message:

abort: An existing connection was forcibly closed by the remote host
transaction abort!
rollback completed
[Code 255]

I used this command for cloning:

hg clone --verbose https://hg.mozilla.org/mozilla-central "C:\Users\...\source\"

(userpath shortened)


问:
Cannot upgrade extension postgres_fdw, due to: has no update path from version "1.0" to version "1.1"
I am trying to upgrade My postgres DBs from postgres 10 to 14, after looking at the extension version here https://docs.aws.amazon.com/AmazonRDS/latest/PostgreSQLReleaseNotes/postgresql-extensions.html#postgresql-extensions-14x I need to upgrade postgres_fdw to 1.1.

However I am getting the below error when i run the upgrade command.

ALTER EXTENSION postgres_fdw UPDATE TO '1.1'

SQL Error [22023]: ERROR: extension "postgres_fdw" has no update path from version "1.0" to version "1.1"


问:
Spring application with EmptyInterceptor no longer calling `onSave` or `onFlushDirty` in tests
We have a Spring Boot 2.4.5 application that uses a custom EmptyInterceptor. This interceptor is working in both the application and the tests where both the onSave and onFlushDirty methods are being executed properly.

We just updated to Boot which also upgrades Hibernate and JUnit along with many other libraries (details below). With this upgrade, our application still works as expected but for some reason, the interceptor's onSave and onFlushDirty methods are not being executed. We do see other interceptor methods being executed so we can assume that the interceptor is properly registered.

I've been combing through release notes for Spring, Spring JPA, and Hibernate but can't find anything that appears to be related to how this works. Is there something we're missing as part of the upgrade that may be related to changing the way the interceptor works?

Technical details:

Our custom interceptor:

```<code>@Component
public class AuditedEntityInterceptor extends EmptyInterceptor implements BeanFactoryAware
</code>```

.. which is then wired into the application by:

```<code>@Configuration
@Slf4j
public class HibernateInterceptorConfig implements HibernatePropertiesCustomizer {

    @Autowired
    private AuditedEntityInterceptor auditedEntityInterceptor;

    //...

    @Override
    public void customize(Map<String, Object> hibernateProperties)
    {
        hibernateProperties.put("hibernate.session_factory.interceptor", auditedEntityInterceptor);

        //...
    }

}
</code>```

I'm trying to not overload this question with too much detail but it's probably important how our integration tests are configured:

```<code>// Each single integration test is structured like:
@Transactional
public class SomethingSomethingServiceIT extends AppSharedIT

@SpringBootTest(classes = { AppSharedItConfig.class })
public abstract class AppSharedIT extends AppSupportHsqlIT

@SpringBootTest(classes = AppSupportItConfig.class)
@Sql(scripts = {
        // ... a bunch of SQL scripts to initialize reference data
})
@Transactional
@ActiveProfiles(profiles = { "test" })
public abstract class AppHsqlIT implements BeanFactoryAware

@Configuration
@EnableAutoConfiguration(exclude = { QuartzAutoConfiguration.class })
@Import({ AppSupportConfig.class })
@ComponentScan(basePackages = {
        //...
})
public class AppSupportItConfig

@Configuration
@EnableTransactionManagement
@EntityScan({
        //...
})
@EnableJpaRepositories({
        //...
})
@ComponentScan(
        basePackages = {
                //...
        })
@Import(value = { //...
        HibernateInterceptorConfig.class })
public class AppSupportConfig

</code>```

Among many other libraries, I've been focusing on the following version changes:

```<code>junit-jupiter:         5.7.1 -> 5.8.2
spring-boot:           2.4.5 -> 2.7.4
hibernate-core: 5.4.30.Final -> 5.6.11.Final
</code>```

Body:
We have a Spring Boot 2.4.5 application that uses a custom EmptyInterceptor. This interceptor is working in both the application and the tests where both the onSave and onFlushDirty methods are being executed properly.

We just updated to Boot which also upgrades Hibernate and JUnit along with many other libraries (details below). With this upgrade, our application still works as expected but for some reason, the interceptor's onSave and onFlushDirty methods are not being executed. We do see other interceptor methods being executed so we can assume that the interceptor is properly registered.

I've been combing through release notes for Spring, Spring JPA, and Hibernate but can't find anything that appears to be related to how this works. Is there something we're missing as part of the upgrade that may be related to changing the way the interceptor works?

Technical details:

Our custom interceptor:

@Component
public class AuditedEntityInterceptor extends EmptyInterceptor implements BeanFactoryAware

.. which is then wired into the application by:

@Configuration
@Slf4j
public class HibernateInterceptorConfig implements HibernatePropertiesCustomizer {

    @Autowired
    private AuditedEntityInterceptor auditedEntityInterceptor;

    //...

    @Override
    public void customize(Map<String, Object> hibernateProperties)
    {
        hibernateProperties.put("hibernate.session_factory.interceptor", auditedEntityInterceptor);

        //...
    }

}

I'm trying to not overload this question with too much detail but it's probably important how our integration tests are configured:

// Each single integration test is structured like:
@Transactional
public class SomethingSomethingServiceIT extends AppSharedIT

@SpringBootTest(classes = { AppSharedItConfig.class })
public abstract class AppSharedIT extends AppSupportHsqlIT

@SpringBootTest(classes = AppSupportItConfig.class)
@Sql(scripts = {
        // ... a bunch of SQL scripts to initialize reference data
})
@Transactional
@ActiveProfiles(profiles = { "test" })
public abstract class AppHsqlIT implements BeanFactoryAware

@Configuration
@EnableAutoConfiguration(exclude = { QuartzAutoConfiguration.class })
@Import({ AppSupportConfig.class })
@ComponentScan(basePackages = {
        //...
})
public class AppSupportItConfig

@Configuration
@EnableTransactionManagement
@EntityScan({
        //...
})
@EnableJpaRepositories({
        //...
})
@ComponentScan(
        basePackages = {
                //...
        })
@Import(value = { //...
        HibernateInterceptorConfig.class })
public class AppSupportConfig

Among many other libraries, I've been focusing on the following version changes:

junit-jupiter:         5.7.1 -> 5.8.2
spring-boot:           2.4.5 -> 2.7.4
hibernate-core: 5.4.30.Final -> 5.6.11.Final


问:
GetService(typeof(IConfiguration)) method in Validation attribute returns null object
I am trying to get a service of type IConfiguration in my validation attribute class, it gives null object but strangely if I out a debug point on the next line after creating the service object it gives the object instead of null. I am not sure about this is something like late binding stuff.

here is my code,

```<code>public class QuoteValidator : ValidationAttribute
{
    private int _coverageId;
    public QuoteValidator(int coverageId)
    {
        _coverageId = coverageId;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();
        var configuration = (IConfiguration)validationContext
            .GetService(typeof(IConfiguration));
        var planDataService = new CoverageDataService(configuration);
        {
            var coverages = planDataService.GetAll();
        }

        return ValidationUtil.IsValid(value, validationContext);
    }
}
</code>```

I have Injected this service as

```<code>services.AddSingleton<IConfiguration>(provider => configuration);
</code>```

and I am using this validation attribute in my model as

```<code>[Required, QuoteValidator(coverageId: 1)]
    public Quote Quote { get; set; }
</code>```

Need help to understand what is going wrong and why does it provide object only in debug mode.
Is there a way to handle this?

Body:
I am trying to get a service of type IConfiguration in my validation attribute class, it gives null object but strangely if I out a debug point on the next line after creating the service object it gives the object instead of null. I am not sure about this is something like late binding stuff.

here is my code,

public class QuoteValidator : ValidationAttribute
{
    private int _coverageId;
    public QuoteValidator(int coverageId)
    {
        _coverageId = coverageId;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();
        var configuration = (IConfiguration)validationContext
            .GetService(typeof(IConfiguration));
        var planDataService = new CoverageDataService(configuration);
        {
            var coverages = planDataService.GetAll();
        }

        return ValidationUtil.IsValid(value, validationContext);
    }
}

I have Injected this service as

services.AddSingleton<IConfiguration>(provider => configuration);

and I am using this validation attribute in my model as

[Required, QuoteValidator(coverageId: 1)]
    public Quote Quote { get; set; }

Need help to understand what is going wrong and why does it provide object only in debug mode.
Is there a way to handle this?


问:
Qt Top Item remove
```<code>    QList<QListWidgetItem*> items = ui->listWidget->selectedItems();
    foreach(QListWidgetItem * item, items)
    {
         delete item;
    }
</code>```

The above function deletes the item selected in the qtlist. I want to delete the top item present on the list

Title: Qt Top Item remove

Body:
    QList<QListWidgetItem*> items = ui->listWidget->selectedItems();
    foreach(QListWidgetItem * item, items)
    {
         delete item;
    }

The above function deletes the item selected in the qtlist. I want to delete the top item present on the list


问:
How to search for MongoDB documents by name using an API GET endpoint?
I currently have a list of businesses in a MongoDB database (the data structure can be found below). I would like to create a REST API endpoint to search for documents by "name" instead of "_id".

```<code>[
  {
    "_id": "1",
    "name": "Apple",
    "reviews": [
      {
        "_id": "1",
        "comment": "Good",
      }
    ]
  },
  {
    "_id": "2",
    "name": "Microsoft",
    "reviews": [
      {
        "_id": "1",
        "comment": "Great",
      }
    ]
  }
]
</code>```

Currently, I have a GET API endpoint that utilises the find_one() method where the user can supply the business _id field in the URL and retrieve that business. For example, if the user visits http://localhost:5000/api/v1.0/businesses/1, Apple will be retrieved along with its reviews.

```<code>@app.route("/api/v1.0/businesses/<string:id>", methods=["GET"])
def show_one_business(id):
    business = businesses.find_one({'_id':ObjectId(id)})
    if business is not None:
        business['_id'] = str(business['_id'])
        for review in business['reviews']:
            review['_id'] = str(review['_id'])
        return make_response( jsonify ( [ business ] ), 200 )
    else:
        return make_response( jsonify( {"error" : "Invalid business ID"} ), 404 )
</code>```

How do I create an API endpoint to retrieve Apple by providing its name? I assume it will be similar to the REST API above, but I attempted to change the '_id' values to 'name' values, but that didn't work.

Body:
I currently have a list of businesses in a MongoDB database (the data structure can be found below). I would like to create a REST API endpoint to search for documents by "name" instead of "_id".

[
  {
    "_id": "1",
    "name": "Apple",
    "reviews": [
      {
        "_id": "1",
        "comment": "Good",
      }
    ]
  },
  {
    "_id": "2",
    "name": "Microsoft",
    "reviews": [
      {
        "_id": "1",
        "comment": "Great",
      }
    ]
  }
]

Currently, I have a GET API endpoint that utilises the find_one() method where the user can supply the business _id field in the URL and retrieve that business. For example, if the user visits http://localhost:5000/api/v1.0/businesses/1, Apple will be retrieved along with its reviews.

@app.route("/api/v1.0/businesses/<string:id>", methods=["GET"])
def show_one_business(id):
    business = businesses.find_one({'_id':ObjectId(id)})
    if business is not None:
        business['_id'] = str(business['_id'])
        for review in business['reviews']:
            review['_id'] = str(review['_id'])
        return make_response( jsonify ( [ business ] ), 200 )
    else:
        return make_response( jsonify( {"error" : "Invalid business ID"} ), 404 )

How do I create an API endpoint to retrieve Apple by providing its name? I assume it will be similar to the REST API above, but I attempted to change the '_id' values to 'name' values, but that didn't work.


问:
How to "build" static content into index.html in a react app?
I am building a react app. The app has some text content and a calculator. Both the text content and the calculator are different components in the app.

When I build the app (using parceljs), the index.html has a

 and a script tag


问:
React Swiper Property 'slidesPerView' does not exist on type 'IntrinsicAttributes & RefAttributes<SwiperRef> & SwiperProps'
I'm using React, Typescript and Swiper. I'm also on Shopify Hydrogen  with server components. Which maybe preventing the files from finding the type definitions because creating a new Typscript app and installing Swiper doesn't have this issue.

Running "swiper": "^8.4.5", react": "^18.2.0", "@shopify/hydrogen": "^1.6.0",

Property 'slidesPerView' does not exist on type 'IntrinsicAttributes & RefAttributes<SwiperRef> & SwiperProps'

It's not just slidesPerView, but other props as well.

Is there anything else I need to install?
I ran yarn add swiper

my component looks like.

```<code>import {Swiper, SwiperSlide, SwiperRef} from 'swiper/react'

// Import Swiper styles
import 'swiper/css'

return (
    <Swiper
      ref={swiperRef}
      slidesPerView={3}
      spaceBetween={30}
    >
      {slides.map((slide) => {
        return (
          <SwiperSlide key={slide.id}>
            <Image ... />
          </SwiperSlide>
        )
      })}
    </Swiper>
</code>```

Body:
I'm using React, Typescript and Swiper. I'm also on Shopify Hydrogen  with server components. Which maybe preventing the files from finding the type definitions because creating a new Typscript app and installing Swiper doesn't have this issue.

Running "swiper": "^8.4.5", react": "^18.2.0", "@shopify/hydrogen": "^1.6.0",

Property 'slidesPerView' does not exist on type 'IntrinsicAttributes & RefAttributes<SwiperRef> & SwiperProps'

It's not just slidesPerView, but other props as well.

Is there anything else I need to install?
I ran yarn add swiper

my component looks like.

import {Swiper, SwiperSlide, SwiperRef} from 'swiper/react'

// Import Swiper styles
import 'swiper/css'

return (
    <Swiper
      ref={swiperRef}
      slidesPerView={3}
      spaceBetween={30}
    >
      {slides.map((slide) => {
        return (
          <SwiperSlide key={slide.id}>
            <Image ... />
          </SwiperSlide>
        )
      })}
    </Swiper>


问:
SQL State: 42000 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
I'm trying to import data into a MySQL database using Java and I'm getting this error:

```<code>insert into employee(emp_id, name, dob, email, phone_no, account_number, wage_type, wage_rate, admin_id)values('20002','A B',STR_TO_DATE('20/03/10','%d/%m/%y'),'CGUltimateno1@gmail.com','02194024245','934546','Monthly',''2000,20002')'
SQL State: 42000
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2000,20002')'' at line 1
</code>```

Here's the inserting code:

```<code>   query = "insert into employee(emp_id, name, dob, email, phone_no, account_number, wage_type, wage_rate, admin_id)" +
"values('" + emp.getEmp_id() + "','" + emp.getName() + "','" + "STR_TO_DATE('" + emp.getDob() + "','%d/%m/%y')" + "','" + emp.getEmail() + "','" + emp.getPhone_no() + "','" +  emp.getAccount_number() + "','" + emp.getWage_type() + "','" + emp.getWage_rate() + "',''" + emp.getAdmin_id() + "')'";
</code>```

I tried to play around removing the extra ' and " but no luck yet I'm sure the issue is in it

Body:
I'm trying to import data into a MySQL database using Java and I'm getting this error:

insert into employee(emp_id, name, dob, email, phone_no, account_number, wage_type, wage_rate, admin_id)values('20002','A B',STR_TO_DATE('20/03/10','%d/%m/%y'),'CGUltimateno1@gmail.com','02194024245','934546','Monthly',''2000,20002')'
SQL State: 42000
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2000,20002')'' at line 1

Here's the inserting code:

   query = "insert into employee(emp_id, name, dob, email, phone_no, account_number, wage_type, wage_rate, admin_id)" +
"values('" + emp.getEmp_id() + "','" + emp.getName() + "','" + "STR_TO_DATE('" + emp.getDob() + "','%d/%m/%y')" + "','" + emp.getEmail() + "','" + emp.getPhone_no() + "','" +  emp.getAccount_number() + "','" + emp.getWage_type() + "','" + emp.getWage_rate() + "',''" + emp.getAdmin_id() + "')'";

I tried to play around removing the extra ' and " but no luck yet I'm sure the issue is in it


问:
Redux function not available in react-native component
Below I have listed some code I have that should call a function called fetchOverview() when the component loads. I am using redux here. However, the problem is that each time I get an error saying:

TypeError: props.fetchOverview is not a function. (In
'props.fetchOverview()', 'props.fetchOverview' is undefined)

I am at a loss as to what I am missing here, since everything seems to map correctly. Here is the key code from the component:

```<code>import { connect } from 'react-redux';

import {
  fetchOverview,
} from '../state/actions';

export const OverviewScreen = (props) => {
  console.log('props in OverviewScreen: ', props); // fetchOverview not here
  console.log('props.isFetching: ', props.isFetching); // undefined
  useEffect(() => {
    props.fetchOverview();
  }, []);
  // More code
}

const mapStateToProps = (state) => {
  return {
    isFetching: state.Overview.isFetching,
  };
};

const mapDispatchToProps = (dispatch) => ({
  fetchOverview: () => dispatch(fetchOverview()),
});

export default connect(mapStateToProps, mapDispatchToProps)(OverviewScreen);
</code>```

And the fetchOverview() function is long, but basically looks like this:

```<code>export const fetchOverview = () => {
  console.log('fetchOverview() is firing...'); // Never runs
  return async (dispatch, getState) => {
    // Get local overview from disk
    // Other code
  }
}
</code>```

Body:
Below I have listed some code I have that should call a function called fetchOverview() when the component loads. I am using redux here. However, the problem is that each time I get an error saying:

TypeError: props.fetchOverview is not a function. (In
'props.fetchOverview()', 'props.fetchOverview' is undefined)

I am at a loss as to what I am missing here, since everything seems to map correctly. Here is the key code from the component:

import { connect } from 'react-redux';

import {
  fetchOverview,
} from '../state/actions';

export const OverviewScreen = (props) => {
  console.log('props in OverviewScreen: ', props); // fetchOverview not here
  console.log('props.isFetching: ', props.isFetching); // undefined
  useEffect(() => {
    props.fetchOverview();
  }, []);
  // More code
}

const mapStateToProps = (state) => {
  return {
    isFetching: state.Overview.isFetching,
  };
};

const mapDispatchToProps = (dispatch) => ({
  fetchOverview: () => dispatch(fetchOverview()),
});

export default connect(mapStateToProps, mapDispatchToProps)(OverviewScreen);

And the fetchOverview() function is long, but basically looks like this:

export const fetchOverview = () => {
  console.log('fetchOverview() is firing...'); // Never runs
  return async (dispatch, getState) => {
    // Get local overview from disk
    // Other code
  }
}


问:
Incorrect sorting of double numbers using JQuery DataTable
I have sorted the data in the table using jQuery DataTable(). I have a problem when I try to sort a column that has a double type, then I have an incorrect sorting, but at the same time columns that have a string and int data type are sorted in the right order. How can this be fixed?

Model:

```<code>public partial class Asteroids
{
     [DisplayName("Астероид")]
     public int AstId { get; set; }
     [DisplayName("Звезда")]
     public int? StarId { get; set; }

     [Required(ErrorMessage = "Не указано название астероида!")]
     [StringLength(50, ErrorMessage = "Длина строки должна быть до 50 символов")]
     [DisplayName("Название")]
     public string AstName { get; set; }

     [Range(1, int.MaxValue, ErrorMessage = "Диаметр должен быть положителен")]
     [DisplayName("Диаметр (км)")]
     public int? AstDiameter { get; set; }

     [Range(0, int.MaxValue, ErrorMessage = "Эксцентриситет должен быть положителен")]
     [DisplayName("Эксцентриситет")]
     public double? AstOrbitalEccentricity { get; set; }

     [Range(1, int.MaxValue, ErrorMessage = "Наклонение должно быть положительно")]
     [DisplayName("Наклонение (°)")]
     public double? AstOrbitalInclination { get; set; }

     [Range(1, int.MaxValue, ErrorMessage = "Аргумент перицентра должен быть положителен")]
     [DisplayName("Аргумент перицентра (°)")]
     public double? AstArgumentOfPerihelion { get; set; }

     [Range(1, int.MaxValue, ErrorMessage = "Средняя аномалия должна быть положительна")]
     [DisplayName("Средняя аномалия (°)")]
     public double? AstMeanAnomaly { get; set; }

     [DisplayName("Звезда")]
     public virtual Stars Star { get; set; }

    }

</code>```

View:

```<code>@model IEnumerable<Space.Models.Asteroids>

@{
    ViewData["Title"] = "Астероиды";
}

<h1>Астероиды</h1>

<link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />

<p>
    <a asp-action="Create">Добавить</a>
</p>
<hr />

<table id="table" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.AstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.AstDiameter)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.AstOrbitalEccentricity)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.AstOrbitalInclination)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.AstArgumentOfPerihelion)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.AstMeanAnomaly)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Star)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr class="Search">
            <td>
                @Html.DisplayFor(modelItem => item.AstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.AstDiameter)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.AstOrbitalEccentricity)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.AstOrbitalInclination)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.AstArgumentOfPerihelion)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.AstMeanAnomaly)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Star.StarName)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.AstId">Изменить</a> |
                <a asp-action="Details" asp-route-id="@item.AstId">Детали</a> |
                <a asp-action="Delete" asp-route-id="@item.AstId">Удалить</a>
            </td>
        </tr>
}
    </tbody>
</table>

@section Scripts {

    <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
    <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script>
    <script src="~/js/customerDatatable.js"></script>

    <script>
        $(document).ready(function () {
            $('#table').DataTable();
            $('.dataTables_length').addClass('bs-select');
        });
    </script>

}

</code>```

For example, the column "Inclination" is sorted in ascending order:enter image description here

Body:
I have sorted the data in the table using jQuery DataTable(). I have a problem when I try to sort a column that has a double type, then I have an incorrect sorting, but at the same time columns that have a string and int data type are sorted in the right order. How can this be fixed?

Model:

public partial class Asteroids
{
     [DisplayName("Астероид")]
     public int AstId { get; set; }
     [DisplayName("Звезда")]
     public int? StarId { get; set; }

     [Required(ErrorMessage = "Не указано название астероида!")]
     [StringLength(50, ErrorMessage = "Длина строки должна быть до 50 символов")]
     [DisplayName("Название")]
     public string AstName { get; set; }

     [Range(1, int.MaxValue, ErrorMessage = "Диаметр должен быть положителен")]
     [DisplayName("Диаметр (км)")]
     public int? AstDiameter { get; set; }

     [Range(0, int.MaxValue, ErrorMessage = "Эксцентриситет должен быть положителен")]
     [DisplayName("Эксцентриситет")]
     public double? AstOrbitalEccentricity { get; set; }

     [Range(1, int.MaxValue, ErrorMessage = "Наклонение должно быть положительно")]
     [DisplayName("Наклонение (°)")]
     public double? AstOrbitalInclination { get; set; }

     [Range(1, int.MaxValue, ErrorMessage = "Аргумент перицентра должен быть положителен")]
     [DisplayName("Аргумент перицентра (°)")]
     public double? AstArgumentOfPerihelion { get; set; }

     [Range(1, int.MaxValue, ErrorMessage = "Средняя аномалия должна быть положительна")]
     [DisplayName("Средняя аномалия (°)")]
     public double? AstMeanAnomaly { get; set; }

     [DisplayName("Звезда")]
     public virtual Stars Star { get; set; }

    }

View:

@model IEnumerable<Space.Models.Asteroids>

@{
    ViewData["Title"] = "Астероиды";
}

Астероиды

<link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />

    Добавить

                @Html.DisplayNameFor(model => model.AstName)

                @Html.DisplayNameFor(model => model.AstDiameter)

                @Html.DisplayNameFor(model => model.AstOrbitalEccentricity)

                @Html.DisplayNameFor(model => model.AstOrbitalInclination)

                @Html.DisplayNameFor(model => model.AstArgumentOfPerihelion)

                @Html.DisplayNameFor(model => model.AstMeanAnomaly)

                @Html.DisplayNameFor(model => model.Star)

@foreach (var item in Model) {

                @Html.DisplayFor(modelItem => item.AstName)

                @Html.DisplayFor(modelItem => item.AstDiameter)

                @Html.DisplayFor(modelItem => item.AstOrbitalEccentricity)

                @Html.DisplayFor(modelItem => item.AstOrbitalInclination)

                @Html.DisplayFor(modelItem => item.AstArgumentOfPerihelion)

                @Html.DisplayFor(modelItem => item.AstMeanAnomaly)

                @Html.DisplayFor(modelItem => item.Star.StarName)

                Изменить |
                Детали |
                Удалить

}

@section Scripts {

}

For example, the column "Inclination" is sorted in ascending order:enter image description here


问:
Tell PIP to install only the dependencies which can be satisfied
I'm installing a local module that relies on a bunch of local modules written by others. This means that sometimes everyone's versioning is out-of-sync, so running pip -e [package] results in a bunch of errors when it comes to installing the dependencies that are other local modules. For example:

Module A relies on Module B. But Module B throws an syntax error when pip tries installing it.

For now, I'd like to tell pip to install every dependency it can install, and pipe all errors to a file or something.

Running each line in the module's requirements.txt won't work because I'm using pip install -e [module]. I do not want to change it or its setup.py

--ignore-installed only works if the dependency is already installed

--no-deps doesn't try to install dependencies at all

I'd specifically like pip to exit with something like: "Installed package with some errors: ..." (i.e., I'd like it to install all the dependencies it can install while ignoring the ones it can't)


问:
How come my compiler isn't able to see these functions I've created?
So I'm currently trying to work through a book called "Crafting Interpreters" and it goes step by step through making a language. I'm writing this language in C and already running into issues. I have a couple header files with respective c files and then the main driver code. When I try to compile the code, I get this error:
compiler error msg
I'm not sure what's going wrong here as I have other projects using header files and they are able to compile correctly.

```<code></code>```
```<code>//main
#include "common.h"
#include "chunk.h"

int main(int argc, const char* argv[]) {
    Chunk chunk;
    initChunk(&chunk);
    writeChunk(&chunk, OP_RETURN);
    freeChunk(&chunk);
    return 0;
}
</code>```
```<code>//common.h
#ifndef clox_common_h
#define clox_common_h

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#endif
</code>```
```<code>//chunk.h
#ifndef clox_chunk_h
#define clox_chunk_h

#include "common.h"

typedef enum {
    OP_RETURN,
} OpCode;

typedef struct {
    int count;
    int capacity;
    uint8_t* code;
} Chunk;

void initChunk(Chunk* chunk);
void freeChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);

#endif
</code>```
```<code>//chunk.c
#include <stdlib.h>

#include "chunk.h"
#include "memory.h"

void initChunk(Chunk* chunk) {
    chunk->count = 0;
    chunk->capacity = 0;
    chunk->code = NULL;
}

void freeChunk(Chunk* chunk) {
    FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
    initChunk(chunk);
}

void writeChunk(Chunk* chunk, uint8_t byte) {
    if (chunk->capacity < chunk->count) {
        int oldCapacity = chunk->capacity;
        chunk->capacity = GROW_CAPACITY(oldCapacity);
        chunk->code = GROW_ARRAY(uint8_t, chunk->code,
            oldCapacity, chunk->capacity);
    }

    chunk->code[chunk->count] = byte;
    chunk->count++;
}
</code>```
```<code>//memory.h
#ifndef clox_memory_h
#define clox_memory_h

#include "common.h"

#define GROW_CAPACITY(capacity) \
    ((capacity) < 8 ? 8 : (capacity) * 2)

#define GROW_ARRAY(type, pointer, oldCount, newCount) \
    (type*)reallocate(pointer, sizeof(type) * (oldCount), \
        sizeof(type) * (newCount))

#define FREE_ARRAY(type, pointer, oldCount) \
    reallocate(pointer, sizeof(type) * (oldCount), 0)

void* reallocate(void* pointer, size_t oldSize, size_t newSize);

#endif
</code>```
```<code>//memory.c
#include <stdlib.h>

#include "memory.h"

void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
    if (newSize == 0) {
        free(pointer);
        return NULL;
    }

    void* result = realloc(pointer, newSize);
    if (result == NULL) exit(1);
    return result;
}
</code>```

Any guidance would be appreciated

Body:
So I'm currently trying to work through a book called "Crafting Interpreters" and it goes step by step through making a language. I'm writing this language in C and already running into issues. I have a couple header files with respective c files and then the main driver code. When I try to compile the code, I get this error:
compiler error msg
I'm not sure what's going wrong here as I have other projects using header files and they are able to compile correctly.

//main
#include "common.h"
#include "chunk.h"

int main(int argc, const char* argv[]) {
    Chunk chunk;
    initChunk(&chunk);
    writeChunk(&chunk, OP_RETURN);
    freeChunk(&chunk);
    return 0;
}

//common.h
#ifndef clox_common_h
#define clox_common_h

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#endif

//chunk.h
#ifndef clox_chunk_h
#define clox_chunk_h

#include "common.h"

typedef enum {
    OP_RETURN,
} OpCode;

typedef struct {
    int count;
    int capacity;
    uint8_t* code;
} Chunk;

void initChunk(Chunk* chunk);
void freeChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);

#endif

//chunk.c
#include <stdlib.h>

#include "chunk.h"
#include "memory.h"

void initChunk(Chunk* chunk) {
    chunk->count = 0;
    chunk->capacity = 0;
    chunk->code = NULL;
}

void freeChunk(Chunk* chunk) {
    FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
    initChunk(chunk);
}

void writeChunk(Chunk* chunk, uint8_t byte) {
    if (chunk->capacity < chunk->count) {
        int oldCapacity = chunk->capacity;
        chunk->capacity = GROW_CAPACITY(oldCapacity);
        chunk->code = GROW_ARRAY(uint8_t, chunk->code,
            oldCapacity, chunk->capacity);
    }

    chunk->code[chunk->count] = byte;
    chunk->count++;
}

//memory.h
#ifndef clox_memory_h
#define clox_memory_h

#include "common.h"

#define GROW_CAPACITY(capacity) \
    ((capacity) < 8 ? 8 : (capacity) * 2)

#define GROW_ARRAY(type, pointer, oldCount, newCount) \
    (type*)reallocate(pointer, sizeof(type) * (oldCount), \
        sizeof(type) * (newCount))

#define FREE_ARRAY(type, pointer, oldCount) \
    reallocate(pointer, sizeof(type) * (oldCount), 0)

void* reallocate(void* pointer, size_t oldSize, size_t newSize);

#endif

//memory.c
#include <stdlib.h>

#include "memory.h"

void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
    if (newSize == 0) {
        free(pointer);
        return NULL;
    }

    void* result = realloc(pointer, newSize);
    if (result == NULL) exit(1);
    return result;
}

Any guidance would be appreciated


问:
IntelliJ TypeScript barrel file: Way to jump to the original file with Ctrl + click?
I have some barrel files in my project to improve bundling. One annoyance is that I must jump through the barrel file to reach the original file with Ctrl + Click.

Is there a way or a plugin to get me directly to the original file?