问:
DevTools memory tab has no profile tab
The guide says there should be a Profile tab inside the Memory tab, but it's missing from both the VSCode version and Chrome browser version. No Diff or Trace tab either. This is a iOS app running in profile mode. What can I do to make it show?

```<code>[✓] Flutter (Channel stable, 3.3.3, on macOS 12.6 21G115 darwin-x64, locale en-CA)
[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
[✓] Xcode - develop for iOS and macOS (Xcode 14.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.1) [✓] VS Code (version 1.74.0)
[✓] HTTP Host Availability

    • No issues found!
</code>```

Title: DevTools memory tab has no profile tab

Body:
The guide says there should be a Profile tab inside the Memory tab, but it's missing from both the VSCode version and Chrome browser version. No Diff or Trace tab either. This is a iOS app running in profile mode. What can I do to make it show?

[✓] Flutter (Channel stable, 3.3.3, on macOS 12.6 21G115 darwin-x64, locale en-CA)
[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
[✓] Xcode - develop for iOS and macOS (Xcode 14.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.1) [✓] VS Code (version 1.74.0)
[✓] HTTP Host Availability

    • No issues found!


来源: stackexchange

问:
Can't read result after sending AT commands to GSM modem with java and jssc
I need to send AT commands to a concrete port and get the response

```<code>public static void main(String[] args) throws InterruptedException {
    try {
        String[] portNames = SerialPortList.getPortNames();

        if (portNames.length < 1) {
            System.out.println("No ports available");
            System.exit(0);
        } else {
            serialPort = new SerialPort("COM25");
        }
        System.out.println("Port opened: " + serialPort.openPort());
        System.out.println("Params set: " + serialPort.setParams(9600, 8, 1, 0));

        serialPort.writeBytes("AT\r\n".getBytes());
        serialPort.closePort();
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }
}
</code>```

Code executes perfectly but all i have in console is:

As i understand this error is not crucial, but still i'm not getting and answer from port that i need. So the QUESTION IS: how can i get the answer on my request from concrete port on concrete AT command.

ContentLicense: CC BY-SA 4.0

Body:
I need to send AT commands to a concrete port and get the response

public static void main(String[] args) throws InterruptedException {
    try {
        String[] portNames = SerialPortList.getPortNames();

        if (portNames.length < 1) {
            System.out.println("No ports available");
            System.exit(0);
        } else {
            serialPort = new SerialPort("COM25");
        }
        System.out.println("Port opened: " + serialPort.openPort());
        System.out.println("Params set: " + serialPort.setParams(9600, 8, 1, 0));

        serialPort.writeBytes("AT\r\n".getBytes());
        serialPort.closePort();
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }
}

Code executes perfectly but all i have in console is:

As i understand this error is not crucial, but still i'm not getting and answer from port that i need. So the QUESTION IS: how can i get the answer on my request from concrete port on concrete AT command.


问:
How to adjust the size of cells in a Manim table?
I am trying to create a balance sheet animation with Manim. The problem is that if the text in one column is larger than the text in another, the sides of the balance sheet are off-centre. Adding spaces has not worked. Neither did using my_table.move_to(vertical_line.get_center()) nor using .shift().

White: T of balance sheet. Blue: Inner lines of the table.


问:
react-codemirror2 controlled usage, What's the purpose of onChange?
Referring to the github page example below react-codemirror2-github

```<code>import {Controlled as CodeMirror} from 'react-codemirror2'
<CodeMirror
    value={this.state.value}
    options={options}
    onBeforeChange={(editor, data, value) => {
       this.setState({value});
    }}
    onChange={(editor, data, value) => {
    }}
/>
</code>```

I used the example and it works, but after testing and removing the onChange it doesn't seem like it matters whether its provided. So as the title states, what's is its purpose for this particular application?  If needed, should the callback be left blank?

Body:
Referring to the github page example below react-codemirror2-github

import {Controlled as CodeMirror} from 'react-codemirror2'
<CodeMirror
    value={this.state.value}
    options={options}
    onBeforeChange={(editor, data, value) => {
       this.setState({value});
    }}
    onChange={(editor, data, value) => {
    }}
/>

I used the example and it works, but after testing and removing the onChange it doesn't seem like it matters whether its provided. So as the title states, what's is its purpose for this particular application?  If needed, should the callback be left blank?


问:
Using nodejs-imap to connect to Office365 outlook email server results in Error: NO LOGIN failed
I'm building a nodejs method that will connect to an Office365 Outlook email inbox and retrieve all unread emails. It uses the nodejs-imap library to achieve this. This is my config for imap:

```<code>const imapConfig = {
    user: process.env.EMAIL_USER,
    password: process.env.EMAIL_PASS,
    host: 'outlook.office365.com',
    port: 993,
    debug: console.log,
    tls: true,
};
</code>```

Sadly when I try connecting to the server I receive these logs and then this error message:

```<code><= '* OK The Microsoft Exchange IMAP4 service is ready. [cgdsfDFgBvAGfsdsgQALgB....]'
=> 'A0 CAPABILITY'
<= '* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+'
<= 'A0 OK CAPABILITY completed.'
=> 'A1 LOGIN "<email>" "<password>"'
<= 'A1 NO LOGIN failed.'
Error: LOGIN failed.
</code>```

I'm quite sure the credentials I'm using are correct, as I'm able to login my Microsoft account in a browser using them, so I'm a bit stuck on what the issue actually is.

Any help would be appreciated.

Body:
I'm building a nodejs method that will connect to an Office365 Outlook email inbox and retrieve all unread emails. It uses the nodejs-imap library to achieve this. This is my config for imap:

const imapConfig = {
    user: process.env.EMAIL_USER,
    password: process.env.EMAIL_PASS,
    host: 'outlook.office365.com',
    port: 993,
    debug: console.log,
    tls: true,
};

Sadly when I try connecting to the server I receive these logs and then this error message:

<= '* OK The Microsoft Exchange IMAP4 service is ready. [cgdsfDFgBvAGfsdsgQALgB....]'
=> 'A0 CAPABILITY'
<= '* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+'
<= 'A0 OK CAPABILITY completed.'
=> 'A1 LOGIN "<email>" "<password>"'
<= 'A1 NO LOGIN failed.'
Error: LOGIN failed.

I'm quite sure the credentials I'm using are correct, as I'm able to login my Microsoft account in a browser using them, so I'm a bit stuck on what the issue actually is.

Any help would be appreciated.


问:
Hive LOAD DATA INPATH query delete source data (s3)
When i use hive in EMR, I use 'LOAD DATA INPATH' query.

That query deletes the source data. The EMR role I use doesn't have delete permission, so that query always fails. Is there any way to solve this problem?

```<code>LOAD DATA INPATH 's3://my-bucket/folder/data.csv'
OVERWRITE INTO TABLE {my-database}.{my-table};
</code>```

FAILED: Execution Error, return code 1 from
org.apache.hadoop.hive.ql.exec.MoveTask. Unable to move source
s3://my-bucket/folder/data.csv to destination
hdfs://{emr_master_node}:8020/{internal_folder}/data.csv

The query throws an error, but the data loads into the table just fine.

Hive internally sends a delete request after a get request, but the get request succeeds and the delete request fails because EMR does not have permission.

Caused by:
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.model.AmazonS3Exception:
Access Denied (Service: Amazon S3; Status Code: 403; Error Code:
AccessDenied; Request ID: F7XPGZW7BVAFFGBV; S3 Extended Request ID:
9MnXACfWf/y2wr4OklowfrJAzzRMYMT7cfE/OHzldS7L/yR2dYufa5sq3OtloAnVjlRdNzYxWm8=;
Proxy: null)  at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1862)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1415)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1384)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1154)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:811)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:779)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:753)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:713)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:695)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:559)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:539)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5445)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5392)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.deleteObject(AmazonS3Client.java:2295)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.call.DeleteObjectCall.perform(DeleteObjectCall.java:25)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.call.DeleteObjectCall.perform(DeleteObjectCall.java:11)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.executor.GlobalS3Executor$CallPerformer.call(GlobalS3Executor.java:108)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
sun.reflect.GeneratedMethodAccessor135.invoke(Unknown Source) ~[?:?]
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[?:1.8.0_352]    at java.lang.reflect.Method.invoke(Method.java:498)
~[?:1.8.0_352]    at
com.amazon.ws.emr.hadoop.fs.shaded.retry.invocation.ProxyingInvocation.invoke(ProxyingInvocation.java:52)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.policies.aimd.RateAdjustedInvoker$1.get(RateAdjustedInvoker.java:43)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.rateadjuster.RateAdjusted.execute(RateAdjusted.java:231)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.policies.aimd.RateAdjustedInvoker.invoke(RateAdjustedInvoker.java:39)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.invocation.DelegatingInvocation.invoke(DelegatingInvocation.java:47)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.invocation.RetryingInvoker.invoke(RetryingInvoker.java:52)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.policies.aimd.AIMDInvocationHandler.invoke(AIMDInvocationHandler.java:92)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.sun.proxy.$Proxy108.call(Unknown Source) ~[?:?]   at
com.amazon.ws.emr.hadoop.fs.s3.lite.executor.GlobalS3Executor.execute(GlobalS3Executor.java:135)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.AmazonS3LiteClient.invoke(AmazonS3LiteClient.java:191)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.AmazonS3LiteClient.invoke(AmazonS3LiteClient.java:186)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.AmazonS3LiteClient.deleteObject(AmazonS3LiteClient.java:122)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3n.Jets3tNativeFileSystemStore.delete(Jets3tNativeFileSystemStore.java:434)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem.delete(S3NativeFileSystem.java:426)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.EmrFileSystem.delete(EmrFileSystem.java:418)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:423)
~[hadoop-common-3.2.1-amzn-5.jar:?]   at
org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:387)
~[hadoop-common-3.2.1-amzn-5.jar:?]   at
org.apache.hadoop.hive.common.FileUtils.copy(FileUtils.java:633)
~[hive-common-3.1.2-amzn-6.jar:3.1.2-amzn-6]  at
org.apache.hadoop.hive.common.FileUtils.copy(FileUtils.java:600)
~[hive-common-3.1.2-amzn-6.jar:3.1.2-amzn-6]  at
org.apache.hadoop.hive.ql.metadata.Hive.moveFile(Hive.java:3854)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.metadata.Hive.replaceFiles(Hive.java:4318)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.exec.HiveDataCommitter.replaceFiles(HiveDataCommitter.java:69)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.metadata.Hive.loadTable(Hive.java:2458)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.exec.MoveTask.execute(MoveTask.java:376)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.exec.Task.executeTask(Task.java:209)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.exec.TaskRunner.runSequential(TaskRunner.java:97)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.launchTask(Driver.java:2664)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.execute(Driver.java:2335)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:2011)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.run(Driver.java:1709)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.run(Driver.java:1703)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.reexec.ReExecDriver.run(ReExecDriver.java:157)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hive.service.cli.operation.SQLOperation.runQuery(SQLOperation.java:224)
~[hive-service-3.1.2-amzn-6.jar:3.1.2-amzn-6]     ... 11 more

