问:
How to convert points using one age model to another age model using Python?
Sorry if this has been asked before but it's hard to come up with a googleable phrase to find it.

I have isotope data from a core hole that has multiple possible age models as shown below in figure 1
Age Models

Age Models 2
Some of the models have defined slopes over different intervals and a few do not. They were created using density data taken at depths that are different to ones I used to get isotope data and so I cant just straight convert the ages I used for my data into ones from other models.

I can convert ages for the models with defined interval slopes, but I would like to learn how to convert using age models such as the ones in figure 2 that do not have known defined intervals using python.

I have some code left over made by the person who did the creation of the main tuned model which I think could be moulded but I am not sure.

```<code>import os
import sys
import csv
import numpy
import matplotlib.pyplot as plt
import scipy
from scipy import signal
from scipy import interpolate
from scipy.signal import butter, lfilter
from scipy import stats
import pandas as pd

def age_model(ds_depths,ds_values,am_depths,am_ages,new_t):
    f_am = interpolate.interp1d(am_ages,am_depths)
    depths = f_am(new_t)
    f_dv = interpolate.interp1d(ds_depths,ds_values)
    new_values = f_dv(depths)
    return new_t,depths,new_values
</code>```

I am guessing interpolate is probably the function best for this type of work?

Body:
Sorry if this has been asked before but it's hard to come up with a googleable phrase to find it.

I have isotope data from a core hole that has multiple possible age models as shown below in figure 1
Age Models

Age Models 2
Some of the models have defined slopes over different intervals and a few do not. They were created using density data taken at depths that are different to ones I used to get isotope data and so I cant just straight convert the ages I used for my data into ones from other models.

I can convert ages for the models with defined interval slopes, but I would like to learn how to convert using age models such as the ones in figure 2 that do not have known defined intervals using python.

I have some code left over made by the person who did the creation of the main tuned model which I think could be moulded but I am not sure.

import os
import sys
import csv
import numpy
import matplotlib.pyplot as plt
import scipy
from scipy import signal
from scipy import interpolate
from scipy.signal import butter, lfilter
from scipy import stats
import pandas as pd

def age_model(ds_depths,ds_values,am_depths,am_ages,new_t):
    f_am = interpolate.interp1d(am_ages,am_depths)
    depths = f_am(new_t)
    f_dv = interpolate.interp1d(ds_depths,ds_values)
    new_values = f_dv(depths)
    return new_t,depths,new_values

I am guessing interpolate is probably the function best for this type of work?


来源: stackexchange

问:
Child_process is not running python inside of vscode extension (extension.js)
I am using the following code to run a python from node. The code works fine as a separate file but when I put it in a VSCode Extension (extension.js), it says graph.py not found.

```<code>const {spawn} = require('child_process')

const child = spawn('python3', ['graph.py'])

child.stdout.on('data', (data)=>{
    console.log(`stdout: ${data}`)
})

child.stderr.on('data', (data)=>{
    console.log(`stderr: ${data}`)
})

child.on('error', (error)=> console.log(`error: ${error.message}`))

child.on('exit', (code, signal)=>{
    if(code) console.log(`Process exit with code: ${code}`)
    if(signal) console.log(`Process killed with signal: ${signal}`)
    console.log(`DONE!!`)
})
</code>```

Does anyone know how to fix it?
TIA.

ContentLicense: CC BY-SA 4.0

Body:
I am using the following code to run a python from node. The code works fine as a separate file but when I put it in a VSCode Extension (extension.js), it says graph.py not found.

const {spawn} = require('child_process')

const child = spawn('python3', ['graph.py'])

child.stdout.on('data', (data)=>{
    console.log(`stdout: ${data}`)
})

child.stderr.on('data', (data)=>{
    console.log(`stderr: ${data}`)
})

child.on('error', (error)=> console.log(`error: ${error.message}`))

child.on('exit', (code, signal)=>{
    if(code) console.log(`Process exit with code: ${code}`)
    if(signal) console.log(`Process killed with signal: ${signal}`)
    console.log(`DONE!!`)
})

Does anyone know how to fix it?
TIA.


问:
Android: how to use Instrumentation in Background Processes
I am trying to simulate Keypresses via my Android APP while my App runs in the Background. (Spoiler: I am a complete Beginner)

I realized the functionality with Instrumentations eg.:

```<code>new Thread(new Runnable() {
            @Override
            public void run() {
                Instrumentation inst = new Instrumentation();
                inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
            }
        }).start();`
</code>```

In the foreground this works fine but in the Background I found out I cannot do this because I have no permission.INJECT_EVENTS. How do I get this permission somehow easily. I don't want to root my Phone or install a custom ROM

Body:
I am trying to simulate Keypresses via my Android APP while my App runs in the Background. (Spoiler: I am a complete Beginner)

I realized the functionality with Instrumentations eg.:

new Thread(new Runnable() {
            @Override
            public void run() {
                Instrumentation inst = new Instrumentation();
                inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
            }
        }).start();`

In the foreground this works fine but in the Background I found out I cannot do this because I have no permission.INJECT_EVENTS. How do I get this permission somehow easily. I don't want to root my Phone or install a custom ROM


问:
problem while import RSA public key in python _ ValueError: RSA key format is not supported
I tried to import this RSA public key :

```<code>from hashlib import md5
from base64 import b64decode
from base64 import b64encode
import json
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Cryptodome.Util import Padding
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from Crypto.Util import asn1
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64decode
import binascii

public_key = """MIGqAgEAAoGBAI688Ywhsy+PP47tnnXp2wqLvVLRZ7uvheTjKfxZFy1RYWl886c5\r\nzFndlBFOcYcr5NCfDDjjV+7CbPXo6Rid3xh+o36uEX/RIOWPq/TAuqlmkBPJpjvg\r\npYbbOcAjX3kZ0fT78GLpf8V6Vk3ctAj2bVeDlpoDOXIfgqE7lcMzbTAnAgMBAAEC\r\nAwEAAQIDAQABAgMBAAECAwEAAQIDAQABAgMBAAE=""".replace('\r\n', '\n')

raw_key = b64decode(public_key)
recipient_key = RSA.import_key(raw_key)

</code>```

but got Error !

ValueError: RSA key format is not supported

then tried another way :

```<code>formated = "-----BEGIN PUBLIC KEY-----\n"+raw_key +"\n-----END PUBLIC KEY-----"
recipient_key = RSA.import_key(formated)
</code>```

but this didn't work !

verified the key with https://holtstrom.com/michael/tools/asn1decoder.php

and key is correct !

I want to use this key to encrypt data with python ,

Can someone please help me out?

Body:
I tried to import this RSA public key :

from hashlib import md5
from base64 import b64decode
from base64 import b64encode
import json
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Cryptodome.Util import Padding
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from Crypto.Util import asn1
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64decode
import binascii

public_key = """MIGqAgEAAoGBAI688Ywhsy+PP47tnnXp2wqLvVLRZ7uvheTjKfxZFy1RYWl886c5\r\nzFndlBFOcYcr5NCfDDjjV+7CbPXo6Rid3xh+o36uEX/RIOWPq/TAuqlmkBPJpjvg\r\npYbbOcAjX3kZ0fT78GLpf8V6Vk3ctAj2bVeDlpoDOXIfgqE7lcMzbTAnAgMBAAEC\r\nAwEAAQIDAQABAgMBAAECAwEAAQIDAQABAgMBAAE=""".replace('\r\n', '\n')

raw_key = b64decode(public_key)
recipient_key = RSA.import_key(raw_key)

but got Error !

ValueError: RSA key format is not supported

then tried another way :

formated = "-----BEGIN PUBLIC KEY-----\n"+raw_key +"\n-----END PUBLIC KEY-----"
recipient_key = RSA.import_key(formated)

but this didn't work !

verified the key with https://holtstrom.com/michael/tools/asn1decoder.php

and key is correct !

I want to use this key to encrypt data with python ,

Can someone please help me out?


问:
How does dbt with Spark work under the hood on EMR?
I am a data engineer who is relatively new to dbt, but our data science and analytics team has been using dbt for couple months. And the DE team recently is required to do an audit on the cost for the dbt pipelines.

Our architecture is quite standard:

dbt + spark via thrift server running on AWS EMR, data stored on S3 as parquet files registered in hive catalog.

So far, the main saving opportunity we found was to utilize spot instance rather than running all instances On-demand. But the problem is that from our observation, dbt pipeline rarely use the task instance but most of the work happened on core nodes (where the data node lives). But we don’t want to run core nodes with spot lifecycle as the loss of a core node may introduce data loss. And the run time of the pipeline seems to be in negative correlation with the number of core nodes.

Are there any suggestion on how to isolate the root cause of this behavior? Was it simply because the dbt pipeline we are running is mainly talking to HDFS? So the heavy lifting all happens on core nodes? Or thrift server itself doesn’t utilize task nodes (this might be a stupid question, cause I don’t fully understand how thrift server works, it sounds like a simple JDBC/ODBC, so it shouldn’t be different from a normal spark application right?)

Very much appreciate!

Increase/decrease Core/Task nodes and observe executors, performance and run time


问:
polars groupby on categorical produces nulls
I ran into an issue with polars where after a groupby on a categorical variable the labels are null

import polars as pl
scores = pl.DataFrame({
    'zone': ['North', 'North', 'South', 'South'],
    'score': [78, 39, 76, 56]
}).with_column(pl.col("zone").cast(pl.Categorical))

scores.groupby("zone").count()
```

This produces the output below with null values for the levels. Is this expected? If so, is there a fix? Note that this doesn't happen when zone is set to a string

Body:
I ran into an issue with polars where after a groupby on a categorical variable the labels are null

import polars as pl
scores = pl.DataFrame({
    'zone': ['North', 'North', 'South', 'South'],
    'score': [78, 39, 76, 56]
}).with_column(pl.col("zone").cast(pl.Categorical))

scores.groupby("zone").count()

This produces the output below with null values for the levels. Is this expected? If so, is there a fix? Note that this doesn't happen when zone is set to a string


问:
Flutter App White Screen(Or crashed) in Release Mode
A/flutter: [FATAL:flutter/runtime/dart_vm_initializer.cc(22)] Error while initializing the Dart VM: Precompiled runtime requires a precompiled snapshot
A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 9712

My flutter app got Crashed in release mode.. instead all working fine in debug mode.
while checking with separate opening android folder in Android studio and run in release mode. I got this issue
"Error while initializing the Dart VM: Precompiled runtime requires a precompiled snapshot".

Version Info that I'm used

```<code>flutter version : 3.0.5

compileSdkVersion 33
minSdkVersion 21
targetSdkVersion 33