When I checked the bucket access log, it found that the EMR Role makes a Get request and then a Delete request.

I wonder why Hive is requesting move instead of copy.
When I checked the error log above, I found that Hive uses moveTask instead of copyTask.

https://github.com/apache/hive/blob/e427ce0d572c9adf6f194693a1b3ba85f246f3b7/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java#L4865

Also, when I checked the hive code in github, I found that if the source file is not located in local, hive is forced to request to delete the source.

Anyone know the reason for this?

Body:
When i use hive in EMR, I use 'LOAD DATA INPATH' query.

That query deletes the source data. The EMR role I use doesn't have delete permission, so that query always fails. Is there any way to solve this problem?

LOAD DATA INPATH 's3://my-bucket/folder/data.csv'
OVERWRITE INTO TABLE {my-database}.{my-table};

FAILED: Execution Error, return code 1 from
org.apache.hadoop.hive.ql.exec.MoveTask. Unable to move source
s3://my-bucket/folder/data.csv to destination
hdfs://{emr_master_node}:8020/{internal_folder}/data.csv

The query throws an error, but the data loads into the table just fine.

Hive internally sends a delete request after a get request, but the get request succeeds and the delete request fails because EMR does not have permission.

Caused by:
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.model.AmazonS3Exception:
Access Denied (Service: Amazon S3; Status Code: 403; Error Code:
AccessDenied; Request ID: F7XPGZW7BVAFFGBV; S3 Extended Request ID:
9MnXACfWf/y2wr4OklowfrJAzzRMYMT7cfE/OHzldS7L/yR2dYufa5sq3OtloAnVjlRdNzYxWm8=;
Proxy: null)  at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1862)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1415)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1384)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1154)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:811)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:779)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:753)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:713)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:695)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:559)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:539)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5445)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5392)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.deleteObject(AmazonS3Client.java:2295)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.call.DeleteObjectCall.perform(DeleteObjectCall.java:25)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.call.DeleteObjectCall.perform(DeleteObjectCall.java:11)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.executor.GlobalS3Executor$CallPerformer.call(GlobalS3Executor.java:108)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
sun.reflect.GeneratedMethodAccessor135.invoke(Unknown Source) ~[?:?]
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[?:1.8.0_352]    at java.lang.reflect.Method.invoke(Method.java:498)
~[?:1.8.0_352]    at
com.amazon.ws.emr.hadoop.fs.shaded.retry.invocation.ProxyingInvocation.invoke(ProxyingInvocation.java:52)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.policies.aimd.RateAdjustedInvoker$1.get(RateAdjustedInvoker.java:43)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.rateadjuster.RateAdjusted.execute(RateAdjusted.java:231)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.policies.aimd.RateAdjustedInvoker.invoke(RateAdjustedInvoker.java:39)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.invocation.DelegatingInvocation.invoke(DelegatingInvocation.java:47)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.invocation.RetryingInvoker.invoke(RetryingInvoker.java:52)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.shaded.retry.policies.aimd.AIMDInvocationHandler.invoke(AIMDInvocationHandler.java:92)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.sun.proxy.$Proxy108.call(Unknown Source) ~[?:?]   at
com.amazon.ws.emr.hadoop.fs.s3.lite.executor.GlobalS3Executor.execute(GlobalS3Executor.java:135)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.AmazonS3LiteClient.invoke(AmazonS3LiteClient.java:191)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.AmazonS3LiteClient.invoke(AmazonS3LiteClient.java:186)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3.lite.AmazonS3LiteClient.deleteObject(AmazonS3LiteClient.java:122)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3n.Jets3tNativeFileSystemStore.delete(Jets3tNativeFileSystemStore.java:434)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem.delete(S3NativeFileSystem.java:426)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
com.amazon.ws.emr.hadoop.fs.EmrFileSystem.delete(EmrFileSystem.java:418)
~[emrfs-hadoop-assembly-2.48.0.jar:?]     at
org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:423)
~[hadoop-common-3.2.1-amzn-5.jar:?]   at
org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:387)
~[hadoop-common-3.2.1-amzn-5.jar:?]   at
org.apache.hadoop.hive.common.FileUtils.copy(FileUtils.java:633)
~[hive-common-3.1.2-amzn-6.jar:3.1.2-amzn-6]  at
org.apache.hadoop.hive.common.FileUtils.copy(FileUtils.java:600)
~[hive-common-3.1.2-amzn-6.jar:3.1.2-amzn-6]  at
org.apache.hadoop.hive.ql.metadata.Hive.moveFile(Hive.java:3854)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.metadata.Hive.replaceFiles(Hive.java:4318)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.exec.HiveDataCommitter.replaceFiles(HiveDataCommitter.java:69)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.metadata.Hive.loadTable(Hive.java:2458)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.exec.MoveTask.execute(MoveTask.java:376)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.exec.Task.executeTask(Task.java:209)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.exec.TaskRunner.runSequential(TaskRunner.java:97)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.launchTask(Driver.java:2664)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.execute(Driver.java:2335)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:2011)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.run(Driver.java:1709)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.Driver.run(Driver.java:1703)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hadoop.hive.ql.reexec.ReExecDriver.run(ReExecDriver.java:157)
~[hive-exec-3.1.2-amzn-6.jar:3.1.2-amzn-6]    at
org.apache.hive.service.cli.operation.SQLOperation.runQuery(SQLOperation.java:224)
~[hive-service-3.1.2-amzn-6.jar:3.1.2-amzn-6]     ... 11 more

When I checked the bucket access log, it found that the EMR Role makes a Get request and then a Delete request.

I wonder why Hive is requesting move instead of copy.
When I checked the error log above, I found that Hive uses moveTask instead of copyTask.

https://github.com/apache/hive/blob/e427ce0d572c9adf6f194693a1b3ba85f246f3b7/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java#L4865

Also, when I checked the hive code in github, I found that if the source file is not located in local, hive is forced to request to delete the source.

Anyone know the reason for this?


问:
How to form render array from multiple APIs in React

Situation

I need to form a comments timeline which looks like this,

Yet the information comes from 2 different APIs,

API Format

1. Comments API, an array of comments by chronological order

[
  {
    comment: 'Hello, how's your day?',
    userId: '001',
    timestamp: '1670548338131'
  },
  {
    comment: 'Pretty good!',
    userId: '002',
    timestamp: '1670548338151'
  },
  {
    comment: 'Want to hang out later?',
    userId: '001',
    timestamp: '1670548338171'
  },
  ...
]
```
<p><strong>2.</strong> <strong>User info API</strong>, 1 user info per search</p>
<pre class="lang-json prettyprint-override"><code>{
  userId: '001',
  userName: 'Ben',
  userProfileUrl: 'https://www.photo.com/001'
}
</code>```

Questions

What's the better way to call API 2 mutiple times?

What's the better way to form the render array? (Want the highest efficiency)

Although modifying the backend data model would be ideal, I'm under some constraints that I can only manipulate data on the frontend.

Initial Idea

Fetch comments list first, use a Set to collect unique userIds

Use Promise.all to fetch API 2 parallelly with all the userIds within the Set

Form a dictionary (map) to lookup user info by userId

Iterate the list from step 1, fill in user info one by one, and produce a new list

Set the final result list into useState state

Render

const getComments = () => axios.get('API_1')
const getUser = (userId) => axios.get(`API_2/${userId}`)

const [renderList, setRenderList] = React.useState([])

const initComments = async () => {
  try {
    const res = await getComments()
    const rawComments = res.data
    const usersSet = new Set(rawComments.map(c => c.userId))
    const promises = [...usersSet].map(u => getUser(u))

    // Here's the question 1, is it viable?
    const usersInfo = await Promise.all(promises)
    const usersMap = usersInfo.reduce((prev, curr) => {
      return {
        ...prev,
        [curr.data.userId]: curr.data,
      }
    }, {})

    // Here's the question 2, is it the most efficient way?
    const finalList = rawComments.map(c => {
      return {
        ...c,
        userName: usersMap[c.userId].userName,
        userProfileUrl: usersMap[c.userId].userProfileUrl,
      }
    })
    setRenderList(finalList)
  } catch(err) {}
}

React.useEffect(() => {
  initComments()
}, [])

return renderList.map(item => <>{/* Do the render here */}</>)

```

Body:
Situation

I need to form a comments timeline which looks like this,

Yet the information comes from 2 different APIs,

API Format

1. Comments API, an array of comments by chronological order

[
  {
    comment: 'Hello, how's your day?',
    userId: '001',
    timestamp: '1670548338131'
  },
  {
    comment: 'Pretty good!',
    userId: '002',
    timestamp: '1670548338151'
  },
  {
    comment: 'Want to hang out later?',
    userId: '001',
    timestamp: '1670548338171'
  },
  ...
]

2. User info API, 1 user info per search

{
  userId: '001',
  userName: 'Ben',
  userProfileUrl: 'https://www.photo.com/001'
}

Questions

What's the better way to call API 2 mutiple times?

What's the better way to form the render array? (Want the highest efficiency)

Although modifying the backend data model would be ideal, I'm under some constraints that I can only manipulate data on the frontend.

Initial Idea

Fetch comments list first, use a Set to collect unique userIds

Use Promise.all to fetch API 2 parallelly with all the userIds within the Set

Form a dictionary (map) to lookup user info by userId

Iterate the list from step 1, fill in user info one by one, and produce a new list

Set the final result list into useState state

Render

const getComments = () => axios.get('API_1')
const getUser = (userId) => axios.get(`API_2/${userId}`)

const [renderList, setRenderList] = React.useState([])

const initComments = async () => {
  try {
    const res = await getComments()
    const rawComments = res.data
    const usersSet = new Set(rawComments.map(c => c.userId))
    const promises = [...usersSet].map(u => getUser(u))

    // Here's the question 1, is it viable?
    const usersInfo = await Promise.all(promises)
    const usersMap = usersInfo.reduce((prev, curr) => {
      return {
        ...prev,
        [curr.data.userId]: curr.data,
      }
    }, {})

    // Here's the question 2, is it the most efficient way?
    const finalList = rawComments.map(c => {
      return {
        ...c,
        userName: usersMap[c.userId].userName,
        userProfileUrl: usersMap[c.userId].userProfileUrl,
      }
    })
    setRenderList(finalList)
  } catch(err) {}
}

React.useEffect(() => {
  initComments()
}, [])

return renderList.map(item => <>{/* Do the render here */}</>)


问:
How to send pygame live video screen to be displayed in a javascript-based frontend via http?
I have a flask application that uses pygame to do some tasks with the camera. I want the camera screen to be displayed in an angular front-end. I use HTTP protocol to send requests from flask to angular. I think the solution is to send the streaming video screen from flask via HTTP requests. Does anyone have any idea how to do this?

I tried calling a flask function that plays audio from angular using HTTP. But video and pygame are different and can't be shown in the frontend.


问:
Search special keywords with elasticsearch
I using the elasticsearch to use search the key word on my app by go. However, when i  text the keyword is 'not', it return result is null, it not act searching with 'not'. I use the type "phrase_prefix" for filed name.
Thank you!

I try to find the special keywords in elasticsearch query but not found.


问:
How to get the right calculations for EMI personal loan calculator (Singapore)
I want to get the right formula for the monthly payment and total interest and total payment for EMI calculator specifically on Singapore calculations.

I'm referencing these 2 sites:

https://www.gscredit.com.sg/personal-loan-calculator/

https://www.credit21.com.sg/personal-loan-calculator/

I tried to calculate these:

```<code>Loan Amount: 15000
Term Monthly: 12
Interest: 4%
=============================