dependencies {
        classpath 'com.android.tools.build:gradle:4.1.3'
//        classpath 'com.android.tools.build:gradle:3.6.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.5'
    }
</code>```

Log Cat Data by running separate android folder in android studio by enabling debuggable true in build.gradle.

01/22 00:12:00: Launching 'app' on Pixel 4 API 31.
Install successfully finished in 4 s 839 ms.
$ adb shell am start -n "com.ore/com.ore.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 16685 on device 'Pixel_4_API_31 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/.outreachexper: Late-enabling -Xcheck:jni
W/.outreachexper: Unexpected CPU variant for X86 using defaults: x86_64
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10163; state: ENABLED
V/GraphicsEnvironment: ANGLE Developer option for 'com.ore' set to: 'default'
V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
I/ResourceExtractor: Found extracted resources res_timestamp-1-1674385878848
I/ResourceExtractor: Resource version mismatch res_timestamp-1-1674387737896
I/ResourceExtractor: Extracted baseline resource assets/flutter_assets/kernel_blob.bin
I/ResourceExtractor: Extracted baseline resource assets/flutter_assets/vm_snapshot_data
I/ResourceExtractor: Extracted baseline resource assets/flutter_assets/isolate_snapshot_data
W/.ore: type=1400 audit(0.0:310): avc: denied { map } for path="/data/data/com.ore/app_flutter/flutter_assets" dev="dm-5" ino=148729 scontext=u:r:untrusted_app:s0:c163,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c163,c256,c512,c768 tclass=dir permissive=0 app=com.ore
A/flutter: [FATAL:flutter/runtime/dart_vm_initializer.cc(22)] Error while initializing the Dart VM: Precompiled runtime requires a precompiled snapshot

    --------- beginning of crash
A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 16685 (.ore), pid 16685 (.ore)
W/.ore: type=1400 audit(0.0:311): avc: denied { map } for path="/data/data/com.ore/app_flutter/flutter_assets" dev="dm-5" ino=148729 scontext=u:r:untrusted_app:s0:c163,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c163,c256,c512,c768 tclass=dir permissive=0 app=com.ore
W/.ore: type=1400 audit(0.0:312): avc: denied { read } for name="max_map_count" dev="proc" ino=183138 scontext=u:r:untrusted_app:s0:c163,c256,c512,c768 tcontext=u:object_r:proc_max_map_count:s0 tclass=file permissive=0 app=com.ore
```

Body:
A/flutter: [FATAL:flutter/runtime/dart_vm_initializer.cc(22)] Error while initializing the Dart VM: Precompiled runtime requires a precompiled snapshot
A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 9712

My flutter app got Crashed in release mode.. instead all working fine in debug mode.
while checking with separate opening android folder in Android studio and run in release mode. I got this issue
"Error while initializing the Dart VM: Precompiled runtime requires a precompiled snapshot".

Version Info that I'm used

flutter version : 3.0.5

compileSdkVersion 33
minSdkVersion 21
targetSdkVersion 33

dependencies {
        classpath 'com.android.tools.build:gradle:4.1.3'
//        classpath 'com.android.tools.build:gradle:3.6.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.5'
    }

Log Cat Data by running separate android folder in android studio by enabling debuggable true in build.gradle.

01/22 00:12:00: Launching 'app' on Pixel 4 API 31.
Install successfully finished in 4 s 839 ms.
$ adb shell am start -n "com.ore/com.ore.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 16685 on device 'Pixel_4_API_31 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/.outreachexper: Late-enabling -Xcheck:jni
W/.outreachexper: Unexpected CPU variant for X86 using defaults: x86_64
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10163; state: ENABLED
V/GraphicsEnvironment: ANGLE Developer option for 'com.ore' set to: 'default'
V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
I/ResourceExtractor: Found extracted resources res_timestamp-1-1674385878848
I/ResourceExtractor: Resource version mismatch res_timestamp-1-1674387737896
I/ResourceExtractor: Extracted baseline resource assets/flutter_assets/kernel_blob.bin
I/ResourceExtractor: Extracted baseline resource assets/flutter_assets/vm_snapshot_data
I/ResourceExtractor: Extracted baseline resource assets/flutter_assets/isolate_snapshot_data
W/.ore: type=1400 audit(0.0:310): avc: denied { map } for path="/data/data/com.ore/app_flutter/flutter_assets" dev="dm-5" ino=148729 scontext=u:r:untrusted_app:s0:c163,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c163,c256,c512,c768 tclass=dir permissive=0 app=com.ore
A/flutter: [FATAL:flutter/runtime/dart_vm_initializer.cc(22)] Error while initializing the Dart VM: Precompiled runtime requires a precompiled snapshot

    --------- beginning of crash
A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 16685 (.ore), pid 16685 (.ore)
W/.ore: type=1400 audit(0.0:311): avc: denied { map } for path="/data/data/com.ore/app_flutter/flutter_assets" dev="dm-5" ino=148729 scontext=u:r:untrusted_app:s0:c163,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c163,c256,c512,c768 tclass=dir permissive=0 app=com.ore
W/.ore: type=1400 audit(0.0:312): avc: denied { read } for name="max_map_count" dev="proc" ino=183138 scontext=u:r:untrusted_app:s0:c163,c256,c512,c768 tcontext=u:object_r:proc_max_map_count:s0 tclass=file permissive=0 app=com.ore


问:
Download a sharepoint file using urlmon.DLL download file
I’m trying to download files using sharepoint link(path link) using urlmon.DLL in C#. It’s downloading full file sometimes and sometimes it’s creating corrupted file. Any solutions to resolve this?

I tried in vscode c#, it’s definitely downloading file but it’s not happening for every run


问:
Will these steps secure access to ActiveAdmin?
I'm using ActiveAdmin for a new online marketplace. Security is very important to ensure we keep our customers safe on our platform. Please give advice on how to secure access to ActiveAdmin.

Listed below are ways that I plan to secure access:

1. Hide the URL & require https:
To make it difficult to find our admin center, I plan to create a namespace that is difficult to guess by using a random string.
(Example: https://api.mysite.com/oj7Gd3a8deLfwaXt/admin/login)

2. Remove first user creditials:
By default, the first admin user is admin@example.com with the password password. This default admin account will be removed.

3. Two-Factor Authentication:
It's possible to add the functionality for TFA. I plan to require a code (from Authy or Google Authenticator) for every attempt at signing-in.

Do you consider this to be good security for protecting access to ActiveAdmin? Are there other steps that you recommend?


问:
Ncurses - Issue with A_DIM effect and init_color

Issue

I have recently come across an issue, I can't figure out where it comes from. It appears to be related to an unexpected behavior of the ncurses library when attempting to apply the A_DIM effect on colors other than the first 9 (they don't get dimmed). Furthermore, when initializing a color to one of the first 9 colors (such as init_color(2,0,100,843)), the A_DIM effect seems to result in the dimmed color of the predefined color:

A minimal reproducible example

#include <curses.h>

void draw_lines(int y, int c)
{
  char ch = wgetch(stdscr);
  init_pair(c, c, COLOR_BLACK);
  mvhline(y   ,0,'B', COLS);
  mvhline(y+1 ,0,'B', COLS);
  mvhline(y+2 ,0,'B', COLS);
  mvchgat(y  , 0, -1, A_BOLD  , c, NULL);
  mvchgat(y+1, 0, -1, A_NORMAL, c, NULL);
  mvchgat(y+2, 0, -1, A_DIM   , c, NULL);
}

int main()
{
  initscr();
  if (!has_colors()) return -1;
  int i=0, j=0;

  start_color  ( );
  cbreak       ( );
  noecho       ( );
  curs_set     (0);
  mouseinterval(0);
  keypad(stdscr, TRUE);
  refresh      ( );

  for (i=0; i<LINES; i+=3) {
    draw_lines(i, j);
    j += 1;
  }
  for (i=1; i<LINES/3; i++) {
    init_color(i,0,100,843); // BLUE
    draw_lines(i*3, i);
  }
  endwin();
  return 0;
}
```

(I am using Alacritty and ncurses-6.4-1)

Question

Is this supposed to happen? and if yes, then how should I approch the initialization of colors, if I want to preserve the ability of the user to customize colors in my app but also keep things sane?

But Why

The reason I care so much is this, where my aproach goes something like this. Meaning that I use an offset so that the user can define custom colors for every individual tui-component, but also be able to have the same color-pattern for all of them if he\she wants so.

Outro

Any idea? Thanks in advance for any help.

Body:
Issue

I have recently come across an issue, I can't figure out where it comes from. It appears to be related to an unexpected behavior of the ncurses library when attempting to apply the A_DIM effect on colors other than the first 9 (they don't get dimmed). Furthermore, when initializing a color to one of the first 9 colors (such as init_color(2,0,100,843)), the A_DIM effect seems to result in the dimmed color of the predefined color:

A minimal reproducible example

#include <curses.h>

void draw_lines(int y, int c)
{
  char ch = wgetch(stdscr);
  init_pair(c, c, COLOR_BLACK);
  mvhline(y   ,0,'B', COLS);
  mvhline(y+1 ,0,'B', COLS);
  mvhline(y+2 ,0,'B', COLS);
  mvchgat(y  , 0, -1, A_BOLD  , c, NULL);
  mvchgat(y+1, 0, -1, A_NORMAL, c, NULL);
  mvchgat(y+2, 0, -1, A_DIM   , c, NULL);
}

int main()
{
  initscr();
  if (!has_colors()) return -1;
  int i=0, j=0;

  start_color  ( );
  cbreak       ( );
  noecho       ( );
  curs_set     (0);
  mouseinterval(0);
  keypad(stdscr, TRUE);
  refresh      ( );

  for (i=0; i<LINES; i+=3) {
    draw_lines(i, j);
    j += 1;
  }
  for (i=1; i<LINES/3; i++) {
    init_color(i,0,100,843); // BLUE
    draw_lines(i*3, i);
  }
  endwin();
  return 0;
}

(I am using Alacritty and ncurses-6.4-1)

Question

Is this supposed to happen? and if yes, then how should I approch the initialization of colors, if I want to preserve the ability of the user to customize colors in my app but also keep things sane?

But Why

The reason I care so much is this, where my aproach goes something like this. Meaning that I use an offset so that the user can define custom colors for every individual tui-component, but also be able to have the same color-pattern for all of them if he\she wants so.

Outro

Any idea? Thanks in advance for any help.


问:
Celery get task name
I am using celery in my application, I want to enable or disable some fields in app depending on currently executing task, for this purpose I need the name of the task which is currently in execution.

So, I tried below code but it always returning task name as None even though I have specified the task name in the decorator.

```<code>celery_app = Celery(__name__, broker=mc.REDIS_URL, backend=mc.REDIS_URL)
</code>```
```<code>celery_app.conf.update(
    task_create_missing_queues=True,
    result_extended=True,  # I have enabled this setting but its not working
    worker_prefetch_multiplier=1,
)
</code>```

Task

```<code>@celery_app.task(bind=True, name="job_one")
def background_task_job_one(self, n_clicks):
    status = False

    # some long running task

    return status
</code>```

Calling using apply_async

```<code>result: AsyncResult = background_task_job_one.apply_async(args=(some arguments), queue="job_queue")

print(f"Task name: {result.name}")  # expecting job_one but getting None
</code>```

Please suggest.

Title: Celery get task name

Body:
I am using celery in my application, I want to enable or disable some fields in app depending on currently executing task, for this purpose I need the name of the task which is currently in execution.

So, I tried below code but it always returning task name as None even though I have specified the task name in the decorator.

celery_app = Celery(__name__, broker=mc.REDIS_URL, backend=mc.REDIS_URL)

celery_app.conf.update(
    task_create_missing_queues=True,
    result_extended=True,  # I have enabled this setting but its not working
    worker_prefetch_multiplier=1,
)

Task

@celery_app.task(bind=True, name="job_one")
def background_task_job_one(self, n_clicks):
    status = False

    # some long running task

    return status

Calling using apply_async

result: AsyncResult = background_task_job_one.apply_async(args=(some arguments), queue="job_queue")

print(f"Task name: {result.name}")  # expecting job_one but getting None

Please suggest.


问:
Override parametrize content before test execution
I would like to be able to dynamically parametrize a test function passed on the command line and override any previously set parametrize value.

Example of command line execution: python -m pytest --TEST_FUNCTION=test_dummy

test_file.py:

```<code>@pytest.mark.parametrize('vm_name', ['vm1', 'vm2'])
def test_dummy(self, vm_name):
    DEBUG(f'Hi {vm_name}!')
</code>```

conftest.py:

```<code>def pytest_generate_tests(metafunc):
test_function = metafunc.config.getoption('--TEST_FUNCTION')
if test_function is not None and metafunc.definition.name == test_function:
    own_markers = []
    for own_marker in metafunc.definition.own_markers:
        if own_marker.args[0] == 'vm_name':
            own_markers.append(pytest.Mark(name=own_marker.name, args=('vm_name', ['vm3', 'vm4']), kwargs=own_marker.kwargs))
        else:
            own_markers.append(own_marker)
    metafunc.definition.own_markers = own_markers

</code>```

This works fine and at execution time, test_dummy runs with vm3 and vm4 even though it's been marked with vm1/vm2 in the code, but the problem with my approach is that pytest.Mark() is private and this may not work forever.

Is there another or a better way to override what may have already been set with the parametrize decorator with something else?

Body:
I would like to be able to dynamically parametrize a test function passed on the command line and override any previously set parametrize value.

Example of command line execution: python -m pytest --TEST_FUNCTION=test_dummy

test_file.py:

@pytest.mark.parametrize('vm_name', ['vm1', 'vm2'])
def test_dummy(self, vm_name):
    DEBUG(f'Hi {vm_name}!')

conftest.py:

def pytest_generate_tests(metafunc):
test_function = metafunc.config.getoption('--TEST_FUNCTION')
if test_function is not None and metafunc.definition.name == test_function:
    own_markers = []
    for own_marker in metafunc.definition.own_markers:
        if own_marker.args[0] == 'vm_name':
            own_markers.append(pytest.Mark(name=own_marker.name, args=('vm_name', ['vm3', 'vm4']), kwargs=own_marker.kwargs))
        else:
            own_markers.append(own_marker)
    metafunc.definition.own_markers = own_markers

This works fine and at execution time, test_dummy runs with vm3 and vm4 even though it's been marked with vm1/vm2 in the code, but the problem with my approach is that pytest.Mark() is private and this may not work forever.

Is there another or a better way to override what may have already been set with the parametrize decorator with something else?


问:
ModuleNotFoundError: No module named 'setuptools.command.build' when installing pybcj>=0.6.0 (from py7zr>=0.18.3->aqtinstall)
I'm trying to install aqtinstall in a docker container on ubuntu. During the dependency install, pybcj keeps failing with error:

ModuleNotFoundError: No module named 'setuptools.command.build'

When this worked before, the aqtinstall was 2 and now it appears to be 3, but I'm not sure if that is even relevant here.

What causes this and how can I workaround it?


问:
Terraform AWS dependency problem between AppSync resolver and AppSync function
When I will create the AppSync resolver with linked function by the terraform, everything is created and it works.

But error will arise, If I will rename the function in terraform file, which is linked to some resolver and then I execute terraform apply again. Terraform cannot apply changes, because It wants to re-create function, which is linked to resolver. I was thinking, that If I will add depends_on field into resolver, it will solve this problem, but It didn't helped. it won't do anything and still I have the same problem.

Error deleting AppSync Function... BadRequestException: Cannot delete a function which is currently used by a resolver. Resolver type: Test, field: testField

Therefore I was trying opposite way. I added "depends_on" field into function pointing to resolver, but after that, I get an "Circular dependency" error during terraform apply.

```<code>Error: Cycle: module..., module..., module..., ....
</code>```

How can I correctly use the terraform dependencies to solve this problem?

Short example:

```<code>
resource "aws_appsync_resolver" "TestResolver" {
  api_id            = var.app-sync-id
  field             = "testField"
  type              = "Query"
  request_template  = "{}"
  response_template = "$util.toJson($context.result)"
  kind              = "PIPELINE"

  pipeline_config {
    functions = [
      aws_appsync_function.TestFunction.function_id
    ]
  }
}

resource "aws_appsync_function" "TestFunction" {
  api_id                   = var.app-sync-id
  data_source              = local.table-name
  name                     = "TestFunction"
  request_mapping_template = <<EOF
    ...whatever
EOF

  response_mapping_template = <<EOF
...whatever
EOF
}
</code>```

Body:
When I will create the AppSync resolver with linked function by the terraform, everything is created and it works.

But error will arise, If I will rename the function in terraform file, which is linked to some resolver and then I execute terraform apply again. Terraform cannot apply changes, because It wants to re-create function, which is linked to resolver. I was thinking, that If I will add depends_on field into resolver, it will solve this problem, but It didn't helped. it won't do anything and still I have the same problem.

Error deleting AppSync Function... BadRequestException: Cannot delete a function which is currently used by a resolver. Resolver type: Test, field: testField

Therefore I was trying opposite way. I added "depends_on" field into function pointing to resolver, but after that, I get an "Circular dependency" error during terraform apply.

Error: Cycle: module..., module..., module..., ....

How can I correctly use the terraform dependencies to solve this problem?

Short example:

resource "aws_appsync_resolver" "TestResolver" {
  api_id            = var.app-sync-id
  field             = "testField"
  type              = "Query"
  request_template  = "{}"
  response_template = "$util.toJson($context.result)"
  kind              = "PIPELINE"

  pipeline_config {
    functions = [
      aws_appsync_function.TestFunction.function_id
    ]
  }
}

resource "aws_appsync_function" "TestFunction" {
  api_id                   = var.app-sync-id
  data_source              = local.table-name
  name                     = "TestFunction"
  request_mapping_template = <<EOF
    ...whatever
EOF

  response_mapping_template = <<EOF
...whatever
EOF
}


问:
How to call db2prereqcheck in command prompt?
Want to know the prerequisite to install DB2 on my machine, and wants to run 'db2prereqcheck' command on command prompt(cmd). Any lead will be appreciated. Thanks!

Tried this command db2prereqcheck -p -v 11.5.0.0 but it's showing 'db2prereqcheck' is not recognized as an internal or external command,
operable program or batch file error. Do I need any installer or software before running this command?


问:
How can I force the command line to run a program from the lower-most folder where the file is located?
I am trying to write a script to run a small c++ program on another, higher-end computing environment. I have the script working on my local PC but I want to write the command as a .bat file so I can give it to someone else to run. The issue that I am running in to is that the file is set to run on my local PC and therefore it follows my directory path. I want it to be able to run from a single file, regardless of the entire directory path.

```<code>cd C:\Users\username\Desktop\file\subfile1\subfile2
</code>```

This change the working directory to the file on my desktop where the c++ program and file are located.

```<code>main -m C:\Users\username\Desktop\file\subfile1\subfile2\c++_file_part1 C:\Users\username\Desktop\file\subfile1\subfile2\c++_file_part2 > C:\Users\username\Desktop\file\subfile1\subfile2\output.txt
</code>```

The purpose of the above code is to run the c++ program (consists of 2 parts), but it runs it from the subfile2 location on my desktop, which is located in subfile1, file, ...etc. Is there a way where I can give someone a file named 'subfile2' and they will be able to run in on their computer, or I can take the file to another computer via flash drive?

The entire purpose of this program is to transcribe audio using 5 different formats. Each format has a different latency and processing speed, so I am trying to figure out if the transcription time will be different by having the program run as a script to make it easier rather than run it manually.

Thanks in advance.

Body:
I am trying to write a script to run a small c++ program on another, higher-end computing environment. I have the script working on my local PC but I want to write the command as a .bat file so I can give it to someone else to run. The issue that I am running in to is that the file is set to run on my local PC and therefore it follows my directory path. I want it to be able to run from a single file, regardless of the entire directory path.

cd C:\Users\username\Desktop\file\subfile1\subfile2

This change the working directory to the file on my desktop where the c++ program and file are located.

main -m C:\Users\username\Desktop\file\subfile1\subfile2\c++_file_part1 C:\Users\username\Desktop\file\subfile1\subfile2\c++_file_part2 > C:\Users\username\Desktop\file\subfile1\subfile2\output.txt

The purpose of the above code is to run the c++ program (consists of 2 parts), but it runs it from the subfile2 location on my desktop, which is located in subfile1, file, ...etc. Is there a way where I can give someone a file named 'subfile2' and they will be able to run in on their computer, or I can take the file to another computer via flash drive?

The entire purpose of this program is to transcribe audio using 5 different formats. Each format has a different latency and processing speed, so I am trying to figure out if the transcription time will be different by having the program run as a script to make it easier rather than run it manually.

Thanks in advance.


问:
How Can I code a widget that automatically looks at users location and matches it with the closest store?
How Can I code a widget that automatically looks at users location and matches it with the closest store and then inputs the location in the header of my website?</p>


问:
WordPress - Nav Menu toplevel does not act as link
I'm very new to WordPress and don't know much about CSS and stuff, so I already apologize in case I'm missing basic information. It might be a silly question, but still: how can I make the toplevel of my navigation menu be clickable links instead of just acting as dropdowns on hover? I found tons of solutions on how to remove that behaviour, but I explicitly want it.

I'm using WordPress 6.1.1 with the "Zeever" template and have added a navigation menu with toplevel items and sometimes sub-items. In such cases, the sub-items act as clickable links, e.g. to an HTML anchor, like #contact. I want that same behaviour for the toplevel item as well.

Example:

```<code>- About
  | - Company
  | - Services