Calculations I get:
Monthly Payment: $ 1277.25
Total Interest: $ 326.98
Total Payment: $ 15326.98
</code>```

The calculations is basically incorrect. It should be:

```<code>Monthly Installment: $1,598.28
Total Interest: $4,179.36
Total Payment: $19,179.36
</code>```

Can someone help me how to get the right calculations for this, same as these 2 sites I'm referencing with?

Here's my code:

function calculation(){
  var quantity_field_id_0 = document.getElementById("quantity_field_id_0").value;
  var range_field_id_1 = document.getElementById("range_field_id_1").value;
  var range_field_id_2 = document.getElementById("range_field_id_2").value;

  var monthly_payment = quantity_field_id_0 * ( range_field_id_2 / 12 / 100 ) *  ( Math.pow( 1 + ( range_field_id_2 / 12 / 100 ) ,  range_field_id_1 ) / ( Math.pow( 1 + ( range_field_id_2 / 12 / 100 ) ,  range_field_id_1 ) - 1 )  );

  var total_payment = range_field_id_1 *  (monthly_payment);

  var total_interest = total_payment  -  quantity_field_id_0;

  document.getElementById("total_field_id_3").innerHTML = " $ " +monthly_payment.toFixed(2);
  document.getElementById("total_field_id_4").innerHTML = " $ " +total_interest.toFixed(2);
  document.getElementById("total_field_id_5").innerHTML = " $ " +total_payment.toFixed(2);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.form-group {display:block;margin-bottom:10px;}
strong,p,label,input {display:inline-block;vertical:align-top;}

.calculations {background:#ccc;margin-top:30px;border-radius:4px;padding:10px;}</code>```

  Loan Amount:(USD) <input id="quantity_field_id_0" type="number" placeholder="Loan Amount">

  Loan Duration(Months): <input type="number" id="range_field_id_1" placeholder="Term(Monthly)">

  Interest Rate:(%) <input id="range_field_id_2" type="number" placeholder="Interest Rate">

<button type="submit" id="calc" onclick="calculation()">Calculate</button>

    Monthly Payment:

    Total Interest:

    Total Payment:

```

Body:
I want to get the right formula for the monthly payment and total interest and total payment for EMI calculator specifically on Singapore calculations.

I'm referencing these 2 sites:

https://www.gscredit.com.sg/personal-loan-calculator/

https://www.credit21.com.sg/personal-loan-calculator/

I tried to calculate these:

Loan Amount: 15000
Term Monthly: 12
Interest: 4%
=============================

Calculations I get:
Monthly Payment: $ 1277.25
Total Interest: $ 326.98
Total Payment: $ 15326.98

The calculations is basically incorrect. It should be:

Monthly Installment: $1,598.28
Total Interest: $4,179.36
Total Payment: $19,179.36

Can someone help me how to get the right calculations for this, same as these 2 sites I'm referencing with?

Here's my code:

function calculation(){
  var quantity_field_id_0 = document.getElementById("quantity_field_id_0").value;
  var range_field_id_1 = document.getElementById("range_field_id_1").value;
  var range_field_id_2 = document.getElementById("range_field_id_2").value;

  var monthly_payment = quantity_field_id_0 * ( range_field_id_2 / 12 / 100 ) *  ( Math.pow( 1 + ( range_field_id_2 / 12 / 100 ) ,  range_field_id_1 ) / ( Math.pow( 1 + ( range_field_id_2 / 12 / 100 ) ,  range_field_id_1 ) - 1 )  );

  var total_payment = range_field_id_1 *  (monthly_payment);

  var total_interest = total_payment  -  quantity_field_id_0;

  document.getElementById("total_field_id_3").innerHTML = " $ " +monthly_payment.toFixed(2);
  document.getElementById("total_field_id_4").innerHTML = " $ " +total_interest.toFixed(2);
  document.getElementById("total_field_id_5").innerHTML = " $ " +total_payment.toFixed(2);
}

.form-group {display:block;margin-bottom:10px;}
strong,p,label,input {display:inline-block;vertical:align-top;}

.calculations {background:#ccc;margin-top:30px;border-radius:4px;padding:10px;}

  Loan Amount:(USD) <input id="quantity_field_id_0" type="number" placeholder="Loan Amount">

  Loan Duration(Months): <input type="number" id="range_field_id_1" placeholder="Term(Monthly)">

  Interest Rate:(%) <input id="range_field_id_2" type="number" placeholder="Interest Rate">

<button type="submit" id="calc" onclick="calculation()">Calculate</button>

    Monthly Payment:

    Total Interest:

    Total Payment:


问:
Swift Package with different assets
I have a swift package, I want to use them in two different colour assets (others all same). Now the all files are in /Sources. What I am doing now is swap colour assets with another one. Is it possible to having two libraries, and they are sharing code but different assets. When I add with SPM to chose which library I use.

In my PackageName I have extensions for Color
I tried to create a new target like this

```<code>let package = Package(
    name: "PackageName",
    platforms: [
      .iOS(.v14)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(name: "Library1", targets: ["Library1"]),
        .library(name: "Library2", targets: ["Library2"])
    ],
    targets: [
        .target(name: "PackageName"),
        .target(name: "Library1", dependencies: ["PackageName"] ,resources: [.process("Resources/Library1.xcassets")]),
        .target(name: "Library2", dependencies: ["PackageName"], resources: [.process("Resources/Library2.xcassets")])
    ]
)
</code>```

But I can't use extension Color within PackageName.

I am expecting that when I add the package in SPM, I can choose one from two libraries and I can use those Color extensions I created in PackageName.

Title: Swift Package with different assets

Body:
I have a swift package, I want to use them in two different colour assets (others all same). Now the all files are in /Sources. What I am doing now is swap colour assets with another one. Is it possible to having two libraries, and they are sharing code but different assets. When I add with SPM to chose which library I use.

In my PackageName I have extensions for Color
I tried to create a new target like this

let package = Package(
    name: "PackageName",
    platforms: [
      .iOS(.v14)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(name: "Library1", targets: ["Library1"]),
        .library(name: "Library2", targets: ["Library2"])
    ],
    targets: [
        .target(name: "PackageName"),
        .target(name: "Library1", dependencies: ["PackageName"] ,resources: [.process("Resources/Library1.xcassets")]),
        .target(name: "Library2", dependencies: ["PackageName"], resources: [.process("Resources/Library2.xcassets")])
    ]
)

But I can't use extension Color within PackageName.

I am expecting that when I add the package in SPM, I can choose one from two libraries and I can use those Color extensions I created in PackageName.


问:
unittest runs in terminal but not in pycharm
I have the following project structure and I am working with remote deployment with Pycharm.

```<code>source/
+- src/
   +- __init__.py
   +- abcd.py
+- test/
   +- __init__.py
   +- tests.py