- News
- Contacts
</code>```

For me, About is not acting as a link, but only shows Company and Services (which are clickable themselves), although I added #about as the URL in the menu editor and also set the respective HTML anchor.

Happy for any suggestions :)

Body:
I'm very new to WordPress and don't know much about CSS and stuff, so I already apologize in case I'm missing basic information. It might be a silly question, but still: how can I make the toplevel of my navigation menu be clickable links instead of just acting as dropdowns on hover? I found tons of solutions on how to remove that behaviour, but I explicitly want it.

I'm using WordPress 6.1.1 with the "Zeever" template and have added a navigation menu with toplevel items and sometimes sub-items. In such cases, the sub-items act as clickable links, e.g. to an HTML anchor, like #contact. I want that same behaviour for the toplevel item as well.

Example:

- About
  | - Company
  | - Services
- News
- Contacts

For me, About is not acting as a link, but only shows Company and Services (which are clickable themselves), although I added #about as the URL in the menu editor and also set the respective HTML anchor.

Happy for any suggestions :)


问:
Using Incremental Source Generator to re-generate code only when a type in a project reference changes
I have three projects:

Api

Contains EF entities. They all inherit from a class BaseEntity.

Api.Test

Contains tests that uses the EF entities. The tests usually setup an in-memory or SqlLite DbContext and add the entities to it. The entities are created using the builder pattern (ie: new UserBuilder().WithFirstName('Kevin').Build()). Those builders are generated using a source generator, each property on the entities have a With{PropertyName}() method.

Contains partial class for those entity builders. These partial classes set defaults on certain properties so we don't have to set up every single property every time, and contains extra methods that do more complicated things.

Api.Test.Generator

Referenced by Api.Test

Has a EntityBuilderGenerator inheriting from ISourceGenerator to generate the builders as partial classes so they can be customized, of any type inheriting from BaseEntity. I was able to use context.Compilation.SourceModule.ReferencedAssemblySymbols to find the entity types I want from the Api project.

Because EntityBuilderGenerator is a basic source generator, it seems it is called and re-generates builders for every single keystroke that happens. It makes writing code or using refactoring/suggestions in the project incredibly slow and painful.

There is now incremental source generators. The problem is that my generator is referenced by the Api.Test project since that's where I want the builders generated, but there's nothing of interest for me there - I want to regenerate the builders when something specific in the Api project changes (any type with a base class of BaseEntity). I don't care about Api.Test project changes.

It works if I reference the Generator project in the Api project, but that means the builders (and the custom partial classes for these), meant to be only used by the test project, are in the API project, which I don't want.

Can I use incremental generators to re-generate code only when a type in a project reference changes?


问:
Python Socks AttributeError: type object 'MailBox' has no attribute 'socket'
I am doing something wrong here or is it as simple as this module is not supported with socks?</p>
```<code>socks.set_default_proxy(socks.HTTP, "proxy.ipproxy.me", 8080, "Johnson", "9P@sw0rd")
        socket.socket = socks.socksocket
        socks.wrap_module(MailBox)
        server = 'outlook.office365.com'
        mb = MailBox(server).login(user, password)
        mb.port = 993
        messages = mb.fetch(criteria=AND(seen=False, subject="Read me"),mark_seen=True,bulk=True)
</code>```

Body:
I am doing something wrong here or is it as simple as this module is not supported with socks?

socks.set_default_proxy(socks.HTTP, "proxy.ipproxy.me", 8080, "Johnson", "9P@sw0rd")
        socket.socket = socks.socksocket
        socks.wrap_module(MailBox)
        server = 'outlook.office365.com'
        mb = MailBox(server).login(user, password)
        mb.port = 993
        messages = mb.fetch(criteria=AND(seen=False, subject="Read me"),mark_seen=True,bulk=True)


问:
How to Create Cordova install
My application itself is developed with Angular and Ionic 3, Ionic has a system for integrating features of devices such as Bluetooth, camera, network, among others, the name of this system is Cordova. The new versions of Ionic use a new system called Capacitor, but even this new system uses a lot of Cordova itself. The plugins for the readers are developed to be installed by Cordova and these plugins are developer systems on top of the SDK of the reader itself that are in Java.

I try to use Android Studio, but it is not working. Can anyone help me?

Title: How to Create Cordova install


问:
How to get physical address of kernel symbol?
I'm trying to get the physical address of a kernel symbol (because I need it to be read by a system that only accepts phys addr). So I'm using things like __pa(vaddr) and virt_to_phys(vaddr).

Problem is that the conversion is not correct everytime. Sometimes it is, sometimes it's not. How do I know that? Because I'm reading the value on the kernel module as well and comparing to value read using fmem and using my other system.

Ex:

my kernel symbol's address is 0xffffffffb3400000, so when I do
printk(KERN_INFO "Addr: 0x%lx , Value: 0x%lx\n", _stext, *_stext) I get => Addr: 0xffffffffb3400000 , Value: 0x4801e03f51258d48.

When it reads right I use fmem and the other system to read the physical address given by __pa and the value matches 0x4801e03f51258d48 in both cases. But sometimes it doesn't work, so the value is different. And how do I know the value itself hasn't changed? Because dereferencing the virtual address still gives me the result 0x4801e03f51258d48.

I know kernel code and data changes on every boot (including kernel symbols addresses), that's not a problem since I'm getting the kernel symbol's addr everytime. But I expected the virtual to phys mapping to be the same every time, shouldn't it be? I mean, what can I do to get the physical address of my kernel symbol correctly?

So right now I have

u64 _stext_pa = __pa(_stext_va)
printk(KERN_INFO "Value of _stext (va: 0x%lx | pa: 0x%x) = 0x%lx\n", _stext_va, _stext_pa, *_stext_va)
```

Addresses (virtual and physical) change every boot but the value is always the same. That's what I need.

I need a physical address paddr so that I can perform int value = *paddr; on my other system and get the same result I'm getting with the virtual address

Edit: this "other system" I'm refering to is an SMM driver, but that's not relevant, just in case you might be wondering "what is 'other system'"

Body:
I'm trying to get the physical address of a kernel symbol (because I need it to be read by a system that only accepts phys addr). So I'm using things like __pa(vaddr) and virt_to_phys(vaddr).

Problem is that the conversion is not correct everytime. Sometimes it is, sometimes it's not. How do I know that? Because I'm reading the value on the kernel module as well and comparing to value read using fmem and using my other system.

Ex:

my kernel symbol's address is 0xffffffffb3400000, so when I do
printk(KERN_INFO "Addr: 0x%lx , Value: 0x%lx\n", _stext, *_stext) I get => Addr: 0xffffffffb3400000 , Value: 0x4801e03f51258d48.

When it reads right I use fmem and the other system to read the physical address given by __pa and the value matches 0x4801e03f51258d48 in both cases. But sometimes it doesn't work, so the value is different. And how do I know the value itself hasn't changed? Because dereferencing the virtual address still gives me the result 0x4801e03f51258d48.

I know kernel code and data changes on every boot (including kernel symbols addresses), that's not a problem since I'm getting the kernel symbol's addr everytime. But I expected the virtual to phys mapping to be the same every time, shouldn't it be? I mean, what can I do to get the physical address of my kernel symbol correctly?

So right now I have

u64 _stext_pa = __pa(_stext_va)
printk(KERN_INFO "Value of _stext (va: 0x%lx | pa: 0x%x) = 0x%lx\n", _stext_va, _stext_pa, *_stext_va)

Addresses (virtual and physical) change every boot but the value is always the same. That's what I need.

I need a physical address paddr so that I can perform int value = *paddr; on my other system and get the same result I'm getting with the virtual address

Edit: this "other system" I'm refering to is an SMM driver, but that's not relevant, just in case you might be wondering "what is 'other system'"


问:
Using multi threading to simulate 6 users logging in using Selenium
I am trying to create a function using selenium to login to a page in a different tab for each credential in a dictionary of usernames and passwords. I have 6 users so I will have 6 tabs open. I want to keep track of each tab I have open so I can navigate back to a specific tab.

This is what I have tried:

```<code>users = {'userA': 'pass',
         'userB': 'pass2',
         'userC': 'pass3',
         'userD': 'pass4',
         'userE': 'pass5',
         'userF': 'pass6',
         }
tab_names = []
count = 0
for key in users:
    try:
        element = WebDriverWait(browser, 100).until(
            EC.presence_of_element_located((By.ID, "name-field"))
            # name_input = browser.find_element(By.ID, 'name-field')
        )
        element.send_keys(key)
        browser.find_element(By.ID, 'password-field').send_keys(users[key])
        second_element = WebDriverWait(browser, 100).until(
            EC.presence_of_element_located((By.ID, 'login-button'))
        )
        second_element.click()
        sleep(3)
        browser.execute_script("window.open('https://somepage/login')")
        count+=1
        tab_names.append(str(count))
        # sleep(10)
        browser.find_element(By.ID, 'login-button').click()
    finally:
        browser.quit()
</code>```

My code is not doing what I intend, this function opens a tab, logs in with specific credentials and closes the window without opening a new tab to login with the next credential.

Body:
I am trying to create a function using selenium to login to a page in a different tab for each credential in a dictionary of usernames and passwords. I have 6 users so I will have 6 tabs open. I want to keep track of each tab I have open so I can navigate back to a specific tab.

This is what I have tried:

users = {'userA': 'pass',
         'userB': 'pass2',
         'userC': 'pass3',
         'userD': 'pass4',
         'userE': 'pass5',
         'userF': 'pass6',
         }
tab_names = []
count = 0
for key in users:
    try:
        element = WebDriverWait(browser, 100).until(
            EC.presence_of_element_located((By.ID, "name-field"))
            # name_input = browser.find_element(By.ID, 'name-field')
        )
        element.send_keys(key)
        browser.find_element(By.ID, 'password-field').send_keys(users[key])
        second_element = WebDriverWait(browser, 100).until(
            EC.presence_of_element_located((By.ID, 'login-button'))
        )
        second_element.click()
        sleep(3)
        browser.execute_script("window.open('https://somepage/login')")
        count+=1
        tab_names.append(str(count))
        # sleep(10)
        browser.find_element(By.ID, 'login-button').click()
    finally:
        browser.quit()

My code is not doing what I intend, this function opens a tab, logs in with specific credentials and closes the window without opening a new tab to login with the next credential.


问:
Error implementing settings when instantiating the AudioPlayer class / AudioLoadConfiguration
For example:
When using the AudioPlayer class together with just_audio_background, the initialization settings are ignored.
But when I use it without just_audio_background it works as expected. It looks like loading the settings together with just_audio_background is not implemented.
Has anyone ever experienced this? Or would you have a suggestion?

 final _player = AudioPlayer( audioLoadConfiguration: AudioLoadConfiguration( androidLoadControl: AndroidLoadControl( bufferForPlaybackDuration: const Duration(seconds: 10), prioritizeTimeOverSizeThresholds: true), ), );

Has anyone ever experienced this? Or would you have a suggestion?
I need to specify bufferForPlaybackDuration.


问:
Get 'Can't get attribute" error while loading my pickel file
I am trying to use pick to save and load my ML models but I get an error. Here is the simplify version of my code to save my model:

```<code>import pickle
def test(x,y):
    return x+y

filename = 'test.pkl'
pickle.dump(test, open(filename, 'wb'))
</code>```

I can load the pickle file from the same notebook that I am creating it but if I close the notebook and try to load the pick in a new one with the below code:

```<code>import pickle
filename = 'test.pkl'
loaded_model = pickle.load(open(filename, 'rb'))

It gets me this error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[2], line 2
      1 filename = 'test.pkl'
----> 2 loaded_model = pickle.load(open(filename, 'rb'))

AttributeError: Can't get attribute 'test' on <module '__main__'>
</code>```

Body:
I am trying to use pick to save and load my ML models but I get an error. Here is the simplify version of my code to save my model:

import pickle
def test(x,y):
    return x+y

filename = 'test.pkl'
pickle.dump(test, open(filename, 'wb'))

I can load the pickle file from the same notebook that I am creating it but if I close the notebook and try to load the pick in a new one with the below code:

import pickle
filename = 'test.pkl'
loaded_model = pickle.load(open(filename, 'rb'))

It gets me this error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[2], line 2
      1 filename = 'test.pkl'
----> 2 loaded_model = pickle.load(open(filename, 'rb'))

AttributeError: Can't get attribute 'test' on <module '__main__'>


问:
Python openpyxl - Is it possible to edit an Excel file with openpyxl and KEEP the charts style? (mines become white)
I'd like basically to write data in an Excel sheet, in a table, with openpyxl. For this no problem, I achieved to do it.
The issue is: when I save the file (with the openpyxl save() function), and then when I open it manually, all the charts/graphs from the other sheets (that I haven't even touched) have now a white background/style. Cf. the screenshot below:

Screenshot of the resultant chart on Excel

I've written some data in a Worksheet of my Excel file with openpyxl. Basically these data are filled in a table in an isolated sheet, and then the other sheets of my file draw graphs depending on these data.
So what I do is:

I get my data from a CSV file with a pandas DataFrame

I use openpyxl WorkBook and WorkSheet to write my data in the sheet I want, in my result XLSX file

I use the save() function of the openpyxl WorkBook to save my data

When I open manually my freshly modified XLSX file, the graphs are well updated, but have now the white background as shown before.

Does someon know if it's possible to keep the original style (originally it had a black/gray background) please?


问:
How to open/close a modal from my header component in Next.js 13?
I am building an e-commerce application with Next.js 13 for fun. I have difficulties when I try to make a Login modal that pops up when I click on a button in  component.

My approach would be make a useState in the parent, which is the rootLayout here, pass the setter to , and pass the state to the modal.

But my question is, since I will be using useState to toggle the visibility of the modal, I will need to use client component by declaring "use client". But if I use "use client" in my root layout, and use the useState hook here, will it make my whole app client component? If that's the case, then this is not ideal. How should I implement it? Is it a bad layout? Should I change it? Thanks.

This is my root layout:

```<code>import "./globals.css";
import Header from "./Header";
import LoginForm from "@components/LoginForm";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <head />
      <body className="relative">
        <Header />  <-------------------------- THIS IS THE HEADER/NAVBAR COMPONENT
        <main className="p-5">
          <div>{children}</div>
        </main>
        <LoginForm /> <------------------------ THIS IS THE LOGIN MODAL COMPONENT
      </body>
    </html>
  );
}
</code>```

Body:
I am building an e-commerce application with Next.js 13 for fun. I have difficulties when I try to make a Login modal that pops up when I click on a button in  component.

My approach would be make a useState in the parent, which is the rootLayout here, pass the setter to , and pass the state to the modal.

But my question is, since I will be using useState to toggle the visibility of the modal, I will need to use client component by declaring "use client". But if I use "use client" in my root layout, and use the useState hook here, will it make my whole app client component? If that's the case, then this is not ideal. How should I implement it? Is it a bad layout? Should I change it? Thanks.

This is my root layout:

import "./globals.css";
import Header from "./Header";
import LoginForm from "@components/LoginForm";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (

          <-------------------------- THIS IS THE HEADER/NAVBAR COMPONENT

{children}

        <LoginForm /> <------------------------ THIS IS THE LOGIN MODAL COMPONENT

  );
}


问:
Error in NormalizeData.default running DoubletFinder on a SCE to Seurat object in R
When I use the DoubletFinder function on my Seurat object, it keeps showing an error on NormalizingData default. I transformed my SingleCellExperiment object into Seurat and then split it by sample. It seems to run well until I use the function Doublet Finder.

This is the script I've used:

```<code>pk_identification <- function(seurat_object){
  sweep.res.list_seu <- paramSweep_v3(seurat_object, PCs = 1:50, sct = FALSE)
  sweep.stats_seu<- summarizeSweep(sweep.res.list_seu, GT = FALSE)
  bcmvn_seu <- find.pK(sweep.stats_seu)`

  `plot <- ggplot(bcmvn_seu, aes(pK, BCmetric, group = 1)) +
  geom_point() +
  geom_line()`

`  pk_maxBC <- bcmvn_seu %>% # select the pK that corresponds to max bcmvn to optimize doublet detection
    filter(BCmetric == max(BCmetric)) %>%
    select(pK)
  pk_maxBC <- as.numeric(as.character(pk_maxBC[[1]]))
`
`results <- list("plot" = plot, "pk"= pk_maxBC)
return(results)
`
`results <- pk_identification(splited_seu$intact_27R)`
</code>```

And this is the error I've been receiving

```<code>`[1] "Creating artificial doublets for pN = 5%"
[1] "Creating Seurat object..."
[1] "Normalizing Seurat object..."
 Error in NormalizeData.default(object = GetAssayData(object = object, :
trying to get slot "params" from an object of a basic class ("NULL") with no slots
</code>```

I'd really appreciate some help, I'm doing exactly as I've read on tutorials and courses and can't find what I'm doing wrong.

Thanks!

Body:
When I use the DoubletFinder function on my Seurat object, it keeps showing an error on NormalizingData default. I transformed my SingleCellExperiment object into Seurat and then split it by sample. It seems to run well until I use the function Doublet Finder.

This is the script I've used:

pk_identification <- function(seurat_object){
  sweep.res.list_seu <- paramSweep_v3(seurat_object, PCs = 1:50, sct = FALSE)
  sweep.stats_seu<- summarizeSweep(sweep.res.list_seu, GT = FALSE)
  bcmvn_seu <- find.pK(sweep.stats_seu)`

  `plot <- ggplot(bcmvn_seu, aes(pK, BCmetric, group = 1)) +
  geom_point() +
  geom_line()`

`  pk_maxBC <- bcmvn_seu %>% # select the pK that corresponds to max bcmvn to optimize doublet detection
    filter(BCmetric == max(BCmetric)) %>%
    select(pK)
  pk_maxBC <- as.numeric(as.character(pk_maxBC[[1]]))
`
`results <- list("plot" = plot, "pk"= pk_maxBC)
return(results)
`
`results <- pk_identification(splited_seu$intact_27R)`

And this is the error I've been receiving

`[1] "Creating artificial doublets for pN = 5%"
[1] "Creating Seurat object..."
[1] "Normalizing Seurat object..."
 Error in NormalizeData.default(object = GetAssayData(object = object, :
trying to get slot "params" from an object of a basic class ("NULL") with no slots

I'd really appreciate some help, I'm doing exactly as I've read on tutorials and courses and can't find what I'm doing wrong.

Thanks!


问:
How do I change the state of a variable from a separate component
I am trying to use React's context hook to store data that is filled out throughout different components. The data is then packaged together and sent to firebase. All of the variables states are changing as expected except for one, the exercise name.

Context

```<code>export const PrContext = createContext({});

export const PrProvider = ({children}) => {
  const [numExercises,setNumExercises] = useState(0);
  const [exercise,setExercise] = useState('Select Exercise');
  const [reps,setReps] = useState('');
  const [weight, setWeight] = useState('');
  const [notes,setNotes] = useState('default note');
  const todayDate = getCurrentDate();
  return(
    <PrContext.Provider
    value = {{
        numExercises,
        setNumExercises,
        exercise,
        setExercise,
        reps,
        setReps,
        weight,
        setWeight,
        notes,
        setNotes,
        sendPrData: async () => {
          try {
            await setDoc(doc(db,'UsersData',userInfo.user),{
              Exercise:{exercise},
              Reps:{reps},
              Weight:{weight},
            });
          }catch(e){
            console.log(e)
          }

        },

        }}
    >
    {children}
    </PrContext.Provider>
  )
}

</code>```

The screen that holds the components

```<code>const PrEnteryScreen = ({}) => {

    return(
        <View style = {{height:'100%',width:'100%',backgroundColor:'#141212'}}>

        <SafeAreaView style = {{alignItems:'center'}}>
             {/**
              * use context for pr information
              */}
                <PrProvider>
                <PopDown/>
                <RepsWeightTextInput/>
                <NotesInput/>
                <SubmitPr />
                </PrProvider>

        </SafeAreaView>
        </View>

    );
    };

export default PrEnteryScreen;
</code>```

Component whose text I want to change

```<code>if (
    Platform.OS === "android" &&
    UIManager.setLayoutAnimationEnabledExperimental
  ) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }

  const PopDown = () => {
    const value = useContext(PrContext)
    const [isOpen,setIsOpen] = useState(false)
    const [listHeight,setListHeight] = useState(0)
    const [textName,setTextName] = useState()
    //eventually want to change text based on exercise state
    const toggleOpen = ({}) => {
        setIsOpen(value => !value);
        LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
    }
   useEffect(() =>{
        setTextName(value.exercise);

    },[value.exercise])
    useEffect(() =>{
        EXERCISE_DATA.forEach(()=>{
            setListHeight(value => value+50)
        })

    },[isOpen])
    return(
        <View>
            <TouchableOpacity
                onPress = {toggleOpen}
            >
                <View
                    style={styles.buttonBackground}
                >
                    <Text style = {styles.Text}>{textName}</Text>
                </View>
            </TouchableOpacity>
            <View style = {{alignItems:'center'}}>
                <SelectExerciseModal style = {isOpen ? styles.show: styles.hidden} listHeight = {listHeight} />
            </View>
        </View>
    )
  }

  const styles = StyleSheet.create({
    hidden:{
        height:0,
    },
    show:{ backgroundColor: '#9B9A9A', width: 250 , borderRadius: 20},
    buttonBackground:{
        backgroundColor: '#9B9A9A',
        width: 335,
        borderRadius:41,
        alignItems:'center',
        marginHorizontal:25,
        height:200,
        justifyContent:'center'
    },
    Text:{
        fontWeight:'bold',
        fontSize:40,
        color:'white',
        alignItems:'center'

    }
  });
export default PopDown;

</code>```

When I change value.exercise the change is not registered in the popdown component and the text does not change.

list of options component
This component pops out of the popdown component and provides a list of exercises to choose from.

```<code>export const EXERCISE_DATA = [
    'Bench',
    'Squat',
    'Deadlift',
]

const SelectExerciseModal = ({listHeight,style}) =>{

    return(
    <View style = {[style,listHeight]}>
            <View style={{
                alignItems: 'center',
                justifyContent:'center'
            }}>
            <PrProvider>
                <FlatList

                    data={EXERCISE_DATA}
                    keyExtractor={item => item}
                   renderItem={({ item }) => <ExerciseListComponent exerciseName={item} />} />
            </PrProvider>
            </View>
    </View>

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

Exercise list component

```<code>const ExerciseListComponent = ({exerciseName}) => {
    const value = useContext(PrContext);
    useEffect(()=>{
        console.log(value.exercise)
    },[value.exercise])
    return(

    <View>

        <TouchableOpacity

            onPress={()=>{{value.setExercise(exerciseName)}}}
       >
            <Text style = {styles.text}>
                {exerciseName}
            </Text>
        </TouchableOpacity>

    </View>
    )
}
const styles = StyleSheet.create({
    text:{
    fontSize:56,
    color:'white'
    },

})
export default ExerciseListComponent;

</code>```
```<code>const SubmitPr = () => {
  const value = useContext(PrContext);
  const [Reps,SetReps] = useState('');
  const [Exercise,SetExercise] = useState('Select a Exercise');
  const [Weight, SetWeight] = useState('');
  const [email,setEmail] = useState('not working');
  const auth = useContext(AuthContext)
  const getInfo = useCallback(()=>{
    SetReps(value.reps);
    SetExercise(value.exercise);
    SetWeight(value.weight);
    setEmail(auth.user);
    console.log(props.state)
  });
  const date = getCurrentDate();

  return(
    <TouchableOpacity
      onPress={async () => {
      getInfo()
      try {
        await setDoc(doc(db,'UsersData',date),{
          Exercise:{Exercise},
          Reps:{Reps},
          Weight:{Weight},
        });
      }catch(e){
        console.log(e)
      }
    }}
    >
      <View style = {styles.submitButton}>
          <Text style = {styles.textStyle}>Submit</Text>
      </View>
    </TouchableOpacity>
  )
};
styles = StyleSheet.create({
    submitButton:{
        width:209,
        height:100,
        backgroundColor:'#9B9A9A',
        borderRadius:80,
        justifyContent:'center',
        alignItems:'center',
        marginTop:50

    },
    textStyle:{
        color:'white',
        fontSize:30,
        fontWeight:'bold'
    }
})
export default SubmitPr;
</code>```

Additional Info:
When i press one of the exercise list components it logs the new state of value.exercise through the useEffect hook but when I go to press submit the state of value.exercise is unchanged. Additionally the popdown component's text isn't changing to the new state of value.exercise.

Body:
I am trying to use React's context hook to store data that is filled out throughout different components. The data is then packaged together and sent to firebase. All of the variables states are changing as expected except for one, the exercise name.

Context

export const PrContext = createContext({});

export const PrProvider = ({children}) => {
  const [numExercises,setNumExercises] = useState(0);
  const [exercise,setExercise] = useState('Select Exercise');
  const [reps,setReps] = useState('');
  const [weight, setWeight] = useState('');
  const [notes,setNotes] = useState('default note');
  const todayDate = getCurrentDate();
  return(
    <PrContext.Provider
    value = {{
        numExercises,
        setNumExercises,
        exercise,
        setExercise,
        reps,
        setReps,
        weight,
        setWeight,
        notes,
        setNotes,
        sendPrData: async () => {
          try {
            await setDoc(doc(db,'UsersData',userInfo.user),{
              Exercise:{exercise},
              Reps:{reps},
              Weight:{weight},
            });
          }catch(e){
            console.log(e)
          }

        },

        }}
    >
    {children}
    </PrContext.Provider>
  )
}

The screen that holds the components

const PrEnteryScreen = ({}) => {

    return(
        <View style = {{height:'100%',width:'100%',backgroundColor:'#141212'}}>

        <SafeAreaView style = {{alignItems:'center'}}>
             {/**
              * use context for pr information
              */}
                <PrProvider>
                <PopDown/>
                <RepsWeightTextInput/>
                <NotesInput/>
                <SubmitPr />
                </PrProvider>

        </SafeAreaView>
        </View>

    );
    };

export default PrEnteryScreen;

Component whose text I want to change

if (
    Platform.OS === "android" &&
    UIManager.setLayoutAnimationEnabledExperimental
  ) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }

  const PopDown = () => {
    const value = useContext(PrContext)
    const [isOpen,setIsOpen] = useState(false)
    const [listHeight,setListHeight] = useState(0)
    const [textName,setTextName] = useState()
    //eventually want to change text based on exercise state
    const toggleOpen = ({}) => {
        setIsOpen(value => !value);
        LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
    }
   useEffect(() =>{
        setTextName(value.exercise);

    },[value.exercise])
    useEffect(() =>{
        EXERCISE_DATA.forEach(()=>{
            setListHeight(value => value+50)
        })

    },[isOpen])
    return(
        <View>
            <TouchableOpacity
                onPress = {toggleOpen}
            >
                <View
                    style={styles.buttonBackground}
                >
                    <Text style = {styles.Text}>{textName}</Text>
                </View>
            </TouchableOpacity>
            <View style = {{alignItems:'center'}}>
                <SelectExerciseModal style = {isOpen ? styles.show: styles.hidden} listHeight = {listHeight} />
            </View>
        </View>
    )
  }

  const styles = StyleSheet.create({
    hidden:{
        height:0,
    },
    show:{ backgroundColor: '#9B9A9A', width: 250 , borderRadius: 20},
    buttonBackground:{
        backgroundColor: '#9B9A9A',
        width: 335,
        borderRadius:41,
        alignItems:'center',
        marginHorizontal:25,
        height:200,
        justifyContent:'center'
    },
    Text:{
        fontWeight:'bold',
        fontSize:40,
        color:'white',
        alignItems:'center'

    }
  });
export default PopDown;

When I change value.exercise the change is not registered in the popdown component and the text does not change.

list of options component
This component pops out of the popdown component and provides a list of exercises to choose from.

export const EXERCISE_DATA = [
    'Bench',
    'Squat',
    'Deadlift',
]

const SelectExerciseModal = ({listHeight,style}) =>{

    return(
    <View style = {[style,listHeight]}>
            <View style={{
                alignItems: 'center',
                justifyContent:'center'
            }}>
            <PrProvider>
                <FlatList

                    data={EXERCISE_DATA}
                    keyExtractor={item => item}
                   renderItem={({ item }) => <ExerciseListComponent exerciseName={item} />} />
            </PrProvider>
            </View>
    </View>

    )
    }
export default SelectExerciseModal;

Exercise list component

const ExerciseListComponent = ({exerciseName}) => {
    const value = useContext(PrContext);
    useEffect(()=>{
        console.log(value.exercise)
    },[value.exercise])
    return(

    <View>

        <TouchableOpacity

            onPress={()=>{{value.setExercise(exerciseName)}}}
       >
            <Text style = {styles.text}>
                {exerciseName}
            </Text>
        </TouchableOpacity>

    </View>
    )
}
const styles = StyleSheet.create({
    text:{
    fontSize:56,
    color:'white'
    },

})
export default ExerciseListComponent;

const SubmitPr = () => {
  const value = useContext(PrContext);
  const [Reps,SetReps] = useState('');
  const [Exercise,SetExercise] = useState('Select a Exercise');
  const [Weight, SetWeight] = useState('');
  const [email,setEmail] = useState('not working');
  const auth = useContext(AuthContext)
  const getInfo = useCallback(()=>{
    SetReps(value.reps);
    SetExercise(value.exercise);
    SetWeight(value.weight);
    setEmail(auth.user);
    console.log(props.state)
  });
  const date = getCurrentDate();

  return(
    <TouchableOpacity
      onPress={async () => {
      getInfo()
      try {
        await setDoc(doc(db,'UsersData',date),{
          Exercise:{Exercise},
          Reps:{Reps},
          Weight:{Weight},
        });
      }catch(e){
        console.log(e)
      }
    }}
    >
      <View style = {styles.submitButton}>
          <Text style = {styles.textStyle}>Submit</Text>
      </View>
    </TouchableOpacity>
  )
};
styles = StyleSheet.create({
    submitButton:{
        width:209,
        height:100,
        backgroundColor:'#9B9A9A',
        borderRadius:80,
        justifyContent:'center',
        alignItems:'center',
        marginTop:50

    },
    textStyle:{
        color:'white',
        fontSize:30,
        fontWeight:'bold'
    }
})
export default SubmitPr;

Additional Info:
When i press one of the exercise list components it logs the new state of value.exercise through the useEffect hook but when I go to press submit the state of value.exercise is unchanged. Additionally the popdown component's text isn't changing to the new state of value.exercise.


问:
i found an html code in my /etc/apt/sources.list.d directory , exactly this file "mssql-server.list"
when i run sudo apt update i get this error message

E: Malformed line 1 in source list /etc/apt/sources.list.d/mssql-server.list (type) E: The list of sources could not be read.
and when i went to do file i found an html code

```<code><html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.18.0 (Ubuntu)</center>
</body>
</html>`
</code>```

`

recently i dont know if its related i found a directory full of screen shots and some files
i didnt have before , the name of it was cilocks

Body:
when i run sudo apt update i get this error message

E: Malformed line 1 in source list /etc/apt/sources.list.d/mssql-server.list (type) E: The list of sources could not be read.
and when i went to do file i found an html code

<title>404 Not Found</title>

404 Not Found

nginx/1.18.0 (Ubuntu)

`

`

recently i dont know if its related i found a directory full of screen shots and some files
i didnt have before , the name of it was cilocks


问:
Spring batch multithreading problem with Iterator Item Reader
I'm new to spring batch and still learning, I have batch configuration with IteratorItemReader , Custom Processor and Custom Writer as below,

```<code>@Autowired
JobBuilderFactory jobBuilderFactory;
@Autowired
StepBuilderFactory stepBuilderFactory;
@Value("${inputFile.location}")
private String inputFile;

@Bean
public Job testJob() throws IOException {
    return jobBuilderFactory.get("testJob")
                .incrementer(new RunIdIncrementer())
                .start(testStep())
                .listener(new JobListener())
                .build();
}

@Bean
public Step testStep() throws IOException {
    return stepBuilderFactory.get("testStep")
                .<File, File>chunk(1)
                .reader(testReader())
                .processor(testProcessor())
                .writer(testWriter())
                .taskExecutor(threadPoolTaskExecutor())
                .build();
}

@Bean
public ItemReader<File> testReader() throws IOException {
    List<File> files = Files.walk(Paths.get(inputFile), 1)
                    .filter(Files::isRegularFile)
                    .map(Path::toFile)
                    .collect(Collectors.toList());

        return new IteratorItemReader<>(files);
}

@Bean
public CustomProcessor testProcessor() {
    return new CustomProcessor();
}

@Bean
public CustomWriter testWriter() {
    return new CustomWriter();
}
@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(4);
    executor.setMaxPoolSize(6);
    executor.setQueueCapacity(4);
    executor.initialize();
    return executor;
}
</code>```

Here testReader() will check the given input path and list all the files into a List then it returns IteratorItemReader, and then in processor business logic is happening.

with multithreading  If there are multiple files (more than one) in the input location everything is working fine, i'm not getting any error but,

Problem Statement :   Let's say there's only one file in the input location (Ex: C:/User/documents/abc.txt), one thread will process the file completely everything is ok but in the end i'm getting this below exception,

```<code>ERROR - Encountered an error executing step testStep in job testJob
java.util.NoSuchElementException: null
at java.util.ArrayList$Itr.next(ArrayList.java:864)
at org.springframework.batch.item.support.IteratorItemReader.read  (IteratorItemReader.java:70)
at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead (SimpleChunk Provider.java:99)
at org.springframework.batch.core.step.item.SimpleChunkProvider.read (SimpleChunkProvider.java:180)
at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration (SimpleChunk Provider.java:126)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult (RepeatTemplate.java:375)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal (RepeatTemplate.java:215)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145)
at org.springframework.batch.core.step.item.SimpleChunk Provider.provide (SimpleChunkProvider.java:118)
at org.springframework.batch.core.step.item. ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:71)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction (TaskletStep.java:407)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:331)
at org.springframework.transaction.support. Transaction Template.execute(Transaction Template.java:140)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext (TaskletStep.java:273)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration (StepContextRepeatCallback.java:82)
at org.springframework.batch.repeat.support.TaskExecutorRepeatTemplate$ExecutingRunnable.run (TaskExecutorRepeatTemplate.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:750)
</code>```

This Exception is happening because of multithreading only, when i tried to look into the IteratorItemReader class line number 70 i've found this below code,

```<code>if (iterator.hasNext())
    return iterator.next();