</code>```

In tests.py, I import src.abcd.

Running unittest in terminal with python -m unittest test.tests in the source folder is OK. But when I run the unittest in Pycharm, it says No module named 'src.abcd'.

If I remove the __init__.py in source/test folder, Pycharm is OK but terminal reports error No module named 'test/tests'.

Is there anyway to run unittest with both the commandline and Pycharm?

Body:
I have the following project structure and I am working with remote deployment with Pycharm.

source/
+- src/
   +- __init__.py
   +- abcd.py
+- test/
   +- __init__.py
   +- tests.py

In tests.py, I import src.abcd.

Running unittest in terminal with python -m unittest test.tests in the source folder is OK. But when I run the unittest in Pycharm, it says No module named 'src.abcd'.

If I remove the __init__.py in source/test folder, Pycharm is OK but terminal reports error No module named 'test/tests'.

Is there anyway to run unittest with both the commandline and Pycharm?


问:
clickhouse: Invalid use of collate in window functions

Question

```<code>- clickhouse: Invalid  use of collate in window functions
</code>```

Version

```<code>- 22.8.5.1
</code>```

Recurrence

    create table test_window_collate(c1 String, c2 String) engine=MergeTree order by c1;
    insert into test_window_collate values('1', '上海');
    insert into test_window_collate values('1', '北京');
    insert into test_window_collate values('1', '西安');
```
<pre class="lang-sql prettyprint-override"><code>    select c2, groupArray(c2) over (partition by c1 order by c2  asc collate 'zh_Hans_CN') as res  from test_window_collate order by c2  asc collate 'zh_Hans_CN';
</code>```

Actual result

```<code>| c2       |    res              |
| -------- |--------------       |
|北京      |   [上海，北京]       |
|上海      |   [上海]             |
|西安      |   [上海， 北京， 西安]|
</code>```

Expected result

```<code>| c2       |      res          |
| -------- |--------------     |
|北京      |   [北京]           |
|上海      |   [北京，上海]     |
|西安      |   [北京，上海，西安]|
</code>```

Guess the cause

It's not the expected result because invalid  use of collate in window functions.

Code analysis

```<code>- File ParserSelectQuery.cpp
- Line 164
- Code         `if (!exp_list_for_select_clause.parse(pos, select_expression_list, expected))`
</code>```

The code here does not give s_order_by(Line 262) a chance to get the collate

```<code>- File ExpressionAnalyzer.cpp
- Line 1951
- Code `&& !query_analyzer.hasWindow()`
</code>```

This code causes collator not to be created

How to make window function support collate？

Body:
Question

- clickhouse: Invalid  use of collate in window functions

Version

- 22.8.5.1

Recurrence

    create table test_window_collate(c1 String, c2 String) engine=MergeTree order by c1;
    insert into test_window_collate values('1', '上海');
    insert into test_window_collate values('1', '北京');
    insert into test_window_collate values('1', '西安');

    select c2, groupArray(c2) over (partition by c1 order by c2  asc collate 'zh_Hans_CN') as res  from test_window_collate order by c2  asc collate 'zh_Hans_CN';

Actual result

| c2       |    res              |
| -------- |--------------       |
|北京      |   [上海，北京]       |
|上海      |   [上海]             |
|西安      |   [上海， 北京， 西安]|

Expected result

| c2       |      res          |
| -------- |--------------     |
|北京      |   [北京]           |
|上海      |   [北京，上海]     |
|西安      |   [北京，上海，西安]|

Guess the cause

It's not the expected result because invalid  use of collate in window functions.

Code analysis

- File ParserSelectQuery.cpp
- Line 164
- Code         `if (!exp_list_for_select_clause.parse(pos, select_expression_list, expected))`

The code here does not give s_order_by(Line 262) a chance to get the collate

- File ExpressionAnalyzer.cpp
- Line 1951
- Code `&& !query_analyzer.hasWindow()`

This code causes collator not to be created

How to make window function support collate？


问:
Executing a function in command line after calling "sudo su"
I'm currently working on a program that is constantly checking the utilization of the available CPU cores on a raspberry pi and then calculates what the optimal frequency the CPU should be running on. However, I am running into some issues with executing the function that actually changes the CPU frequency.

My current code snippet is as follows

```<code>system("cd ~; cd /sys/devices/system/cpu/cpufreq/policy0; sudo su;")
</code>```

However, I haven't been able to find a method to get it to then execute the last command

```<code>echo //some_frequency > scaling_setspeed
</code>```

I've tried the following

```<code>int freq = //some number
char buf[BIFSIZ]
snprintf(buf, sizeof(buf), "cd ~; cd /sys/devices/system/cpu/cpufreq/policy0; sudo su; echo %d > scaling_setspeed", freq);
system(buf)
</code>```

as well as using

```<code>system("cd ~; cd /sys/devices/system/cpu/cpufreq/policy0; sudo su;")
cout << "echo " << freq << " > scaling_setspeed" << endl;
</code>```

and

```<code>system("cd ~; cd /sys/devices/system/cpu/cpufreq/policy0; sudo su;")
printf("echo %d > scaling_setspeed");
</code>```

None of these have worked.

I realize this question probably has an obvious solution that I'm just oblivious to, but I am unable to determine how to get this to work, any help would be greatly appreciated.
Thanks

Body:
I'm currently working on a program that is constantly checking the utilization of the available CPU cores on a raspberry pi and then calculates what the optimal frequency the CPU should be running on. However, I am running into some issues with executing the function that actually changes the CPU frequency.

My current code snippet is as follows

system("cd ~; cd /sys/devices/system/cpu/cpufreq/policy0; sudo su;")

However, I haven't been able to find a method to get it to then execute the last command

echo //some_frequency > scaling_setspeed

I've tried the following

int freq = //some number
char buf[BIFSIZ]
snprintf(buf, sizeof(buf), "cd ~; cd /sys/devices/system/cpu/cpufreq/policy0; sudo su; echo %d > scaling_setspeed", freq);
system(buf)

as well as using

system("cd ~; cd /sys/devices/system/cpu/cpufreq/policy0; sudo su;")
cout << "echo " << freq << " > scaling_setspeed" << endl;

and

system("cd ~; cd /sys/devices/system/cpu/cpufreq/policy0; sudo su;")
printf("echo %d > scaling_setspeed");

None of these have worked.

I realize this question probably has an obvious solution that I'm just oblivious to, but I am unable to determine how to get this to work, any help would be greatly appreciated.
Thanks


问:
How can I configure rollup to include fonts from a dependent package
I'm using an open-wc application project (npm init @open-wc) with kor-ui as my components library and trying to build with rollup. After I build the app and start it, I get the following errors:

downloadable font: download failed (font-family: "open-sans" style:normal weight:400 stretch:100 src index:2): status=2147746065 source: http://localhost:8000/fonts/open-sans-regular.woff2

downloadable font: download failed (font-family: "open-sans" style:normal weight:400 stretch:100 src index:3): status=2147746065 source: http://localhost:8000/fonts/open-sans-regular.woff

plus two 404 errors from network requests for those files.

I've traced that down to kor's styles.css, which I link in the page's html and imports those fonts from a relative path locally

```<code>@font-face {
  font-family: 'open-sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans Regular'), local('OpenSans-Regular'), url('./fonts/open-sans-regular.woff2') format('woff2'), url('./fonts/open-sans-regular.woff') format('woff');
}
</code>```

I've scoured the internet for plugins that can solve this problem and am coming up fairly blank, which leads me to believe that either I've encountered a brand new problem (lol this is never the answer), Kor has done something that is incompatible with rollup, or I've done something dumb (I believe this is the correct answer).

So, internet: please tell me what I've done wrong and how I can make this work.

Body:
I'm using an open-wc application project (npm init @open-wc) with kor-ui as my components library and trying to build with rollup. After I build the app and start it, I get the following errors:

downloadable font: download failed (font-family: "open-sans" style:normal weight:400 stretch:100 src index:2): status=2147746065 source: http://localhost:8000/fonts/open-sans-regular.woff2

downloadable font: download failed (font-family: "open-sans" style:normal weight:400 stretch:100 src index:3): status=2147746065 source: http://localhost:8000/fonts/open-sans-regular.woff

plus two 404 errors from network requests for those files.

I've traced that down to kor's styles.css, which I link in the page's html and imports those fonts from a relative path locally

@font-face {
  font-family: 'open-sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans Regular'), local('OpenSans-Regular'), url('./fonts/open-sans-regular.woff2') format('woff2'), url('./fonts/open-sans-regular.woff') format('woff');
}

I've scoured the internet for plugins that can solve this problem and am coming up fairly blank, which leads me to believe that either I've encountered a brand new problem (lol this is never the answer), Kor has done something that is incompatible with rollup, or I've done something dumb (I believe this is the correct answer).

So, internet: please tell me what I've done wrong and how I can make this work.


问:
ShellBrowserWindow creation fails on Windows 11 22H2
In this article:
Developing with Windows Explorer

This code returns S_OK on Windows 11 21H2.

However, on Windows 11 22H2, it returns E_FAIL.

```<code>IWebBrowser2 *pwb;
HRESULT hr = CoCreateInstance(CLSID_ShellBrowserWindow, NULL, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&pwb));
</code>```

Is there a reason for this?

I want to open an explorer window in a specified placement.

Like this:

```<code>IWebBrowser2* pwb;
CoCreateInstance( CLSID_ShellBrowserWindow, ... IID_PPV_ARGS( &pwb ) );
pwb->Navigate2( ... );
pwb->put_Left( ... );
pwb->put_Top( ... );
pwb->put_Visible( VARIANT_TRUE );
</code>```

This code fails on Windows 11 22H2.

Is there any other way to do this?

Body:
In this article:
Developing with Windows Explorer

This code returns S_OK on Windows 11 21H2.

However, on Windows 11 22H2, it returns E_FAIL.

IWebBrowser2 *pwb;
HRESULT hr = CoCreateInstance(CLSID_ShellBrowserWindow, NULL, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&pwb));

Is there a reason for this?

I want to open an explorer window in a specified placement.

Like this:

IWebBrowser2* pwb;
CoCreateInstance( CLSID_ShellBrowserWindow, ... IID_PPV_ARGS( &pwb ) );
pwb->Navigate2( ... );
pwb->put_Left( ... );
pwb->put_Top( ... );
pwb->put_Visible( VARIANT_TRUE );

This code fails on Windows 11 22H2.

Is there any other way to do this?


问:
Python script not saving csv to specified location
I have a python script for a program I'm trying to run that is attempting to save a .csv file to the downloads folder on my computer. The script runs without errors but it's not saving the file to the specified location. Any help would be much appreciated!</p>
```<code>import pandas as pd
import numpy as np

# Define function to analyze student performance, interests, and learning style
def create_customized_lesson_plan(student_id):
  # Read in student data from a csv file
  student_data = pd.read_csv('/Users/jmeszaros/Downloads/student_data.csv')

  # Extract the relevant data for the specified student
  student_row = student_data[student_data["student_id"] == student_id]
  performance_data = student_row["performance"]
  interests_data = student_row["interests"]
  learning_style = student_row["learning_style"]

  # Analyze the data to determine the student's strengths and interests
  strengths = []
  interests = []
  if "math" in interests_data and performance_data["math"] > 80:
    strengths.append("math")
  if "science" in interests_data and performance_data["science"] > 80:
    strengths.append("science")
  if "history" in interests_data:
    interests.append("history")
  if "art" in interests_data:
    interests.append("art")

  # Create a customized lesson plan based on the student's strengths and interests
  lesson_plan = []
  if "math" in strengths:
    lesson_plan.append("Math game: Solve challenging math problems to earn points and unlock new levels")
  if "science" in strengths:
    lesson_plan.append("Science simulation: Explore the solar system and learn about the planets and their characteristics")
  if "history" in interests:
    lesson_plan.append("History quiz: Test your knowledge of historical events and figures")
  if "art" in interests:
    lesson_plan.append("Art project: Create your own masterpiece using different art materials and techniques")

  # Create a dataframe for the lesson plan
  lesson_plan_df = pd.DataFrame({"activity": lesson_plan})

  # Save the lesson plan to a csv file
  lesson_plan_df.to_csv('/Users/jmeszaros/Downloads/lesson_plan_' + student_id + '.csv', index=False)
</code>```

Body:
I have a python script for a program I'm trying to run that is attempting to save a .csv file to the downloads folder on my computer. The script runs without errors but it's not saving the file to the specified location. Any help would be much appreciated!

import pandas as pd
import numpy as np

# Define function to analyze student performance, interests, and learning style
def create_customized_lesson_plan(student_id):
  # Read in student data from a csv file
  student_data = pd.read_csv('/Users/jmeszaros/Downloads/student_data.csv')

  # Extract the relevant data for the specified student
  student_row = student_data[student_data["student_id"] == student_id]
  performance_data = student_row["performance"]
  interests_data = student_row["interests"]
  learning_style = student_row["learning_style"]

  # Analyze the data to determine the student's strengths and interests
  strengths = []
  interests = []
  if "math" in interests_data and performance_data["math"] > 80:
    strengths.append("math")
  if "science" in interests_data and performance_data["science"] > 80:
    strengths.append("science")
  if "history" in interests_data:
    interests.append("history")
  if "art" in interests_data:
    interests.append("art")

  # Create a customized lesson plan based on the student's strengths and interests
  lesson_plan = []
  if "math" in strengths:
    lesson_plan.append("Math game: Solve challenging math problems to earn points and unlock new levels")
  if "science" in strengths:
    lesson_plan.append("Science simulation: Explore the solar system and learn about the planets and their characteristics")
  if "history" in interests:
    lesson_plan.append("History quiz: Test your knowledge of historical events and figures")
  if "art" in interests:
    lesson_plan.append("Art project: Create your own masterpiece using different art materials and techniques")

  # Create a dataframe for the lesson plan
  lesson_plan_df = pd.DataFrame({"activity": lesson_plan})

  # Save the lesson plan to a csv file
  lesson_plan_df.to_csv('/Users/jmeszaros/Downloads/lesson_plan_' + student_id + '.csv', index=False)


问:
How to succinctly print ActiveSupport::Duration based on largest integer part?
Certain Durations are naturally represented in ways that aren't very succinct.

For example:

```<code>d = ActiveSupport::Duration.build(5.weeks)
d.inspect
# Output is "1 month, 4 days, 13 hours, 30 minutes, and 54 seconds"

d = ActiveSupport::Duration.build(90.days)
d.inspect
# Output is "2 months, 4 weeks, 1 day, 3 hours, 1 minute, and 48 seconds"
</code>```

I would like to output these Durations based on the largest integer part, so my examples above would output simply as "5 weeks" and "90 days".

I have written these helper methods:

```<code>def format_duration(duration)
  duration_unit = largest_part_for(duration)
  "#{duration.to_i / 1.send(duration_unit).to_i} #{duration_unit}"
end

def largest_part_for(duration)
  return 'seconds' if duration.in_seconds == 0
  return 'years'   if duration.in_years % 1 == 0
  return 'months'  if duration.in_months % 1 == 0
  return 'weeks'   if duration.in_weeks % 1 == 0
  return 'days'    if duration.in_days % 1 == 0
  return 'hours'   if duration.in_hours % 1 == 0
  return 'minutes' if duration.in_minutes % 1 == 0
  'seconds'
end
</code>```

..but it doesn't seem like good Ruby.

Can anyone suggest how I can do this in a simpler/cleaner way?

Body:
Certain Durations are naturally represented in ways that aren't very succinct.

For example:

d = ActiveSupport::Duration.build(5.weeks)
d.inspect
# Output is "1 month, 4 days, 13 hours, 30 minutes, and 54 seconds"

d = ActiveSupport::Duration.build(90.days)
d.inspect
# Output is "2 months, 4 weeks, 1 day, 3 hours, 1 minute, and 48 seconds"

I would like to output these Durations based on the largest integer part, so my examples above would output simply as "5 weeks" and "90 days".

I have written these helper methods:

def format_duration(duration)
  duration_unit = largest_part_for(duration)
  "#{duration.to_i / 1.send(duration_unit).to_i} #{duration_unit}"
end

def largest_part_for(duration)
  return 'seconds' if duration.in_seconds == 0
  return 'years'   if duration.in_years % 1 == 0
  return 'months'  if duration.in_months % 1 == 0
  return 'weeks'   if duration.in_weeks % 1 == 0
  return 'days'    if duration.in_days % 1 == 0
  return 'hours'   if duration.in_hours % 1 == 0
  return 'minutes' if duration.in_minutes % 1 == 0
  'seconds'
end

..but it doesn't seem like good Ruby.

Can anyone suggest how I can do this in a simpler/cleaner way?


问:
Bootstrap 5 contents of my page are not entirely centered and floating towards the left side
I wanted to align the contents of my page to the center. Everything seems to be floating more towards the left side and I am trying to get everything even for an assignment.
(This is my first time using bootstrap so bear with me if anything doesn't look right.)

Here is the code:

```<code>  <!-- passions -->
    <section class="bg-secondary text-white p-5">
        <h1 class="text-center mb-5 p-5 text-dark">My passions</h1>
        <div class="container">
            <div class="row align-items-center justify-content-between g-5">
                <div class="col-sm-5">
                    <img class="img-fluid d-none d-sm-block rounded" width="400"
                        src="pics/pexels-victor-freitas-841134.jpg" alt="Weights">
                </div>
                <div class="col-sm-5">
                    <h3>Working out</h3>
                    <p>Working out has always been a passion of mine.<br> It helps me focus and also
                        alleviates stress. I also wanted to <br> self improve and work on myself and get in shape.
                    </p>
                </div>
                <div class="col-sm-5">
                    <h3>Coding</h3>
                    <p>Coding is a recent endevour that has been<br>a priority of mine to master.
                        After spending<br>a long time trying to find a passion of mine to turn into a <br>career, I
                        discovered that coding is something that I enjoy really doing. <br>Just listen to what Steve
                        Jobs had to
                        say about coding.</p>
                    <audio controls="controls">
                        <source src="audio/steveJobs-Computer-science.mp3" type="audio/mpeg">
                        <source src="audio/steveJobs-Computer-science.ogg" type="audio/ogg">
                        Your browser does not support the audio element.
                    </audio>
                </div>
                <div class="col-sm-5">
                    <img class="img-fluid d-none d-sm-block rounded" width="400" height="400"
                        src="pics/laptopcode.jpg" alt="Weights">
                </div>
                <div class="col-sm-5"><img class="img-fluid d-none d-sm-block rounded" width="400" height="400"
                        src="pics/puckStick.jpg" alt="Weights"></div>
                <div class="col-sm-5 ">
                    <h3>Sports</h3>
                    <p>Playing sports has always been a passion of mine.<br>As i was growing up, I always
                        loved watching, and also<br>playing hockey. There is just something about putting<br>your
                        skates
                        on and playing hockey
                        with friends and family.</p>
                </div>
            </div>
        </div>
    </section>
</code>```

Body:
I wanted to align the contents of my page to the center. Everything seems to be floating more towards the left side and I am trying to get everything even for an assignment.
(This is my first time using bootstrap so bear with me if anything doesn't look right.)

Here is the code:

My passions

Working out

Working out has always been a passion of mine.
 It helps me focus and also
                        alleviates stress. I also wanted to
 self improve and work on myself and get in shape.

Coding

Coding is a recent endevour that has been
a priority of mine to master.
                        After spending
a long time trying to find a passion of mine to turn into a
career, I
                        discovered that coding is something that I enjoy really doing.
Just listen to what Steve
                        Jobs had to
                        say about coding.

                    <audio controls="controls">
                        <source src="audio/steveJobs-Computer-science.mp3" type="audio/mpeg">
                        <source src="audio/steveJobs-Computer-science.ogg" type="audio/ogg">
                        Your browser does not support the audio element.
                    </audio>

Sports

Playing sports has always been a passion of mine.
As i was growing up, I always
                        loved watching, and also
playing hockey. There is just something about putting
your
                        skates
                        on and playing hockey
                        with friends and family.


问:
gcc-12 error when installing R packages (e.g. DESeq2)
The problem arose when I tried installing DESeq2.

Running: BiocManager::install("DESeq2") produced

```<code>Installing package(s) 'DESeq2'
also installing the dependencies 'sys', 'fastmap', 'askpass',
</code>```

Download was fine, then this error occured for every single package and dependency:

```<code>* installing *source* package 'sys' ...
** package 'sys' successfully unpacked and MD5 sums checked
** using staged installation
** libs
gcc-12 -I"/home/linuxbrew/.linuxbrew/Cellar/r/4.2.2/lib/R/include" -DNDEBUG   -I/home/linuxbrew/.linuxbrew/opt/libtirpc/include/tirpc -I/home/linuxbrew/.linuxbrew/opt/gettext/include -I/home/linuxbrew/.linuxbrew/opt/readline/include -I/home/linuxbrew/.linuxbrew/opt/xz/include -I/home/linuxbrew/.linuxbrew/include   -fpic  -Wno-implicit-function-declaration  -c exec.c -o exec.o
/bin/bash: /home/linuxbrew/.linuxbrew/bin/gcc-12: Bad address
make: *** [/home/linuxbrew/.linuxbrew/Cellar/r/4.2.2/lib/R/etc/Makeconf:169: exec.o] Error 126
ERROR: compilation failed for package 'sys'
* removing '/home/linuxbrew/.linuxbrew/lib/R/4.2/site-library/sys'
</code>```

So the error seems to be with the GCC-12, because of this line:

```<code>/bin/bash: /home/linuxbrew/.linuxbrew/bin/gcc-12: Bad address
</code>```

Running gcc --version produces:

```<code>gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

Running gcc-12 --version produces:

```<code>-bash: /home/linuxbrew/.linuxbrew/bin/gcc-12: Bad address
</code>```

It seems to be a recent problem following homebrew upgrade but I am running the latest WSL Kernel version (Kernel version: 5.10.102.1).

Lastly, running brew postinstall gcc produces:

```<code>==> Postinstalling gcc
Warning: The post-install step did not complete successfully
You can try again using:
  brew postinstall gcc
</code>```

I ran sudo apt-get install build-essential and got

```<code>build-essential is already the newest version (12.8ubuntu1.1).
</code>```

Running brew reinstall gcc produces:

```<code>==> Downloading https://ghcr.io/v2/homebrew/core/gcc/manifests/12.2.0-2
Already downloaded: /home/osekulovic/.cache/Homebrew/downloads/a4a4a48db6f1c5ebc47c0929825c735a0c4837922713f6773cb4fbec928e5a8f--gcc-12.2.0-2.bottle_manifest.json
==> Downloading https://ghcr.io/v2/homebrew/core/gcc/blobs/sha256:d2080ede63b45e711bbb05c474af6affe3edc255fecf81009a85e23429b509e2
Already downloaded: /home/osekulovic/.cache/Homebrew/downloads/ab6926110713961da39411864073329dbfc562bde4cdad0f4f3f17fe1b4640cd--gcc--12.2.0.x86_64_linux.bottle.2.tar.gz
==> Reinstalling gcc
==> Pouring gcc--12.2.0.x86_64_linux.bottle.2.tar.gz
Warning: The post-install step did not complete successfully
You can try again using:
  brew postinstall gcc
==> Summary
  /home/linuxbrew/.linuxbrew/Cellar/gcc/12.2.0: 1,623 files, 306.6MB
==> Running `brew cleanup gcc`...
Disable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.
Hide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).
</code>```

Help highly appreaciated!

TP

Body:
The problem arose when I tried installing DESeq2.

Running: BiocManager::install("DESeq2") produced

Installing package(s) 'DESeq2'
also installing the dependencies 'sys', 'fastmap', 'askpass',

Download was fine, then this error occured for every single package and dependency:

* installing *source* package 'sys' ...
** package 'sys' successfully unpacked and MD5 sums checked
** using staged installation
** libs
gcc-12 -I"/home/linuxbrew/.linuxbrew/Cellar/r/4.2.2/lib/R/include" -DNDEBUG   -I/home/linuxbrew/.linuxbrew/opt/libtirpc/include/tirpc -I/home/linuxbrew/.linuxbrew/opt/gettext/include -I/home/linuxbrew/.linuxbrew/opt/readline/include -I/home/linuxbrew/.linuxbrew/opt/xz/include -I/home/linuxbrew/.linuxbrew/include   -fpic  -Wno-implicit-function-declaration  -c exec.c -o exec.o
/bin/bash: /home/linuxbrew/.linuxbrew/bin/gcc-12: Bad address
make: *** [/home/linuxbrew/.linuxbrew/Cellar/r/4.2.2/lib/R/etc/Makeconf:169: exec.o] Error 126
ERROR: compilation failed for package 'sys'
* removing '/home/linuxbrew/.linuxbrew/lib/R/4.2/site-library/sys'

So the error seems to be with the GCC-12, because of this line:

/bin/bash: /home/linuxbrew/.linuxbrew/bin/gcc-12: Bad address

Running gcc --version produces:

gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Running gcc-12 --version produces:

-bash: /home/linuxbrew/.linuxbrew/bin/gcc-12: Bad address

It seems to be a recent problem following homebrew upgrade but I am running the latest WSL Kernel version (Kernel version: 5.10.102.1).

Lastly, running brew postinstall gcc produces:

==> Postinstalling gcc
Warning: The post-install step did not complete successfully
You can try again using:
  brew postinstall gcc

I ran sudo apt-get install build-essential and got

build-essential is already the newest version (12.8ubuntu1.1).

Running brew reinstall gcc produces:

==> Downloading https://ghcr.io/v2/homebrew/core/gcc/manifests/12.2.0-2
Already downloaded: /home/osekulovic/.cache/Homebrew/downloads/a4a4a48db6f1c5ebc47c0929825c735a0c4837922713f6773cb4fbec928e5a8f--gcc-12.2.0-2.bottle_manifest.json
==> Downloading https://ghcr.io/v2/homebrew/core/gcc/blobs/sha256:d2080ede63b45e711bbb05c474af6affe3edc255fecf81009a85e23429b509e2
Already downloaded: /home/osekulovic/.cache/Homebrew/downloads/ab6926110713961da39411864073329dbfc562bde4cdad0f4f3f17fe1b4640cd--gcc--12.2.0.x86_64_linux.bottle.2.tar.gz
==> Reinstalling gcc
==> Pouring gcc--12.2.0.x86_64_linux.bottle.2.tar.gz
Warning: The post-install step did not complete successfully
You can try again using:
  brew postinstall gcc
==> Summary
  /home/linuxbrew/.linuxbrew/Cellar/gcc/12.2.0: 1,623 files, 306.6MB
==> Running `brew cleanup gcc`...
Disable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.
Hide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).

Help highly appreaciated!

TP


问:
getting data from graphql data modelling table aws
I want to retrieve data from my API Graph table, not DataStore. I have a Trainers table that has Gender fields, but the type is in a list. How can I retrieve that list and populate my dropdown field? I want to retrieve it that way because then I would only need to change the gender values from the Amplify Studio rather than changing it again in the code. Here is my data modelling table for Trainers and GenderList.

This is currently how I populate my dropdownvalue.

```<code>  List<String> gender = ['Male', 'Female', 'Prefer Not To Say'];
  String dropdownvalue = 'Female';

  void getDropDownItem() {
    setState(() {
      holder = dropdownvalue;
    });
  }

SizedBox(
                  child: DropdownButtonFormField(
                    hint: const Text('Please select...'),
                    value: dropdownvalue,
                    decoration: const InputDecoration(
                      prefixIcon: Icon(Icons.person),
                      prefixIconColor: Colors.grey,
                      filled: true,
                      fillColor: Colors.white,
                      contentPadding: EdgeInsets.all(15),
                      border: OutlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey)),
                    ),
                    icon: Icon(Icons.arrow_drop_down),
                    iconSize: 24,
                    elevation: 16,
                    onChanged: (data) {
                      setState(() {
                        dropdownvalue = data!;
                      });
                    },
                    items: gender.map<DropdownMenuItem>((value) {
                      return DropdownMenuItem(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                  ),
                ),
</code>```

Body:
I want to retrieve data from my API Graph table, not DataStore. I have a Trainers table that has Gender fields, but the type is in a list. How can I retrieve that list and populate my dropdown field? I want to retrieve it that way because then I would only need to change the gender values from the Amplify Studio rather than changing it again in the code. Here is my data modelling table for Trainers and GenderList.

This is currently how I populate my dropdownvalue.

  List<String> gender = ['Male', 'Female', 'Prefer Not To Say'];
  String dropdownvalue = 'Female';

  void getDropDownItem() {
    setState(() {
      holder = dropdownvalue;
    });
  }