else
    return null; // end of data
</code>```

What will be the best solution to over come this issue please provide your inputs on this,

Thanks in advance.

any suggestions would be helpful.

Body:
I'm new to spring batch and still learning, I have batch configuration with IteratorItemReader , Custom Processor and Custom Writer as below,

@Autowired
JobBuilderFactory jobBuilderFactory;
@Autowired
StepBuilderFactory stepBuilderFactory;
@Value("${inputFile.location}")
private String inputFile;

@Bean
public Job testJob() throws IOException {
    return jobBuilderFactory.get("testJob")
                .incrementer(new RunIdIncrementer())
                .start(testStep())
                .listener(new JobListener())
                .build();
}

@Bean
public Step testStep() throws IOException {
    return stepBuilderFactory.get("testStep")
                .<File, File>chunk(1)
                .reader(testReader())
                .processor(testProcessor())
                .writer(testWriter())
                .taskExecutor(threadPoolTaskExecutor())
                .build();
}

@Bean
public ItemReader<File> testReader() throws IOException {
    List<File> files = Files.walk(Paths.get(inputFile), 1)
                    .filter(Files::isRegularFile)
                    .map(Path::toFile)
                    .collect(Collectors.toList());

        return new IteratorItemReader<>(files);
}

@Bean
public CustomProcessor testProcessor() {
    return new CustomProcessor();
}

@Bean
public CustomWriter testWriter() {
    return new CustomWriter();
}
@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(4);
    executor.setMaxPoolSize(6);
    executor.setQueueCapacity(4);
    executor.initialize();
    return executor;
}

Here testReader() will check the given input path and list all the files into a List then it returns IteratorItemReader, and then in processor business logic is happening.

with multithreading  If there are multiple files (more than one) in the input location everything is working fine, i'm not getting any error but,

Problem Statement :   Let's say there's only one file in the input location (Ex: C:/User/documents/abc.txt), one thread will process the file completely everything is ok but in the end i'm getting this below exception,

ERROR - Encountered an error executing step testStep in job testJob
java.util.NoSuchElementException: null
at java.util.ArrayList$Itr.next(ArrayList.java:864)
at org.springframework.batch.item.support.IteratorItemReader.read  (IteratorItemReader.java:70)
at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead (SimpleChunk Provider.java:99)
at org.springframework.batch.core.step.item.SimpleChunkProvider.read (SimpleChunkProvider.java:180)
at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration (SimpleChunk Provider.java:126)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult (RepeatTemplate.java:375)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal (RepeatTemplate.java:215)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145)
at org.springframework.batch.core.step.item.SimpleChunk Provider.provide (SimpleChunkProvider.java:118)
at org.springframework.batch.core.step.item. ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:71)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction (TaskletStep.java:407)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:331)
at org.springframework.transaction.support. Transaction Template.execute(Transaction Template.java:140)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext (TaskletStep.java:273)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration (StepContextRepeatCallback.java:82)
at org.springframework.batch.repeat.support.TaskExecutorRepeatTemplate$ExecutingRunnable.run (TaskExecutorRepeatTemplate.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:750)

This Exception is happening because of multithreading only, when i tried to look into the IteratorItemReader class line number 70 i've found this below code,

if (iterator.hasNext())
    return iterator.next();
else
    return null; // end of data

What will be the best solution to over come this issue please provide your inputs on this,

Thanks in advance.

any suggestions would be helpful.


问:
Why doesn't input box shrink in width since we've fr as width for column

HI,

In above picture, as we can see, the input box doesn't shrink in width, even though the column is a grid with fr as widths of column, what is the exact meaning of fr and why doesn't the label shrink as well?


问:
Sharp install failed for Strapi in Windows 11 64x
I am trying to install sharp module in my Strapi project. Of course, I tried to follow several solutions to fix this.

Can't install sharp on windows 10 (x64)
https://github.com/lovell/sharp/issues/3086

But I could not fix it. Could you help me?

npm ERR! code 1
npm ERR! path E:\exercise\eqhq\server\node_modules\sharp
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)
npm ERR! info sharp Using cached C:\Users\Administrator\AppData\Local\npm-cache_libvips\libvips-8.10.0-win32-x64.tar.br
npm ERR! info sharp Creating E:\exercise\eqhq\server\node_modules\sharp\build\Release

npm ERR! info sharp Copying DLLs from E:\exercise\eqhq\server\node_modules\sharp\vendor\8.10.0\lib to E:\exercise\eqhq\server\node_modules\sharp\build\Release
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.0.0
npm ERR! gyp info using node@16.16.0 | win32 | x64
npm ERR! gyp info find Python using Python version 3.11.1 found at "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\python.exe"
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS msvs_version not set from command line or npm config
npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
npm ERR! gyp ERR! find VS could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details
npm ERR! gyp ERR! find VS looking for Visual Studio 2015
npm ERR! gyp ERR! find VS - not found
npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8

npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS **************************************************************

npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio
npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload.
npm ERR! gyp ERR! find VS For more information consult the documentation at:
npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
npm ERR! gyp ERR! find VS **************************************************************

npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use

npm ERR! gyp ERR! stack     at VisualStudioFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:122:47)
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:75:16
npm ERR! gyp ERR! stack     at VisualStudioFinder.findVisualStudio2013 (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:363:14)
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:71:14
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:384:16
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
npm ERR! gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
npm ERR! gyp ERR! stack     at ChildProcess.exithandler (node:child_process:406:5)

npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:527:28)
npm ERR! gyp ERR! stack     at maybeClose (node:internal/child_process:1092:16)
npm ERR! gyp ERR! System Windows_NT 10.0.22621
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd E:\exercise\eqhq\server\node_modules\sharp
npm ERR! gyp ERR! node -v v16.16.0
npm ERR! gyp ERR! node-gyp -v v9.0.0
npm ERR! gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Administrator\AppData\Local\npm-cache_logs\2023-01-10T18_53_26_318Z-debug-0.log


问:
Why does all my values become zero before being able to save them in the onplayerRemoved
I tried everything i found but nothing seems to0 be working, here is my script

```<code>local DataStoreService = game:GetService('DataStoreService')
local playerData = DataStoreService:GetDataStore('PlayerData')

local datatobesaved

local function load(player: Player)
    local leaderstats = Instance.new('Folder')
    leaderstats.Name = 'leaderstats'
    leaderstats.Parent = player

    local LuckSauceIn = Instance.new('StringValue')
    LuckSauceIn.Name = 'LuckSauce'
    LuckSauceIn.Parent = leaderstats
    LuckSauceIn.Value = "0"

    local LuckSauce = Instance.new('NumberValue')
    LuckSauce.Name = 'LuckSauceInt'
    LuckSauce.Parent = player

    local LuckUppgradeCost = Instance.new('NumberValue')
    LuckUppgradeCost.Name = 'LuckUppgradeCost'
    LuckUppgradeCost.Parent = player
    LuckUppgradeCost.Value = 1000

    local luckMultiplier = Instance.new('NumberValue')
    luckMultiplier.Name = 'LuckMultiplier'
    luckMultiplier.Parent = player

    local autoClicksGamePass = Instance.new('BoolValue')
    autoClicksGamePass.Name = 'autoClicksGamePassOwned'
    autoClicksGamePass.Parent = player
    autoClicksGamePass.Value = false

    local instantClicksGamePass = Instance.new('BoolValue')
    instantClicksGamePass.Name = 'instantClicksGamePassOwned'
    instantClicksGamePass.Parent = player
    instantClicksGamePass.Value = false

    local doubleLuckGamePass = Instance.new('BoolValue')
    doubleLuckGamePass.Name = 'doubleLuckGamePassOwned'
    doubleLuckGamePass.Parent = player
    doubleLuckGamePass.Value = false

    local PlayerUserId = 'Player_'..player.UserId

    local data = playerData:GetAsync(PlayerUserId)

    if data then
        print(data['LuckSauce'].." valuenow")

        player.LuckSauceInt.Value = data['LuckSauce']
    else
        print("no data")
        player.LuckSauceInt.Value = 0
    end
end

local function save(player: Player)

    print(player.LuckSauceInt.Value.." Money")

    datatobesaved = {
        LuckSauce = player.LuckSauceInt.Value
    }

    local playerid = 'Player_'..player.UserId

    local success, err = pcall(function()
        playerData:SetAsync(playerid, datatobesaved)
    end)

    if success then
        print("data saved!")
    else
        print("data failed to save!")
    end
end

game:BindToClose(function()
    for i, plr in pairs(game.Players:GetPlayers()) do
        save(plr)
    end
end)

game.Players.PlayerAdded:Connect(function(player: Player)
    load(player)
end)

game.Players.PlayerRemoving:Connect(function(player: Player)
    print(player.leaderstats.LuckSauce.Value.." Money before")
    save(player)
end)
</code>```

i tried hard coding in wat the data should be by making it 5, so now it always loads as 5 so that works but the saving is the problem

Ive tried all the things people recomended on other posts but nothing works also i dont have it anywhere else that removes them either, i want the values to not become zero right before trying to save

Body:
I tried everything i found but nothing seems to0 be working, here is my script

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

local datatobesaved

local function load(player: Player)
    local leaderstats = Instance.new('Folder')
    leaderstats.Name = 'leaderstats'
    leaderstats.Parent = player

    local LuckSauceIn = Instance.new('StringValue')
    LuckSauceIn.Name = 'LuckSauce'
    LuckSauceIn.Parent = leaderstats
    LuckSauceIn.Value = "0"

    local LuckSauce = Instance.new('NumberValue')
    LuckSauce.Name = 'LuckSauceInt'
    LuckSauce.Parent = player

    local LuckUppgradeCost = Instance.new('NumberValue')
    LuckUppgradeCost.Name = 'LuckUppgradeCost'
    LuckUppgradeCost.Parent = player
    LuckUppgradeCost.Value = 1000

    local luckMultiplier = Instance.new('NumberValue')
    luckMultiplier.Name = 'LuckMultiplier'
    luckMultiplier.Parent = player

    local autoClicksGamePass = Instance.new('BoolValue')
    autoClicksGamePass.Name = 'autoClicksGamePassOwned'
    autoClicksGamePass.Parent = player
    autoClicksGamePass.Value = false

    local instantClicksGamePass = Instance.new('BoolValue')
    instantClicksGamePass.Name = 'instantClicksGamePassOwned'
    instantClicksGamePass.Parent = player
    instantClicksGamePass.Value = false

    local doubleLuckGamePass = Instance.new('BoolValue')
    doubleLuckGamePass.Name = 'doubleLuckGamePassOwned'
    doubleLuckGamePass.Parent = player
    doubleLuckGamePass.Value = false

    local PlayerUserId = 'Player_'..player.UserId

    local data = playerData:GetAsync(PlayerUserId)

    if data then
        print(data['LuckSauce'].." valuenow")

        player.LuckSauceInt.Value = data['LuckSauce']
    else
        print("no data")
        player.LuckSauceInt.Value = 0
    end
end

local function save(player: Player)

    print(player.LuckSauceInt.Value.." Money")

    datatobesaved = {
        LuckSauce = player.LuckSauceInt.Value
    }

    local playerid = 'Player_'..player.UserId

    local success, err = pcall(function()
        playerData:SetAsync(playerid, datatobesaved)
    end)

    if success then
        print("data saved!")
    else
        print("data failed to save!")
    end
end

game:BindToClose(function()
    for i, plr in pairs(game.Players:GetPlayers()) do
        save(plr)
    end
end)

game.Players.PlayerAdded:Connect(function(player: Player)
    load(player)
end)

game.Players.PlayerRemoving:Connect(function(player: Player)
    print(player.leaderstats.LuckSauce.Value.." Money before")
    save(player)
end)

i tried hard coding in wat the data should be by making it 5, so now it always loads as 5 so that works but the saving is the problem

Ive tried all the things people recomended on other posts but nothing works also i dont have it anywhere else that removes them either, i want the values to not become zero right before trying to save


问:
Problems with using @mongodb-js/charts-embed-dom to embed a chart from MongoDB
METHOD 1
I am trying to embed a chart from MongoDB using the following code, which was adapted from documentation from MongoDB and NPM.

```<code><script src="https://unpkg.com/@mongodb-js/charts-embed-dom"></script>

<script>
  const ChartsEmbedSDK = window.ChartsEmbedSDK;

  const sdk = new ChartsEmbedSDK({
     baseUrl: "https://charts.mongodb.com/charts-webscraping-ciaso-ercot-wnjhz",
     });

  const chart = sdk.createChart({
      chartId: "62d7224c-79ab-41ca-83f6-690f4ab86869",
     });

  chart.render(document.getElementById('chart'));

</script>
</body>
</code>```

The error I’m getting is “TypeError t is null”

a picture of the error

Near as I can tell that might mean that whatever is supposed to be imported from https://unpkg.com/@mongodb-js/charts-embed-dom is not coming through so the sdk and the chart aren’t getting created properly. Hence why the chart comes up null when it trys to getElementById.

METHOD 2
I also tried a different method. What you see below is directly copied from Mongo’s documentation. I got an error that “relative references must begin with /, ./, or ../”.

```<code> <script type=module> /*did that to avoid error cannot import outside a module*/

      import ChartsEmbedSDK from "@mongodb-js/charts-embed-dom"; //error: relative references must begin with /, ./, or ../

      //import ChartsEmbedSDK from "https://unpkg.com/@mongodb-js/charts-embed-dom" // Ambiguous indirect export: default

      // import ChartsEmbedSDK from "/unpkg.com/@mongodb-js/charts-embed-dom" //error not found.

     //import 'https://unpkg.com/@mongodb-js/charts-embed-dom';  // TypeError: t is null (same as other method)

      const sdk = new ChartsEmbedSDK({
        baseUrl: "https://charts.mongodb.com/charts-webscraping-ciaso-ercot-wnjhz",
     });

      const chart = sdk.createChart({
        chartId: "62d7224c-79ab-41ca-83f6-690f4ab86869",
        height: "700px",
        // Additional options go here
      });

      chart.render(document.getElementById("chart"));
   </script>
</code>```

You can see I also tried a few other things (commented out).

I think that for method 2 a possible reason it’s not working is that I wasn’t able to install the @mongodb-js/charts-embed-dom package correctly. When I tried to install using npm this is what I saw:
screenshot of error with npm

I did some looking into this problem but was never able to resolve it.

Overall it seems like I'm not able to properly import the charts-embed-dom. It seems to me like method 1 only has one problem to fix, whereas method 2 has possibly 2 or more layers of problems, so I’m hoping there is a relatively simple solution to method 1.

I know another solution would be to use an iframe. I've gotten that to work, but it just doesn't seem to be versatile enough to do what I need (drop down boxes, dynamic filtering)

Body:
METHOD 1
I am trying to embed a chart from MongoDB using the following code, which was adapted from documentation from MongoDB and NPM.

The error I’m getting is “TypeError t is null”

a picture of the error

Near as I can tell that might mean that whatever is supposed to be imported from https://unpkg.com/@mongodb-js/charts-embed-dom is not coming through so the sdk and the chart aren’t getting created properly. Hence why the chart comes up null when it trys to getElementById.

METHOD 2
I also tried a different method. What you see below is directly copied from Mongo’s documentation. I got an error that “relative references must begin with /, ./, or ../”.

You can see I also tried a few other things (commented out).

I think that for method 2 a possible reason it’s not working is that I wasn’t able to install the @mongodb-js/charts-embed-dom package correctly. When I tried to install using npm this is what I saw:
screenshot of error with npm

I did some looking into this problem but was never able to resolve it.

Overall it seems like I'm not able to properly import the charts-embed-dom. It seems to me like method 1 only has one problem to fix, whereas method 2 has possibly 2 or more layers of problems, so I’m hoping there is a relatively simple solution to method 1.

I know another solution would be to use an iframe. I've gotten that to work, but it just doesn't seem to be versatile enough to do what I need (drop down boxes, dynamic filtering)


问:
Replit - Bad system call (core dumped)
Assembly code:

```<code>section .text

global _start

_start:
  mov eax, 4
  mov ebx, 1
  mov ecx, message
  mov edx, message_len
  int 0x80

section .data
  message db "Hello, World!", 0x0a
  message_len equ $-message
</code>```

compiling code:

```<code>rm Lab.o
rm lab
nasm -f elf -F dwarf -g Lab.asm
ld -m elf_i386 -o lab Lab.o
</code>```

This is a basic Hello World program (called Lab.asm.)

When I compile the code and run it I get the following error:
Bad system call (core dumped).

I can't seem to find the core dump to do gdb debugging, and I've tried compiling it in different ways. Any ideas what is going wrong here?

Title: Replit - Bad system call (core dumped)

Body:
Assembly code:

section .text

global _start

_start:
  mov eax, 4
  mov ebx, 1
  mov ecx, message
  mov edx, message_len
  int 0x80

section .data
  message db "Hello, World!", 0x0a
  message_len equ $-message

compiling code:

rm Lab.o
rm lab
nasm -f elf -F dwarf -g Lab.asm
ld -m elf_i386 -o lab Lab.o

This is a basic Hello World program (called Lab.asm.)

When I compile the code and run it I get the following error:
Bad system call (core dumped).

I can't seem to find the core dump to do gdb debugging, and I've tried compiling it in different ways. Any ideas what is going wrong here?


问:
How do I setup different font styles using apple's typography guidelines for different screen sizes on React Native
I want to change font sizes depending on breakpoints globally through redux, what is the standard way to scale typography for different screen sizes for mobile apps.

Can someone please guide me whether this is font sizes changed in accessibility settings or these are guidelines for setting font sizes for different screen sizes ie: small, medium, etc

and if yes then what exactly what is the screen size of small device and which screen sizes are defined in small. I need a standard for all break points(screen sizes)
enter image description here

I have tried scaled metrics and changing font Sizes using the dimensions library in react native but my CTO is saying that it doesn't scale properly according to apple's guidelines

I used scaled metrics and changing font Sizes using the dimensions library in react native but it doesn't scale properly according to apple's guidelines.