SizedBox(
                  child: DropdownButtonFormField(
                    hint: const Text('Please select...'),
                    value: dropdownvalue,
                    decoration: const InputDecoration(
                      prefixIcon: Icon(Icons.person),
                      prefixIconColor: Colors.grey,
                      filled: true,
                      fillColor: Colors.white,
                      contentPadding: EdgeInsets.all(15),
                      border: OutlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey)),
                    ),
                    icon: Icon(Icons.arrow_drop_down),
                    iconSize: 24,
                    elevation: 16,
                    onChanged: (data) {
                      setState(() {
                        dropdownvalue = data!;
                      });
                    },
                    items: gender.map<DropdownMenuItem>((value) {
                      return DropdownMenuItem(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                  ),
                ),


问:
How should I structure my code if I am using Moshi to parse form a local JSON file in Kotlin for Android?
So I have a local json that is basically a survey object that contains a survey and some details/attributes(List, Header, Footer, ids etc) relating to the survey. I created a Data Class model using Moshi code gen adapters and it works but I want to know what is the best way to achieve this. Currently this is my thought process. I'm a bit confused on what should be in my DI Module vs what should my repository look like, do I need a DI concrete class, interface etc?

Here is where I am currently at

Hilt Module:

```<code>@Provides
@Singleton
fun provideModelAdapter(@ApplicationContext context: Context) : JsonAdapter<Model> {

    val moshi: Moshi = Moshi.Builder().build()
    return moshi.adapter(Model::class.java)
}
</code>```

Then would my repository use a DAO interface? If so what would that look like or would it get the json model from in the repo?

Repository:

```<code>class Repository @Inject constructor(
    @ApplicationContext private val context: Context,
    private val adapter: JsonAdapter<ChltSurveyModel>
) {

suspend fun getModel() {
    val json: String = context.readFromAssets(MODEL_FILENAME)
    adapter.fromJson()
     }
}
</code>```

ViewModel:

```<code>@HiltViewModel
class ViewModel @lInject constructor(
    private val repository: Repository
) : ViewModel() {

private val _model = MutableLiveData<Model>()
val model: LiveData<Model> = _model

init {
    getModel()
}

fun getModel() = viewModelScope.launch {
    try {
        _model.value = repository.getModel()
    } catch (e: JsonDataException) {
        e.printStackTrace()
    }
  }
}
</code>```

Util Class to Read JSON

```<code>fun Context.readFromAssets(filename: String): String = try {
    val reader = BufferedReader(InputStreamReader(assets.open(filename)))
    val sb = StringBuilder()
    var line = reader.readLine()
    while (line != null) {
        sb.append(line)
        line = reader.readLine()
    }
    reader.close()
    sb.toString()
} catch (exp: Exception) {
    println("Failed reading line from $filename -> ${exp.localizedMessage}")
    ""
}
</code>```

Body:
So I have a local json that is basically a survey object that contains a survey and some details/attributes(List, Header, Footer, ids etc) relating to the survey. I created a Data Class model using Moshi code gen adapters and it works but I want to know what is the best way to achieve this. Currently this is my thought process. I'm a bit confused on what should be in my DI Module vs what should my repository look like, do I need a DI concrete class, interface etc?

Here is where I am currently at

Hilt Module:

@Provides
@Singleton
fun provideModelAdapter(@ApplicationContext context: Context) : JsonAdapter<Model> {

    val moshi: Moshi = Moshi.Builder().build()
    return moshi.adapter(Model::class.java)
}

Then would my repository use a DAO interface? If so what would that look like or would it get the json model from in the repo?

Repository:

class Repository @Inject constructor(
    @ApplicationContext private val context: Context,
    private val adapter: JsonAdapter<ChltSurveyModel>
) {

suspend fun getModel() {
    val json: String = context.readFromAssets(MODEL_FILENAME)
    adapter.fromJson()
     }
}

ViewModel:

@HiltViewModel
class ViewModel @lInject constructor(
    private val repository: Repository
) : ViewModel() {

private val _model = MutableLiveData<Model>()
val model: LiveData<Model> = _model

init {
    getModel()
}

fun getModel() = viewModelScope.launch {
    try {
        _model.value = repository.getModel()
    } catch (e: JsonDataException) {
        e.printStackTrace()
    }
  }
}

Util Class to Read JSON

fun Context.readFromAssets(filename: String): String = try {
    val reader = BufferedReader(InputStreamReader(assets.open(filename)))
    val sb = StringBuilder()
    var line = reader.readLine()
    while (line != null) {
        sb.append(line)
        line = reader.readLine()
    }
    reader.close()
    sb.toString()
} catch (exp: Exception) {
    println("Failed reading line from $filename -> ${exp.localizedMessage}")
    ""
}


问:
How can I get the lines that were covered by a particular test method?
I was trying to get all the lines that a test case covered. For instance,

```<code>org.apache.commons.lang.text.StrBuilderAppendInsertTest.testAppendFixedWidthPadLeft(org.apache.commons.lang.text.StrBuilderAppendInsertTest)
org.apache.commons.lang.text.StrBuilder:appendFixedWidthPadLeft:1188
org.apache.commons.lang.text.StrBuilder:appendFixedWidthPadLeft:1191
org.apache.commons.lang.text.StrBuilder:appendFixedWidthPadLeft:1194
org.apache.commons.lang.text.StrBuilder:appendFixedWidthPadLeft:1185
org.apache.commons.lang.text.StrBuilder:clear:288
org.apache.commons.lang.text.StrBuilder:clear:287
org.apache.commons.lang.text.StrBuilder:<init>:111
org.apache.commons.lang.text.StrBuilder:<init>:112
org.apache.commons.lang.text.StrBuilder:setNullText:171
org.apache.commons.lang.text.StrBuilder:setNullText:172
org.apache.commons.lang.text.StrBuilderAppendInsertTest:<init>:56
org.apache.commons.lang.text.StrBuilderAppendInsertTest:<init>:55
</code>```

here testAppendFixedWidthPadLeft covered the lines of StrBuilder class's appendFixedWidthPadLeft method's lines 1188, 1191, 1194, and so on. So I am trying to get this information in a text file. Can anyone suggest me something? I tried Cobertura and Jacoco. But couldn't get anything like that. Thanks.

I tried Cobertura, Jacoco, Gzoltar.

Body:
I was trying to get all the lines that a test case covered. For instance,

org.apache.commons.lang.text.StrBuilderAppendInsertTest.testAppendFixedWidthPadLeft(org.apache.commons.lang.text.StrBuilderAppendInsertTest)
org.apache.commons.lang.text.StrBuilder:appendFixedWidthPadLeft:1188
org.apache.commons.lang.text.StrBuilder:appendFixedWidthPadLeft:1191
org.apache.commons.lang.text.StrBuilder:appendFixedWidthPadLeft:1194
org.apache.commons.lang.text.StrBuilder:appendFixedWidthPadLeft:1185
org.apache.commons.lang.text.StrBuilder:clear:288
org.apache.commons.lang.text.StrBuilder:clear:287
org.apache.commons.lang.text.StrBuilder:<init>:111
org.apache.commons.lang.text.StrBuilder:<init>:112
org.apache.commons.lang.text.StrBuilder:setNullText:171
org.apache.commons.lang.text.StrBuilder:setNullText:172
org.apache.commons.lang.text.StrBuilderAppendInsertTest:<init>:56
org.apache.commons.lang.text.StrBuilderAppendInsertTest:<init>:55

here testAppendFixedWidthPadLeft covered the lines of StrBuilder class's appendFixedWidthPadLeft method's lines 1188, 1191, 1194, and so on. So I am trying to get this information in a text file. Can anyone suggest me something? I tried Cobertura and Jacoco. But couldn't get anything like that. Thanks.

I tried Cobertura, Jacoco, Gzoltar.


问:
Mysql2::Error: Incorrect table name '' - when using AppMap Gem
I recently found out about the AppMap utility and I'm trying to incorporate it into my Rails app via IntelliJ. However, after installing the gem and configuring it, any request I make results throws the following exception:

```<code>ActiveRecord::StatementInvalid in UsersController#index

Mysql2::Error: Incorrect table name ''
</code>```

It does this for every page, model, request, etc. when using a browser. From my stack trace, it looks like the issue is arising when the roles are being checked in my Ability.rb file (I'm using Devise, CanCanCan, and Rolify for authentication).

If I try to do user.roles in the rails console it produces this:

```<code>irb(main):007:0> u.roles
  Role Load (0.5ms)  SELECT `roles`.* FROM `roles` INNER JOIN `` ON `roles`.`id` = ``.`role_id` WHERE ``.`user_id` = 1
(Object doesn't support #inspect)
</code>```

If I remove the AppMap gem then everything in my application works as intended like it has been previously.

I'm not really sure where to go from here so any input would be greatly appreciated!

Versions:

IntelliJ IDEA: 2022.1.4 (Ultimate)

AppMap Plugin: 0.21.0

AppMap Gem: 0.94.1

Rails: 6.1.4.7

Ruby: 3.0.1

MySql2: 0.5.4

CanCaCan: 3.2.2

Devise: 4.8.1

Rolify: 6.0.0

Body:
I recently found out about the AppMap utility and I'm trying to incorporate it into my Rails app via IntelliJ. However, after installing the gem and configuring it, any request I make results throws the following exception:

ActiveRecord::StatementInvalid in UsersController#index

Mysql2::Error: Incorrect table name ''

It does this for every page, model, request, etc. when using a browser. From my stack trace, it looks like the issue is arising when the roles are being checked in my Ability.rb file (I'm using Devise, CanCanCan, and Rolify for authentication).

If I try to do user.roles in the rails console it produces this:

irb(main):007:0> u.roles
  Role Load (0.5ms)  SELECT `roles`.* FROM `roles` INNER JOIN `` ON `roles`.`id` = ``.`role_id` WHERE ``.`user_id` = 1
(Object doesn't support #inspect)

If I remove the AppMap gem then everything in my application works as intended like it has been previously.

I'm not really sure where to go from here so any input would be greatly appreciated!

Versions:

IntelliJ IDEA: 2022.1.4 (Ultimate)

AppMap Plugin: 0.21.0

AppMap Gem: 0.94.1

Rails: 6.1.4.7

Ruby: 3.0.1

MySql2: 0.5.4

CanCaCan: 3.2.2

Devise: 4.8.1

Rolify: 6.0.0


问:
How to access object data using variable value as element in vue js
How i can access the object data using variable value as key?

Let say i have this object:

```<code>let item = {
    name: {
        first_name: "Mark",
        last_name: "James"
    }
}

</code>```

How i can get the value of first name using variable value?

I know i can access it using

item.name.first_name

What if i want to access it using variable value like this:

```<code>let key = "name.first_name"

console.log(item[key])
</code>```

Body:
How i can access the object data using variable value as key?

Let say i have this object:

let item = {
    name: {
        first_name: "Mark",
        last_name: "James"
    }
}

How i can get the value of first name using variable value?

I know i can access it using

item.name.first_name

What if i want to access it using variable value like this:

let key = "name.first_name"

console.log(item[key])


问:
How do i efficiently retrieve a variable and use in this formula
I am trying to calculate distance between areas by using the answer in this answer  but I am not an expert on sql.

The formular is as such

```<code>    SELECT * , (3956 * 2 * ASIN(SQRT( POWER(SIN(( $lat - LatOnTable) *  pi()/180 / 2), 2) +COS( $lat * pi()/180) * COS(LatOnTable * pi()/180) * POWER(SIN(( $long - LongOnTable) * pi()/180 / 2), 2) ))) as distance
from yourTable
having  distance <= 10
order by distance
</code>```

But i am unsure how to get the variables $lat and $long in the formula. My table is layed out below you can see the lat and long highlighted in the table below. How do i retrieve these values and use them in the formula

enter image description here

How do I retrieve these values in my table and use them in the formula?

Body:
I am trying to calculate distance between areas by using the answer in this answer  but I am not an expert on sql.

The formular is as such

    SELECT * , (3956 * 2 * ASIN(SQRT( POWER(SIN(( $lat - LatOnTable) *  pi()/180 / 2), 2) +COS( $lat * pi()/180) * COS(LatOnTable * pi()/180) * POWER(SIN(( $long - LongOnTable) * pi()/180 / 2), 2) ))) as distance
from yourTable
having  distance <= 10
order by distance

But i am unsure how to get the variables $lat and $long in the formula. My table is layed out below you can see the lat and long highlighted in the table below. How do i retrieve these values and use them in the formula

enter image description here

How do I retrieve these values in my table and use them in the formula?


问:
Can I use CSS to override or change the keyboard for a TextArea in HTML?
I'm working on an HTML-based Hebrew typing tutorial.  The person using it shouldn't need a Hebrew keyboard installed.  In the sample code below, I show in Hebrew the word "Shalom" which is typed with the letters "akuo" (for SHIN, LAMED, VAV, MEM-SOFIT).

My little test program works when I use a Hebrew keyboard.  Is there some CSS option that can allow it work with an English keyboard? Or do I just need to write the code for that?  For example, user types in "a" and I'd like to see the letter "SHIN" in my textarea.

Based on this, I thought maybe it would be possible:
https://www.quackit.com/css/css3/properties/css_font-language-override.cfm
and
https://www.w3.org/TR/css-fonts-3/#font-language-override-prop

```<code><!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Demo</title>
    <style>
        #WhatToType {
          font-size: xxx-large;
          text-align: right;
          direction: rtl;
          content:"\a";
          white-space: pre;
        }

        #WhatYouTyped {
          font-size: xxx-large;
          text-align: right;
          direction: rtl;
          content:"\a";
          white-space: pre;
        }

        div {
          background-color: lightblue;
        }

        p {
          background-color: yellow;
        }
    </style>

    <script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            console.log("Starting my code")

            $('#WhatYouTyped').keypress(function(e){
                console.log('keypress', String.fromCharCode( e.which ));
            });

})

    </script>
</head>

<body>

<h2>Type What is Shown Here:</h2>

 <div id="WhatToType" bgColor="blue">
     שלום
</div>

<h2>This is where you type</h2>

    <textarea id="WhatYouTyped" name="WhatYouTyped" rows="5" cols="30"></textarea>

</body>

</html>
</code>```

Body:
I'm working on an HTML-based Hebrew typing tutorial.  The person using it shouldn't need a Hebrew keyboard installed.  In the sample code below, I show in Hebrew the word "Shalom" which is typed with the letters "akuo" (for SHIN, LAMED, VAV, MEM-SOFIT).

My little test program works when I use a Hebrew keyboard.  Is there some CSS option that can allow it work with an English keyboard? Or do I just need to write the code for that?  For example, user types in "a" and I'd like to see the letter "SHIN" in my textarea.

Based on this, I thought maybe it would be possible:
https://www.quackit.com/css/css3/properties/css_font-language-override.cfm
and
https://www.w3.org/TR/css-fonts-3/#font-language-override-prop

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Demo</title>

Type What is Shown Here:

     שלום

This is where you type

    <textarea id="WhatYouTyped" name="WhatYouTyped" rows="5" cols="30"></textarea>


问:
how can I predict only 5 days price in this LSTM model (by pytorch)
```<code>class StockDataset(Dataset):
    #데이터 셋은 i번째 레코드 값을 주는 역할 수행
    def __init__(self, symbol, x_frames, y_frames, start, end):

        self.symbol = symbol
        self.x_frames = x_frames
        self.y_frames = y_frames

        self.start = datetime.datetime(*start)
        self.end = datetime.datetime(*end)
        #위에서 지정했던 데이터, 날짜 값들 다 받아옴

        self.data = pdr.DataReader(self.symbol, 'yahoo', self.start, self.end)

    def __len__(self):
            return len(self.data) - (self.x_frames + self.y_frames) + 1

    def __getitem__(self, idx):
        global data
        #global data_set
        #데이터셋 i번째 값 입력받았을때 그걸 출력해줌  데이터를 '리스트'화 하는 것
        idx += self.x_frames
        data = self.data.iloc[idx-self.x_frames:idx+self.y_frames]
        data = data[['High', 'Low', 'Open', 'Close', 'Adj Close', 'Volume']]
        data = data.apply(lambda x: np.log(x+1) - np.log(x[self.x_frames-1]+1)) #로그수익률 변환 한뒤, 혹시모를 결측값 위해 1더해줌

        global x_ex
        global y_ex
        x_ex= data[:self.x_frames]
        y_ex= data[self.x_frames:]
        data = data.values #numpy array로 변환한거
        X = data[:self.x_frames]
        y = data[self.x_frames:]

        return X, y
</code>```

This one is dataset

```<code>class LSTM(nn.Module):
    #50분 이후부터 모델설명
    def __init__(self, input_dim, hidden_dim, output_dim, num_layers, batch_size, dropout, use_bn):

        super(LSTM, self).__init__()
        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.output_dim = output_dim
        self.num_layers = num_layers

        self.batch_size = batch_size
        self.dropout = dropout
        self.use_bn = use_bn

        self.lstm = nn.LSTM(self.input_dim, self.hidden_dim, self.num_layers)
        self.hidden = self.init_hidden()
        self.regressor = self.make_regressor()

    def init_hidden(self):
        return (torch.zeros(self.num_layers, self.batch_size, self.hidden_dim),
                torch.zeros(self.num_layers, self.batch_size, self.hidden_dim))

    def make_regressor(self):
        layers = []
        if self.use_bn:
            layers.append(nn.BatchNorm1d(self.hidden_dim))

        layers.append(nn.Dropout(self.dropout))
        layers.append(nn.Linear(self.hidden_dim, self.hidden_dim // 2))
        layers.append(nn.ReLU())
        layers.append(nn.Linear(self.hidden_dim // 2, self.output_dim))
        regressor = nn.Sequential(*layers)

        return regressor

    def forward(self, x):
        lstm_out, self.hidden = self.lstm(x, self.hidden)

        y_pred = self.regressor(lstm_out[-1].view(self.batch_size, -1))
        return y_pred
</code>```

This one is model

```<code>def test(model, partition, args):
    global y_true
    global y_pred
    global X
    testloader = DataLoader(partition['test'],
                           batch_size=args.batch_size,
                           shuffle=False, drop_last=True)
    model.eval()

    test_acc = 0.0
    with torch.no_grad():
        for i, (X, y) in enumerate(testloader):

            X = X.transpose(0, 1).float().to(args.device)
            y_true = y[:, :, 3].float().to(args.device)
            model.hidden = [hidden.to(args.device) for hidden in model.init_hidden()]

            y_pred = model(X)
            test_acc += metric(y_pred, y_true)[0]

    test_acc = test_acc /  len(testloader)
    return test_acc

</code>```

This is test data loader.

```<code># ====== Random Seed Initialization ====== #
seed = 666
np.random.seed(seed)
torch.manual_seed(seed)

parser = argparse.ArgumentParser()
args = parser.parse_args("")
args.exp_name = "exp1_lr"
args.device = 'cuda' if torch.cuda.is_available() else 'cpu'

# ====== Data Loading ====== #
args.symbol = '005930.KS' #원하는 종목
args.batch_size = 4 #배치사이즈
args.x_frames = 5 #수정x 이전 n일치 데이터 이게 너무 길면 1주일 예측 불가능
args.y_frames = 5 #수정y 이후 n일치 데이터 이게 너무 길면 1주일 예측 불가능

# ====== Model Capacity ===== #
args.input_dim = 6
args.hid_dim = 50
args.n_layers = 2 # (은닉층의 레이어 갯수) https://justkode.kr/deep-learning/pytorch-rnn링크 참고

# ====== Regularization ======= #
args.l2 = 0.0001
args.dropout = 0.3
args.use_bn = True

# ====== Optimizer & Training ====== #
args.optim = 'RMSprop' #'RMSprop' #SGD, RMSprop, ADAM...
args.lr = 0.001
args.epoch = 1

# ====== Experiment Variable ====== #
name_var1 = 'lr' # lr=러닝레이트
name_var2 = 'n_layers'#뉴럴 네트워크 몇개를 쌓을것인지?
list_var1 = [0.001, 0.0001, 0.00001]
list_var2 = [1,2,3]

#데이터셋 실제 형성
trainset = StockDataset(args.symbol, args.x_frames, args.y_frames, (2012,1,1), (2021,1,1)) #학습기간
valset = StockDataset(args.symbol, args.x_frames, args.y_frames, (2021,1,2), (2021,12,30)) #검증기간 최소 +6 월, +19 일 안하면 float division by zero 에러 발생 왜?? 21년 기준
testset = StockDataset(args.symbol, args.x_frames, args.y_frames, (2022,1,10), (2022,1,14)) #테스트기간 최소 +6 월, + 25일 안하면 float division by zero 에러 발생. 22년기준
#기간이 일정 영업일 이상을 요구하는듯?  <<146 영업일 이상 데이터 요구. 그만큼 안주면 오류남 왜??

partition = {'train': trainset, 'val':valset, 'test':testset}

for var1 in list_var1:
    for var2 in list_var2:
        setattr(args, name_var1, var1)
        setattr(args, name_var2, var2)
        print(args)

        setting, result = experiment(partition, deepcopy(args))
        save_exp_result(setting, result)

    #꼭 디렉토리에 있는 파일들 지운다음에 그래프 그려야한다. 안그러면 결과값 전부 겹쳐서 나옴
</code>```

This one is hyper parameter regulate.

I wonder how can I get result when I set testset length in 5days?  (like (2022,1,10)  (2022,1,14))

This cord didn't work when I set testset length at least 7month (maybe + 146 trade day)

error is float divided by zero. (when I use  lower 146 days.)

if I set length +146 days, then codes work well.

I think this code cause error:

```<code>data = data.apply(lambda x: np.log(x+1) - np.log(x[self.x_frames-1]+1))
</code>```

log data was so small, so error occurred. (my opinion)

data is yahoo finance data. Thanx to read

When I # below code, then data got infinite.

```<code>data = data.apply(lambda x: np.log(x+1) - np.log(x[self.x_frames-1]+1))
</code>```

Body:
class StockDataset(Dataset):
    #데이터 셋은 i번째 레코드 값을 주는 역할 수행
    def __init__(self, symbol, x_frames, y_frames, start, end):

        self.symbol = symbol
        self.x_frames = x_frames
        self.y_frames = y_frames

        self.start = datetime.datetime(*start)
        self.end = datetime.datetime(*end)
        #위에서 지정했던 데이터, 날짜 값들 다 받아옴

        self.data = pdr.DataReader(self.symbol, 'yahoo', self.start, self.end)

    def __len__(self):
            return len(self.data) - (self.x_frames + self.y_frames) + 1

    def __getitem__(self, idx):
        global data
        #global data_set
        #데이터셋 i번째 값 입력받았을때 그걸 출력해줌  데이터를 '리스트'화 하는 것
        idx += self.x_frames
        data = self.data.iloc[idx-self.x_frames:idx+self.y_frames]
        data = data[['High', 'Low', 'Open', 'Close', 'Adj Close', 'Volume']]
        data = data.apply(lambda x: np.log(x+1) - np.log(x[self.x_frames-1]+1)) #로그수익률 변환 한뒤, 혹시모를 결측값 위해 1더해줌

        global x_ex
        global y_ex
        x_ex= data[:self.x_frames]
        y_ex= data[self.x_frames:]
        data = data.values #numpy array로 변환한거
        X = data[:self.x_frames]
        y = data[self.x_frames:]

        return X, y

This one is dataset

class LSTM(nn.Module):
    #50분 이후부터 모델설명
    def __init__(self, input_dim, hidden_dim, output_dim, num_layers, batch_size, dropout, use_bn):

        super(LSTM, self).__init__()
        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.output_dim = output_dim
        self.num_layers = num_layers

        self.batch_size = batch_size
        self.dropout = dropout
        self.use_bn = use_bn

        self.lstm = nn.LSTM(self.input_dim, self.hidden_dim, self.num_layers)
        self.hidden = self.init_hidden()
        self.regressor = self.make_regressor()

    def init_hidden(self):
        return (torch.zeros(self.num_layers, self.batch_size, self.hidden_dim),
                torch.zeros(self.num_layers, self.batch_size, self.hidden_dim))

    def make_regressor(self):
        layers = []
        if self.use_bn:
            layers.append(nn.BatchNorm1d(self.hidden_dim))

        layers.append(nn.Dropout(self.dropout))
        layers.append(nn.Linear(self.hidden_dim, self.hidden_dim // 2))
        layers.append(nn.ReLU())
        layers.append(nn.Linear(self.hidden_dim // 2, self.output_dim))
        regressor = nn.Sequential(*layers)

        return regressor

    def forward(self, x):
        lstm_out, self.hidden = self.lstm(x, self.hidden)

        y_pred = self.regressor(lstm_out[-1].view(self.batch_size, -1))
        return y_pred

This one is model

def test(model, partition, args):
    global y_true
    global y_pred
    global X
    testloader = DataLoader(partition['test'],
                           batch_size=args.batch_size,
                           shuffle=False, drop_last=True)
    model.eval()

    test_acc = 0.0
    with torch.no_grad():
        for i, (X, y) in enumerate(testloader):

            X = X.transpose(0, 1).float().to(args.device)
            y_true = y[:, :, 3].float().to(args.device)
            model.hidden = [hidden.to(args.device) for hidden in model.init_hidden()]

            y_pred = model(X)
            test_acc += metric(y_pred, y_true)[0]

    test_acc = test_acc /  len(testloader)
    return test_acc

This is test data loader.

# ====== Random Seed Initialization ====== #
seed = 666
np.random.seed(seed)
torch.manual_seed(seed)

parser = argparse.ArgumentParser()
args = parser.parse_args("")
args.exp_name = "exp1_lr"
args.device = 'cuda' if torch.cuda.is_available() else 'cpu'

# ====== Data Loading ====== #
args.symbol = '005930.KS' #원하는 종목
args.batch_size = 4 #배치사이즈
args.x_frames = 5 #수정x 이전 n일치 데이터 이게 너무 길면 1주일 예측 불가능
args.y_frames = 5 #수정y 이후 n일치 데이터 이게 너무 길면 1주일 예측 불가능

# ====== Model Capacity ===== #
args.input_dim = 6
args.hid_dim = 50
args.n_layers = 2 # (은닉층의 레이어 갯수) https://justkode.kr/deep-learning/pytorch-rnn링크 참고

# ====== Regularization ======= #
args.l2 = 0.0001
args.dropout = 0.3
args.use_bn = True

# ====== Optimizer & Training ====== #
args.optim = 'RMSprop' #'RMSprop' #SGD, RMSprop, ADAM...
args.lr = 0.001
args.epoch = 1

# ====== Experiment Variable ====== #
name_var1 = 'lr' # lr=러닝레이트
name_var2 = 'n_layers'#뉴럴 네트워크 몇개를 쌓을것인지?
list_var1 = [0.001, 0.0001, 0.00001]
list_var2 = [1,2,3]

#데이터셋 실제 형성
trainset = StockDataset(args.symbol, args.x_frames, args.y_frames, (2012,1,1), (2021,1,1)) #학습기간
valset = StockDataset(args.symbol, args.x_frames, args.y_frames, (2021,1,2), (2021,12,30)) #검증기간 최소 +6 월, +19 일 안하면 float division by zero 에러 발생 왜?? 21년 기준
testset = StockDataset(args.symbol, args.x_frames, args.y_frames, (2022,1,10), (2022,1,14)) #테스트기간 최소 +6 월, + 25일 안하면 float division by zero 에러 발생. 22년기준
#기간이 일정 영업일 이상을 요구하는듯?  <<146 영업일 이상 데이터 요구. 그만큼 안주면 오류남 왜??

partition = {'train': trainset, 'val':valset, 'test':testset}

for var1 in list_var1:
    for var2 in list_var2:
        setattr(args, name_var1, var1)
        setattr(args, name_var2, var2)
        print(args)

        setting, result = experiment(partition, deepcopy(args))
        save_exp_result(setting, result)

    #꼭 디렉토리에 있는 파일들 지운다음에 그래프 그려야한다. 안그러면 결과값 전부 겹쳐서 나옴

This one is hyper parameter regulate.

I wonder how can I get result when I set testset length in 5days?  (like (2022,1,10)  (2022,1,14))

This cord didn't work when I set testset length at least 7month (maybe + 146 trade day)

error is float divided by zero. (when I use  lower 146 days.)

if I set length +146 days, then codes work well.

I think this code cause error:

data = data.apply(lambda x: np.log(x+1) - np.log(x[self.x_frames-1]+1))

log data was so small, so error occurred. (my opinion)

data is yahoo finance data. Thanx to read

When I # below code, then data got infinite.

data = data.apply(lambda x: np.log(x+1) - np.log(x[self.x_frames-1]+1))