问:
Conan Cross-build from Linux:x86_64 to Linux:armv7hf test_package build fails
I have a C++ library packaged with conan and it contains a test_package with a conanfile.py that uses the new conan 2.0 self.requries(self.tested_reference_str) and test_type = "explicit".

When not cross-building everything runs fine. I can build the library using conan build . and build and run the consumer test_package.

In case of cross-building, the main library can be built without issues. However, the build of the test_package fails with:

```<code>----Running------
> . "/work/tests/test_package/build/generators/conanbuild.sh" && cmake -G "Unix Makefiles" -DCMAKE_TOOLCHAIN_FILE="/work/tests/test_package/build/generators/conan_toolchain.cmake" -DCMAKE_POLICY_DEFAULT_CMP0091="NEW" -DCMAKE_BUILD_TYPE="Release" "/work/tests/test_package/."
-----------------
-- Using Conan toolchain: /work/tests/test_package/build/generators/conan_toolchain.cmake
-- The CXX compiler identification is GNU 11.3.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - failed
-- Check for working CXX compiler: /opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++
-- Check for working CXX compiler: /opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++ - broken
CMake Error at /opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/share/cmake-3.22/Modules/CMakeTestCXXCompiler.cmake:62 (message):
  The C++ compiler

    "/opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++"

  is not able to compile a simple test program.

  It fails with the following output:

    Change Dir: /work/tests/test_package/build/Release/CMakeFiles/CMakeTmp

    Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_8ea64/fast && /usr/bin/gmake  -f CMakeFiles/cmTC_8ea64.dir/build.make CMakeFiles/cmTC_8ea64.dir/build
    gmake[1]: Entering directory '/work/tests/test_package/build/Release/CMakeFiles/CMakeTmp'
    Building CXX object CMakeFiles/cmTC_8ea64.dir/testCXXCompiler.cxx.o
    /opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++   -O2 -pipe -g -feliminate-unused-debug-types    -stdlib=libstdc++  -o CMakeFiles/cmTC_8ea64.dir/testCXXCompiler.cxx.o -c /work/tests/test_package/build/Release/CMakeFiles/CMakeTmp/testCXXCompiler.cxx
    arm-poky-linux-gnueabi-g++: error: unrecognized command-line option ‘-stdlib=libstdc++’
    gmake[1]: *** [CMakeFiles/cmTC_8ea64.dir/build.make:78: CMakeFiles/cmTC_8ea64.dir/testCXXCompiler.cxx.o] Error 1
    gmake[1]: Leaving directory '/work/tests/test_package/build/Release/CMakeFiles/CMakeTmp'
    gmake: *** [Makefile:127: cmTC_8ea64/fast] Error 2

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:2 (project)
</code>```

host profile:

```<code>[settings]
os=Linux
arch=armv7hf
compiler=clang
compiler.version=14
# Tried also with libc++
compiler.libcxx=libstdc++11
build_type=Release
</code>```

build profile:

```<code>[settings]
os=Linux
arch=x86_64
compiler=gcc
compiler.version=11
# Without the following the error becomes:
# arm-poky-linux-gnueabi-g++: error: unrecognized command-line option ‘-stdlib=libc++’
compiler.libcxx=libstdc++11
build_type=Release

[env]
CC=gcc-11
CXX=g++-11
</code>```

Any idea why cross compiling works for the library itself but the test_package fails?

Edit: I looked into conaninfo.txt, CMakeCache.txt, for both: the library generated files and the test_package generated files. Conan specifies the clang compiler in both cases (library build and test_package) but CMake uses anyway the GNU compiler for the test_package. It seems the CMAKE_CXX_COMPILER is not passed correctly to CMake in case of the test_package. A conan install inside the test_package folder also results in the wrong compiler (GNU) being used.

Body:
I have a C++ library packaged with conan and it contains a test_package with a conanfile.py that uses the new conan 2.0 self.requries(self.tested_reference_str) and test_type = "explicit".

When not cross-building everything runs fine. I can build the library using conan build . and build and run the consumer test_package.

In case of cross-building, the main library can be built without issues. However, the build of the test_package fails with:

----Running------
> . "/work/tests/test_package/build/generators/conanbuild.sh" && cmake -G "Unix Makefiles" -DCMAKE_TOOLCHAIN_FILE="/work/tests/test_package/build/generators/conan_toolchain.cmake" -DCMAKE_POLICY_DEFAULT_CMP0091="NEW" -DCMAKE_BUILD_TYPE="Release" "/work/tests/test_package/."
-----------------
-- Using Conan toolchain: /work/tests/test_package/build/generators/conan_toolchain.cmake
-- The CXX compiler identification is GNU 11.3.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - failed
-- Check for working CXX compiler: /opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++
-- Check for working CXX compiler: /opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++ - broken
CMake Error at /opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/share/cmake-3.22/Modules/CMakeTestCXXCompiler.cmake:62 (message):
  The C++ compiler

    "/opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++"

  is not able to compile a simple test program.

  It fails with the following output:

    Change Dir: /work/tests/test_package/build/Release/CMakeFiles/CMakeTmp

    Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_8ea64/fast && /usr/bin/gmake  -f CMakeFiles/cmTC_8ea64.dir/build.make CMakeFiles/cmTC_8ea64.dir/build
    gmake[1]: Entering directory '/work/tests/test_package/build/Release/CMakeFiles/CMakeTmp'
    Building CXX object CMakeFiles/cmTC_8ea64.dir/testCXXCompiler.cxx.o
    /opt/poky/4.0.5/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++   -O2 -pipe -g -feliminate-unused-debug-types    -stdlib=libstdc++  -o CMakeFiles/cmTC_8ea64.dir/testCXXCompiler.cxx.o -c /work/tests/test_package/build/Release/CMakeFiles/CMakeTmp/testCXXCompiler.cxx
    arm-poky-linux-gnueabi-g++: error: unrecognized command-line option ‘-stdlib=libstdc++’
    gmake[1]: *** [CMakeFiles/cmTC_8ea64.dir/build.make:78: CMakeFiles/cmTC_8ea64.dir/testCXXCompiler.cxx.o] Error 1
    gmake[1]: Leaving directory '/work/tests/test_package/build/Release/CMakeFiles/CMakeTmp'
    gmake: *** [Makefile:127: cmTC_8ea64/fast] Error 2

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:2 (project)

host profile:

[settings]
os=Linux
arch=armv7hf
compiler=clang
compiler.version=14
# Tried also with libc++
compiler.libcxx=libstdc++11
build_type=Release

build profile:

[settings]
os=Linux
arch=x86_64
compiler=gcc
compiler.version=11
# Without the following the error becomes:
# arm-poky-linux-gnueabi-g++: error: unrecognized command-line option ‘-stdlib=libc++’
compiler.libcxx=libstdc++11
build_type=Release

[env]
CC=gcc-11
CXX=g++-11

Any idea why cross compiling works for the library itself but the test_package fails?

Edit: I looked into conaninfo.txt, CMakeCache.txt, for both: the library generated files and the test_package generated files. Conan specifies the clang compiler in both cases (library build and test_package) but CMake uses anyway the GNU compiler for the test_package. It seems the CMAKE_CXX_COMPILER is not passed correctly to CMake in case of the test_package. A conan install inside the test_package folder also results in the wrong compiler (GNU) being used.


来源: stackexchange

问:
How to get corner plots from a MCMC parameters
I have a MCMC results and trying to plot with corner.py I only obtain one plot instead of three. I have one parameter that I want to plot but I don't know what's happening.

I used my data results (gamma) as follows:

```<code>figure = corner.corner(nh, labels=[r"$\Gamma$", r"$\Gamma$"],
                       quantiles=[0.16, 0.5, 0.84], show_titles=True, title_kwargs={"fontsize": 12},)
#corner.corner(gamma*2, fig=figure, color='red')
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a MCMC results and trying to plot with corner.py I only obtain one plot instead of three. I have one parameter that I want to plot but I don't know what's happening.

I used my data results (gamma) as follows:

figure = corner.corner(nh, labels=[r"$\Gamma$", r"$\Gamma$"],
                       quantiles=[0.16, 0.5, 0.84], show_titles=True, title_kwargs={"fontsize": 12},)
#corner.corner(gamma*2, fig=figure, color='red')
plt.show()


问:
Coingecko API data is not appending neatly to a pandas dataframe using ticker/date variables
I am pulling twitter user data to measure the accuracy of their tweets.

I've got the dataset in a pandas df and i want to coingecko api to pull the ticker and date so it can append the 'Tweet Price' date so i can do further data processing.

The problem is that the sentiment pulls neatly, but the price does not.

This is the CoinGecko bit which i suspect i have messed up. I was expecting this to pull from the ticker and date variable and then call the requests to enrich the data:

```<code># Set the endpoint URL
url = "https://api.coingecko.com/api/v3/coins/{ticker}/history?date={date}"

# Loop through each row in the DataFrame
for index, row in df.iterrows():
    ticker = row['Query']
    date = row['Date Only']

    # Set the request headers
    headers = {
        "accept": "application/json"
    }

    # Use the API to fetch the price of the cryptocurrency on the date of the tweet
    response = requests.get(url.format(ticker=ticker, date=date), headers=headers)
    data = response.json()

    # Check if the data object has a "prices" key
    if "prices" in data:
        # Get the first item in the prices list
        first_item = data["prices"][0]

        # Get the price from the first item
        price = first_item[1]

        # Add the price to the DataFrame
        df.loc[index, 'Tweet Price'] = price

print(df)
</code>```

And here is how the df looks (had to split up date and time):

```<code># Convert tweets to dataframe
df = pd.DataFrame(tweets, columns=['Date', 'User', 'Tweet', 'URL', 'Query'])

# Convert the Date column to a datetime object
df['Date'] = pd.to_datetime(df['Date'])

# Create a new column called "Date Only" that contains only the date part of the datetime object
df['Date Only'] = df['Date'].dt.strftime('%Y-%m-%d')

# Create a new column called "Time Only" that contains only the time part of the datetime object
df['Time Only'] = df['Date'].dt.strftime('%H:%M:%S')
</code>```

Body:
I am pulling twitter user data to measure the accuracy of their tweets.

I've got the dataset in a pandas df and i want to coingecko api to pull the ticker and date so it can append the 'Tweet Price' date so i can do further data processing.

The problem is that the sentiment pulls neatly, but the price does not.

This is the CoinGecko bit which i suspect i have messed up. I was expecting this to pull from the ticker and date variable and then call the requests to enrich the data:

# Set the endpoint URL
url = "https://api.coingecko.com/api/v3/coins/{ticker}/history?date={date}"

# Loop through each row in the DataFrame
for index, row in df.iterrows():
    ticker = row['Query']
    date = row['Date Only']

    # Set the request headers
    headers = {
        "accept": "application/json"
    }

    # Use the API to fetch the price of the cryptocurrency on the date of the tweet
    response = requests.get(url.format(ticker=ticker, date=date), headers=headers)
    data = response.json()

    # Check if the data object has a "prices" key
    if "prices" in data:
        # Get the first item in the prices list
        first_item = data["prices"][0]

        # Get the price from the first item
        price = first_item[1]

        # Add the price to the DataFrame
        df.loc[index, 'Tweet Price'] = price

print(df)

And here is how the df looks (had to split up date and time):

# Convert tweets to dataframe
df = pd.DataFrame(tweets, columns=['Date', 'User', 'Tweet', 'URL', 'Query'])

# Convert the Date column to a datetime object
df['Date'] = pd.to_datetime(df['Date'])

# Create a new column called "Date Only" that contains only the date part of the datetime object
df['Date Only'] = df['Date'].dt.strftime('%Y-%m-%d')

# Create a new column called "Time Only" that contains only the time part of the datetime object
df['Time Only'] = df['Date'].dt.strftime('%H:%M:%S')


问:
Specify multiple provisioning profile for expo local credentials
Expo EAS has a way to use local credentials

The problem is that I have 2 environments: production and development, and 2 provision profile accordingly. Unfortunatly I can't find a way how to define 2 different provision profiles in credentials.json.

```<code>{
  "android": {
    "keystore": {
      "keystorePath": "android/keystores/release.keystore",
      "keystorePassword": "paofohlooZ9e",
      "keyAlias": "keyalias",
      "keyPassword": "aew1Geuthoev"
    }
  },
  "ios": {
    "provisioningProfilePath": "ios/certs/profile.mobileprovision",
    "distributionCertificate": {
      "path": "ios/certs/dist-cert.p12",
      "password": "iex3shi9Lohl"
    }
  }
}
</code>```

The only field we have here is provisioningProfilePath.
When I'm trying to build internal distribution with a production profile, of course, I'm getting the error: You must use an adhoc provisioning profile (target 'TARGET NAME)' for internal distribution any solution?

Any suggestions?

Body:
Expo EAS has a way to use local credentials

The problem is that I have 2 environments: production and development, and 2 provision profile accordingly. Unfortunatly I can't find a way how to define 2 different provision profiles in credentials.json.

{
  "android": {
    "keystore": {
      "keystorePath": "android/keystores/release.keystore",
      "keystorePassword": "paofohlooZ9e",
      "keyAlias": "keyalias",
      "keyPassword": "aew1Geuthoev"
    }
  },
  "ios": {
    "provisioningProfilePath": "ios/certs/profile.mobileprovision",
    "distributionCertificate": {
      "path": "ios/certs/dist-cert.p12",
      "password": "iex3shi9Lohl"
    }
  }
}

The only field we have here is provisioningProfilePath.
When I'm trying to build internal distribution with a production profile, of course, I'm getting the error: You must use an adhoc provisioning profile (target 'TARGET NAME)' for internal distribution any solution?

Any suggestions?


问:
MSAL Node / Electron - PublicClientApplication.acquireTokenByCode() accessing Tokens despite clearing accounts
I'm trying to clear all access Tokens from Main.Ts in an Electron App without success.

On the Node side of the App, I have a login function that implements the Auth Code Flow with PKCE  - which works fine:

```<code>let login = async () => {
  try {
    const authResult = await getTokenInteractive(authCodeUrlParams);
    mainWindow.webContents.send(IpcMessages.XXX-XXXX, authResult);
  } catch (error) {
    console.log(error);
  }
};
</code>```
```<code>let getTokenInteractive = async (

tokenRequest: AuthorizationUrlRequest

): Promise\<AuthenticationResult\> =\> {

try {

     ...
     // Generate PKCE Challenge and Verifier before request
        const cryptoProvider = new CryptoProvider();
        const { challenge, verifier } = await cryptoProvider.generatePkceCodes();

     ...
     // Get Auth Code URL
    const authCodeUrl = await clientApplication.getAuthCodeUrl(
      localAuthCodeUrlParams
    );
    const authCode = await listenForAuthCode(authCodeUrl, authWindow);

    ...

// This works fine
const authResult: AuthenticationResult =
await clientApplication.acquireTokenByCode({
...authCodeRequest,
code: authCode,
codeVerifier: verifier,
});

    return authResult;

} catch (error) {

    throw error;

}
};
</code>```

The logout function also clears the accounts:

```<code>    const logout = async () =\> {
         try {
   console.log("LOGOUT RECEIVED");
const accounts: AccountInfo\[\] = await clientApplication
.getTokenCache()
.getAllAccounts();
if (accounts && accounts.length \> 0) console.log(accounts);
await clientApplication.getTokenCache().removeAccount(accounts\[0\]);

     // Test to see if accounts are cleared returns '[]'
    const checkAccounts: AccountInfo[] = await clientApplication
      .getTokenCache()
      .getAllAccounts();

    console.log(checkAccounts);
    mainWindow.webContents.send(IpcMessages.USER_LOGGED_OUT);

} catch (err) {
console.log("Error in main.logout ", err);
}
};
</code>```

Unfortunately, acquireTokenByCode still accesses the Token (?? How) when the user is redirected to a login page.

ps I've also checked local storage, Cookies etc in the browser and they are never populated (ie always remain empty).

I've seen numerous answers suggesting using a logout URL:

https://learn.microsoft.com/en-us/answers/questions/263335/msal-sign-out-does-not-appear-to-clear-cache.html

https://learn.microsoft.com/en-us/answers/questions/994601/logout-does-not-clear-session.html

However, these solutions down't work with Azure B2C. Also, redirecting using the logout endpoint using Electron.shell(openExternal([url])) also does nothing.

It's unbelievable that MS hasn't implemented a simple logout solution.

Question: Does anyone know how to stop tokens from being acquired WITHOUT having to open a native browser window or populate the Browser Window with a "Successfully signed out. You can now close this window" prompt ?

Thanks in advance.

Body:
I'm trying to clear all access Tokens from Main.Ts in an Electron App without success.

On the Node side of the App, I have a login function that implements the Auth Code Flow with PKCE  - which works fine:

let login = async () => {
  try {
    const authResult = await getTokenInteractive(authCodeUrlParams);
    mainWindow.webContents.send(IpcMessages.XXX-XXXX, authResult);
  } catch (error) {
    console.log(error);
  }
};

let getTokenInteractive = async (

tokenRequest: AuthorizationUrlRequest

): Promise\<AuthenticationResult\> =\> {

try {

     ...
     // Generate PKCE Challenge and Verifier before request
        const cryptoProvider = new CryptoProvider();
        const { challenge, verifier } = await cryptoProvider.generatePkceCodes();

     ...
     // Get Auth Code URL
    const authCodeUrl = await clientApplication.getAuthCodeUrl(
      localAuthCodeUrlParams
    );
    const authCode = await listenForAuthCode(authCodeUrl, authWindow);

    ...

// This works fine
const authResult: AuthenticationResult =
await clientApplication.acquireTokenByCode({
...authCodeRequest,
code: authCode,
codeVerifier: verifier,
});

    return authResult;

} catch (error) {

    throw error;

}
};

The logout function also clears the accounts:

    const logout = async () =\> {
         try {
   console.log("LOGOUT RECEIVED");
const accounts: AccountInfo\[\] = await clientApplication
.getTokenCache()
.getAllAccounts();
if (accounts && accounts.length \> 0) console.log(accounts);
await clientApplication.getTokenCache().removeAccount(accounts\[0\]);

     // Test to see if accounts are cleared returns '[]'
    const checkAccounts: AccountInfo[] = await clientApplication
      .getTokenCache()
      .getAllAccounts();

    console.log(checkAccounts);
    mainWindow.webContents.send(IpcMessages.USER_LOGGED_OUT);

} catch (err) {
console.log("Error in main.logout ", err);
}
};

Unfortunately, acquireTokenByCode still accesses the Token (?? How) when the user is redirected to a login page.

ps I've also checked local storage, Cookies etc in the browser and they are never populated (ie always remain empty).

I've seen numerous answers suggesting using a logout URL:

https://learn.microsoft.com/en-us/answers/questions/263335/msal-sign-out-does-not-appear-to-clear-cache.html

https://learn.microsoft.com/en-us/answers/questions/994601/logout-does-not-clear-session.html

However, these solutions down't work with Azure B2C. Also, redirecting using the logout endpoint using Electron.shell(openExternal([url])) also does nothing.

It's unbelievable that MS hasn't implemented a simple logout solution.

Question: Does anyone know how to stop tokens from being acquired WITHOUT having to open a native browser window or populate the Browser Window with a "Successfully signed out. You can now close this window" prompt ?

Thanks in advance.


问:
python sounddevice play mono 1-ch wav file back on specific output channel of sound card
I am trying to have a python sounddevice script that will use a 1-ch audio wav file and to play back on a specific output channel of my sound card (for example ch3 only).  I wasn't sure exactly how to do that with the mapping arg for sounddevice.play().  My objective is to play the mono audio file back on the 3rd channel only.</p>
```<code>import sounddevice as sd
import soundfile as sf

ch_map = [0,0,1]
data,fs = sf.read("mono_audio_file.wav")
sd.play(data,mapping=ch_map,device=myDevice)
</code>```

Body:
I am trying to have a python sounddevice script that will use a 1-ch audio wav file and to play back on a specific output channel of my sound card (for example ch3 only).  I wasn't sure exactly how to do that with the mapping arg for sounddevice.play().  My objective is to play the mono audio file back on the 3rd channel only.

import sounddevice as sd
import soundfile as sf

ch_map = [0,0,1]
data,fs = sf.read("mono_audio_file.wav")
sd.play(data,mapping=ch_map,device=myDevice)


问:
Java.lang.NoSuchMethodError: org.apache.spark.sql.internal.SQLConf$.LEGACY_AVRO_REBASE_MODE_IN_WRITE()
I'm trying to insert data into a redshift using PySpark 3.2.2

I'm using the following packages:

```<code>io.github.spark-redshift-community:spark-redshift_2.12:5.0.3
Scala 2.12.
com.amazonaws:aws-java-sdk-bundle:1.11.375
org.apache.hadoop:hadoop-aws:3.2.0
com.google.guava:guava:23.0
</code>```

To insert the data, the codes looks like the following:

```<code>insert.write.format("io.github.spark_redshift_community.spark.redshift").options(
    url=f"jdbc:redshift://{HOST_REDSHIFT}:{PORT_REDSHIFT}/{DATABASE_REDSHIFT}",
    dbtable="table",
    user=USER_REDSHIFT,
    password=PASSWORD_REDSHIFT,
    tempdir=f"s3a://{S3_BUCKET}/test_folder",
    forward_spark_s3_credentials="true"
).mode("append").save()
</code>```

But I'm getting the error:

```<code>java.lang.NoSuchMethodError: org.apache.spark.sql.internal.SQLConf$.LEGACY_AVRO_REBASE_MODE_IN_WRITE()Lorg/apache/spark/internal/config/ConfigEntry
</code>```

I also added the spark-avro jar to my jars path, but didn't worked.

Could someone help me, please?

Body:
I'm trying to insert data into a redshift using PySpark 3.2.2

I'm using the following packages:

io.github.spark-redshift-community:spark-redshift_2.12:5.0.3
Scala 2.12.
com.amazonaws:aws-java-sdk-bundle:1.11.375
org.apache.hadoop:hadoop-aws:3.2.0
com.google.guava:guava:23.0

To insert the data, the codes looks like the following:

insert.write.format("io.github.spark_redshift_community.spark.redshift").options(
    url=f"jdbc:redshift://{HOST_REDSHIFT}:{PORT_REDSHIFT}/{DATABASE_REDSHIFT}",
    dbtable="table",
    user=USER_REDSHIFT,
    password=PASSWORD_REDSHIFT,
    tempdir=f"s3a://{S3_BUCKET}/test_folder",
    forward_spark_s3_credentials="true"
).mode("append").save()

But I'm getting the error:

java.lang.NoSuchMethodError: org.apache.spark.sql.internal.SQLConf$.LEGACY_AVRO_REBASE_MODE_IN_WRITE()Lorg/apache/spark/internal/config/ConfigEntry

I also added the spark-avro jar to my jars path, but didn't worked.

Could someone help me, please?


问:
Is there any way to fix the runtime error caused by module not found error "yaml" not found error in the serverless lambda in python flask application
START RequestId: "841a14f8-cee0-42df-9b5a-be25caba07" Version: $LATEST
[ERROR] Runtime.ImportModuleError: Unable to import module 'handler.handler': No module named 'yaml' Traceback (most recent call last):
END RequestId: 841a14f8-cee0-42df-9b5a-b5caf2ba07

here is the error we are seeing in the cloudwatch.

and we tried other solutions to edit on the cloud9 to add the library in server os but we deployed lambda directly with docker.
`

```<code>serverless.yml
</code>```

service: test-service

plugins:

serverless-python-requirements
serverless-pseudo-parameters

custom:
pythonRequirements:
zip: true

provider:
default_stage: test
default_region: ap-southeast-2
role:

python3.9

package:
include:

'pyyaml'
exclude:
requirements.txt
`

```<code>i included the pyyaml in this file but after deploying still im getting the yaml not found error. can anyone help me with this? thanks
</code>```

Body:
START RequestId: "841a14f8-cee0-42df-9b5a-be25caba07" Version: $LATEST
[ERROR] Runtime.ImportModuleError: Unable to import module 'handler.handler': No module named 'yaml' Traceback (most recent call last):
END RequestId: 841a14f8-cee0-42df-9b5a-b5caf2ba07

here is the error we are seeing in the cloudwatch.

and we tried other solutions to edit on the cloud9 to add the library in server os but we deployed lambda directly with docker.
`

serverless.yml

service: test-service

plugins:

serverless-python-requirements
serverless-pseudo-parameters

custom:
pythonRequirements:
zip: true

provider:
default_stage: test
default_region: ap-southeast-2
role:

python3.9

package:
include:

'pyyaml'
exclude:
requirements.txt
`

i included the pyyaml in this file but after deploying still im getting the yaml not found error. can anyone help me with this? thanks


问:
Unable to make 'spring legacy project' in Eclipse
I use M2 macbook air, and Eclipse Version: 2022-09 (4.25.0)

I plug in 'spring 3' at Eclipse IDE and create 'Spring Legacy Project' and its template was 'Spring MVC Project'. but "Marketplace solutions available" alert comes up again n again, even i install maven2Nature.Marketplace solutions available alert

enter image description here
I checked every plugin install correctly. try reinstall, reboot, project clean and so on.
please let me know how to do.


问:
How to get position in RecyclerViewAdapter for ViewPager when offscreenPageLimit is activated
How to get the current position within the Fragment or Adapter file while offscreenPageLimit is activated for all elements?

I have a viewpager2 and RecyclerView adapter for it. So I need to change the state in variable if the lastPosition is shown. But since I am using offscreenPageLimit, all elements created at once and my state is changing at the same time when pager is created...

Any suggestions..
Thank youu!!!

I tried to get position in onBindViewHolder, but since all elements are made automatically in the first launch, my state variable is changed from the first moment viewpager is created, while i need to change it if it is last page in viewpager2


问:
How can I filter database objects by date, based on the selected day on react calendar?
My Code fetches objects from a Mongodb collection called workoutLog, and currently displays all of them in a table. I'm able to filter them by date, but only if I hardcode the date. My page also has a React Calendar that currently displays the selected date in the table onChange. I want to filter the workouts based on this selected date.

```<code>//const for fetching and displaying workouts
//• adds bullet point
const Workout = (props) => (
  <tr>
    <td>•   {props.workout.name}<td classname='setText'> - <i>{props.workout.sets}</i> sets of <i>{props.workout.reps}</i> reps</td></td>
  </tr>
);
</code>```

As you can see I'm filtering by a hardcoded date over here, it works.

```<code>export default function Profile() {
  const [date, setDate] = useState(new Date());
  const [workouts, setWorkouts] = useState([]);

//fetch workouts
  useEffect(() => {
    async function getWorkouts(){
      const response = await fetch('http://localhost:5000/workouts/');

      if (!response.ok){
        const message = `An error occured: ${response.statusText}`;
        window.alert(message);
        return;
      }

      const workouts = await response.json();
      const filtered  = workouts.filter((e) => e.date ==="2022-11-19")
      console.log(date.toISOString().slice(0, 10));
      setWorkouts(filtered);
    }

    getWorkouts();

    return
  }, [workouts.length]);
</code>```
```<code>//this method will display the workouts
  function displayWorkout(){
    return workouts.map((workout) => {
      return (
        <Workout
          workout={workout}
        />
      );
    });
  }
</code>```
```<code>return (
    <div class="container">
      <div class="Calendar">
        <Calendar
          onChange={setDate}
          value={date}
          />
      </div>
      <div class="Journal"><table>
            <tr>
              <th>{date.toISOString().slice(0, 10)} Journal</th>
            </tr>
            <tr>
              <th>Food Eaten <Link to='/nutrition' className="linkPlus">+</Link></th>
            </tr>
            <div className="tableScroll">
              {displayMeals()}
            </div>

            <tr>
              <th>Exercises Completed <Link to='/fitness' className="linkPlus">+</Link></th>
            </tr>
            <div className="tableScroll">
              {displayWorkout()}
            </div>

            <tr>
              <th>Weight Today</th>
            </tr>
          </table></div>
      <div class="Avatar"><img src='https://mir-s3-cdn-cf.behance.net/project_modules/disp/96be2232163929.567197ac6fb64.png'/></div>
      <div class="Name">{displayName()}</div>
    </div>
  );
}
</code>```

I'm not sure how I should be storing the date, either directly from the Calendar onChange or from the displayed date in the table and then utilising it within my getWorkouts function in order to filter.

Body:
My Code fetches objects from a Mongodb collection called workoutLog, and currently displays all of them in a table. I'm able to filter them by date, but only if I hardcode the date. My page also has a React Calendar that currently displays the selected date in the table onChange. I want to filter the workouts based on this selected date.

//const for fetching and displaying workouts
//• adds bullet point
const Workout = (props) => (

    •   {props.workout.name} - {props.workout.sets} sets of {props.workout.reps} reps

);

As you can see I'm filtering by a hardcoded date over here, it works.

export default function Profile() {
  const [date, setDate] = useState(new Date());
  const [workouts, setWorkouts] = useState([]);

//fetch workouts
  useEffect(() => {
    async function getWorkouts(){
      const response = await fetch('http://localhost:5000/workouts/');

      if (!response.ok){
        const message = `An error occured: ${response.statusText}`;
        window.alert(message);
        return;
      }

      const workouts = await response.json();
      const filtered  = workouts.filter((e) => e.date ==="2022-11-19")
      console.log(date.toISOString().slice(0, 10));
      setWorkouts(filtered);
    }

    getWorkouts();

    return
  }, [workouts.length]);

//this method will display the workouts
  function displayWorkout(){
    return workouts.map((workout) => {
      return (
        <Workout
          workout={workout}
        />
      );
    });
  }

return (

        <Calendar
          onChange={setDate}
          value={date}
          />

              {date.toISOString().slice(0, 10)} Journal

              Food Eaten <Link to='/nutrition' className="linkPlus">+</Link>

              {displayMeals()}

              Exercises Completed <Link to='/fitness' className="linkPlus">+</Link>

              {displayWorkout()}

              Weight Today

{displayName()}

  );
}

I'm not sure how I should be storing the date, either directly from the Calendar onChange or from the displayed date in the table and then utilising it within my getWorkouts function in order to filter.


问:
Batch operation in AWS SSM putParameter. Is there an option to write parameters in bulk to ParameterStore in AWS?
Is there an option to write parameters in bulk to ParameterStore in AWS? I have tried the putParameter API, but from the documentation I can see that only one parameter can be updated at a time. This operation takes around 20 milliseconds ( I maybe wrong ), so if I need to update some 20 parameters, it will exceed 400 ms. Typically, I have a requirement to accommodate for up to 50 parameters. Is there a better way to handle updating of parameters in parameter store?</p>


问:
How to overlay Google Play app page on the top of my app?
I want to show Google play app page on the top of my app but cannot find a way. Google play app linking page does not say anything about it. Linking to Google Play.

I have not found anything like this on Google Play Core library.
Few suggested me, it is just a custom bottom sheet.

But check the images below.

Image 1 : Google app on Android showing BBC app's google play page on the top of GOOGLE app.

Image 2: Facebook in app ad shows advertiser's Google Play page after clicking the ad.

How can I implement it ?


问:
1093 You can't specify target table 'ProgressStepsAcademicPeriod' for update in FROM clause when updating same table used with multiple subqueries
I need to check a table and determine if there is not a value greater than 0 where the academic period Id's are the same.  If there is no value greater than 0, I want to update the isActive column in the common set of academic period Ids where the Progress Step Id is 1

For Example:

In the table below, I have 8 steps for each academic period. I need to check where there are no active steps for an academic period (as is the case for academic period 1) and set the isActive to 1 for the ProgressStepId of 1 as seen in the example for the Academic Period 2

Id
isActive
ProgressStepId
AcademicPeriodId

1
0
1
1

2
0
2
1

3
0
3
1

4
0
4
1

5
0
5
1

6
0
6
1

7
0
7
1

8
0
8
1

9
1
1
2

10
0
2
2

11
0
3
2

12
0
4
2

13
0
5
2

14
0
6
2

15
0
7
2

16
0
8
2

I have the following script where the sub select queries work, but when combined with the update statement, I receive the 1093 You can't specify target table 'ProgressStepsAcademicPeriod' for update in FROM clause

```<code>UPDATE ProgressStepsAcademicPeriod SET isActive = 1 WHERE
ProgressStepId = 1 IN

(SELECT DISTINCT ProgressStepId
FROM ProgressStepsAcademicPeriod
WHERE AcademicPeriodId IN
(SELECT AcademicPeriodId
FROM ProgressStepsAcademicPeriod
GROUP BY AcademicPeriodId
HAVING (count(case when isActive = 1 then 1 end) = 0))
    ORDER BY ProgressStepId)
</code>```

Body:
I need to check a table and determine if there is not a value greater than 0 where the academic period Id's are the same.  If there is no value greater than 0, I want to update the isActive column in the common set of academic period Ids where the Progress Step Id is 1

For Example:

In the table below, I have 8 steps for each academic period. I need to check where there are no active steps for an academic period (as is the case for academic period 1) and set the isActive to 1 for the ProgressStepId of 1 as seen in the example for the Academic Period 2

Id
isActive
ProgressStepId
AcademicPeriodId

1
0
1
1

2
0
2
1

3
0
3
1

4
0
4
1

5
0
5
1

6
0
6
1

7
0
7
1

8
0
8
1

9
1
1
2

10
0
2
2

11
0
3
2

12
0
4
2

13
0
5
2

14
0
6
2

15
0
7
2

16
0
8
2

I have the following script where the sub select queries work, but when combined with the update statement, I receive the 1093 You can't specify target table 'ProgressStepsAcademicPeriod' for update in FROM clause

UPDATE ProgressStepsAcademicPeriod SET isActive = 1 WHERE
ProgressStepId = 1 IN

(SELECT DISTINCT ProgressStepId
FROM ProgressStepsAcademicPeriod
WHERE AcademicPeriodId IN
(SELECT AcademicPeriodId
FROM ProgressStepsAcademicPeriod
GROUP BY AcademicPeriodId
HAVING (count(case when isActive = 1 then 1 end) = 0))
    ORDER BY ProgressStepId)


问:
Can I remove a line from my VScode terminal?
So whenever I output something this always shows up in the terminal before my output does. Is it possible to remove it? IT seems rather disorganized to me which is why I want to clear it, output occurs its just that the text below is output before it too.

```<code>PS C:\Users\587user\Desktop\Python PBL> & C:/Users/587user/AppData/Local/Microsoft/WindowsApps/python3.11.exe "c:/Users/587user/Desktop/Desktop/Python PBL/main.py"
</code>```

I haven't been able to find anything online about it maybe I am asking for the wrong thing.

Body:
So whenever I output something this always shows up in the terminal before my output does. Is it possible to remove it? IT seems rather disorganized to me which is why I want to clear it, output occurs its just that the text below is output before it too.

PS C:\Users\587user\Desktop\Python PBL> & C:/Users/587user/AppData/Local/Microsoft/WindowsApps/python3.11.exe "c:/Users/587user/Desktop/Desktop/Python PBL/main.py"

I haven't been able to find anything online about it maybe I am asking for the wrong thing.


问:
Why Are My Hinge Joints Being Pushed Away?(Unity 2D)
Hey guys so I'm making a 2d Stickman ragdoll and I'm trying to get one of the arms to look at the mouse and the arm looks at the mouse but when the mouse gets to close the arms start glitching uncontrollably and the joints are now off set. How can I fix?

upper arm

lower arm

When I move the mouse, this happens

```<code>public GameObject LeftArm;
public GameObject LeftElbow;
 Vector2 mousepos = Input.mousePosition;
    mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 direction = new Vector2(mousepos.x - LeftArm.transform.position.x, mousepos.y - LeftArm.transform.position.y);
    LeftArm.transform.right = direction;
    LeftElbow.transform.right = direction;
</code>```

Body:
Hey guys so I'm making a 2d Stickman ragdoll and I'm trying to get one of the arms to look at the mouse and the arm looks at the mouse but when the mouse gets to close the arms start glitching uncontrollably and the joints are now off set. How can I fix?

upper arm

lower arm

When I move the mouse, this happens

public GameObject LeftArm;
public GameObject LeftElbow;
 Vector2 mousepos = Input.mousePosition;
    mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 direction = new Vector2(mousepos.x - LeftArm.transform.position.x, mousepos.y - LeftArm.transform.position.y);
    LeftArm.transform.right = direction;
    LeftElbow.transform.right = direction;


问:
 cannot appear as a child of
 -- How to find the exact location in my code
I know how to fix this error in the code. However I cant seem to find where its coming from.

I looked everywhere in EmployeeProfile and main. Though I cant seem to find it.

I also tried this in the console document.querySelectorAll('ul tr') in chrome. Through it returned nothing

```<code>react-dom.development.js:88 Warning: validateDOMNesting(...): <tr> cannot appear as a child of <ul>.
in tr (created by main)
in ul (created by main)
in div (created by main)
in div (created by main)
in div (created by main)
in div (created by main)
in main (created by EmployeeProfile)
in div (created by EmployeeProfile)
in div (created by EmployeeProfile)
in div (created by EmployeeProfile)
in div (created by EmployeeProfile)
in div (created by EmployeeProfile)
in EmployeeProfile (created by Connect(EmployeeProfile))
in Connect(EmployeeProfile) (created by Context.Consumer)
in Route (created by subscriptionroute)
in Switch (created by subscriptionroute)
in subscriptionroute (created by Context.Consumer)
in Route (created by DefaultLayout)
in div (created by DefaultLayout)
in div (created by DefaultLayout)
in DefaultLayout (created by Context.Consumer)
in withRouter(DefaultLayout) (created by Connect(withRouter(DefaultLayout)))
in Connect(withRouter(DefaultLayout)) (created by Context.Consumer)
in Route (created by AuthRoute)
in AuthRoute (created by Connect(AuthRoute))
in Connect(AuthRoute) (created by App)
in Switch (created by App)
in Provider (created by App)
in App (created by Context.Consumer)
in withRouter(App) (created by Connect(withRouter(App)))
in Connect(withRouter(App)) (created by Context.Consumer)
in Route (created by MainApp)
in Switch (created by MainApp)
in Router (created by BrowserRouter)
in BrowserRouter (created by MainApp)
in MainApp
in Provider
</code>```

I am also getting this error that I am having trouble finding and fixing. I think I may have found the location, though entering a key does not fix the issue, so I am thinking maybe its not the right spot?

I basically just need help on how to locate the offending line of code. Is there some js I can use to find it? Such as document.querySelectorAll('ul tr')?

Title: <tr> cannot appear as a child of <ul> -- How to find the exact location in my code

Body:
I know how to fix this error in the code. However I cant seem to find where its coming from.

I looked everywhere in EmployeeProfile and main. Though I cant seem to find it.

I also tried this in the console document.querySelectorAll('ul tr') in chrome. Through it returned nothing

react-dom.development.js:88 Warning: validateDOMNesting(...):
 cannot appear as a child of
.
in tr (created by main)
in ul (created by main)
in div (created by main)
in div (created by main)
in div (created by main)
in div (created by main)
in main (created by EmployeeProfile)
in div (created by EmployeeProfile)
in div (created by EmployeeProfile)
in div (created by EmployeeProfile)
in div (created by EmployeeProfile)
in div (created by EmployeeProfile)
in EmployeeProfile (created by Connect(EmployeeProfile))
in Connect(EmployeeProfile) (created by Context.Consumer)
in Route (created by subscriptionroute)
in Switch (created by subscriptionroute)
in subscriptionroute (created by Context.Consumer)
in Route (created by DefaultLayout)
in div (created by DefaultLayout)
in div (created by DefaultLayout)
in DefaultLayout (created by Context.Consumer)
in withRouter(DefaultLayout) (created by Connect(withRouter(DefaultLayout)))
in Connect(withRouter(DefaultLayout)) (created by Context.Consumer)
in Route (created by AuthRoute)
in AuthRoute (created by Connect(AuthRoute))
in Connect(AuthRoute) (created by App)
in Switch (created by App)
in Provider (created by App)
in App (created by Context.Consumer)
in withRouter(App) (created by Connect(withRouter(App)))
in Connect(withRouter(App)) (created by Context.Consumer)
in Route (created by MainApp)
in Switch (created by MainApp)
in Router (created by BrowserRouter)
in BrowserRouter (created by MainApp)
in MainApp
in Provider

I am also getting this error that I am having trouble finding and fixing. I think I may have found the location, though entering a key does not fix the issue, so I am thinking maybe its not the right spot?

I basically just need help on how to locate the offending line of code. Is there some js I can use to find it? Such as document.querySelectorAll('ul tr')?


问:
Grafana alert provisioning issue
I'd like to be able to provision alerts, and try to follow this instructions, but no luck!

OS Grafana version: 9.2.0 Running in Kubernetes

Steps that I take:

Created a new alert rule from UI.

Extract alert rule from API:
curl -k https://<my-grafana-url>/api/v1/provisioning/alert-rules/-4pMuQFVk -u admin:<my-admin-password>

It returns the following:

```<code>---
id: 18
uid: "-4pMuQFVk"
orgID: 1
folderUID: 3i72aQKVk
ruleGroup: cpu_alert_group
title: my_cpu_alert
condition: B
data:
- refId: A
  queryType: ''
  relativeTimeRange:
    from: 600
    to: 0
  datasourceUid: _SaubQF4k
  model:
    editorMode: code
    expr: system_cpu_usage
    hide: false
    intervalMs: 1000
    legendFormat: __auto
    maxDataPoints: 43200
    range: true
    refId: A
- refId: B
  queryType: ''
  relativeTimeRange:
    from: 0
    to: 0
  datasourceUid: "-100"
  model:
    conditions:
    - evaluator:
        params:
        - 3
        type: gt
      operator:
        type: and
      query:
        params:
        - A
      reducer:
        params: []
        type: last
      type: query
    datasource:
      type: __expr__
      uid: "-100"
    expression: A
    hide: false
    intervalMs: 1000
    maxDataPoints: 43200
    refId: B
    type: classic_conditions
updated: '2022-12-07T20:01:47Z'
noDataState: NoData
execErrState: Error
for: 5m

</code>```

Deleted the alert rule from UI.

Made a configmap from above alert-rule, as such:

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: grafana-alerting
data:
  alerting.yaml: |-
    apiVersion: 1
    groups:
      - id: 18
        uid: "-4pMuQFVk"
        orgID: 1
        folderUID: 3i72aQKVk
        ruleGroup: cpu_alert_group
        title: my_cpu_alert
        condition: B
        data:
        - refId: A
          queryType: ''
          relativeTimeRange:
            from: 600
            to: 0
          datasourceUid: _SaubQF4k
          model:
            editorMode: code
            expr: system_cpu_usage
            hide: false
            intervalMs: 1000
            legendFormat: __auto
            maxDataPoints: 43200
            range: true
            refId: A
        - refId: B
          queryType: ''
          relativeTimeRange:
            from: 0
            to: 0
          datasourceUid: "-100"
          model:
            conditions:
            - evaluator:
                params:
                - 3
                type: gt
              operator:
                type: and
              query:
                params:
                - A
              reducer:
                params: []
                type: last
              type: query
            datasource:
              type: __expr__
              uid: "-100"
            expression: A
            hide: false
            intervalMs: 1000
            maxDataPoints: 43200
            refId: B
            type: classic_conditions
        updated: '2022-12-07T20:01:47Z'
        noDataState: NoData
        execErrState: Error
        for: 5m

</code>```

I mount above configmap in grafana container (in /etc/grafna/provisioning/alerting).
The full manifest of the deployment is as follow:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "2"
    meta.helm.sh/release-name: grafana
    meta.helm.sh/release-namespace: monitoring
  creationTimestamp: "2022-12-08T18:31:30Z"
  generation: 4
  labels:
    app.kubernetes.io/instance: grafana
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: grafana
    app.kubernetes.io/version: 9.3.0
    helm.sh/chart: grafana-6.46.1
  name: grafana
  namespace: monitoring
  resourceVersion: "648617"
  uid: dc06b802-5281-4f31-a2b2-fef3cf53a70b
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app.kubernetes.io/instance: grafana
      app.kubernetes.io/name: grafana
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      annotations:
        checksum/config: 98cac51656714db48a116d3109994ee48c401b138bc8459540e1a497f994d197
        checksum/dashboards-json-config: 01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b
        checksum/sc-dashboard-provider-config: 01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b
        checksum/secret: 203f0e4d883461bdd41fe68515fc47f679722dc2fdda49b584209d1d288a5f07
      creationTimestamp: null
      labels:
        app.kubernetes.io/instance: grafana
        app.kubernetes.io/name: grafana
    spec:
      automountServiceAccountToken: true
      containers:
      - env:
        - name: GF_SECURITY_ADMIN_USER
          valueFrom:
            secretKeyRef:
              key: admin-user
              name: grafana
        - name: GF_SECURITY_ADMIN_PASSWORD
          valueFrom:
            secretKeyRef:
              key: admin-password
              name: grafana
        - name: GF_PATHS_DATA
          value: /var/lib/grafana/
        - name: GF_PATHS_LOGS
          value: /var/log/grafana
        - name: GF_PATHS_PLUGINS
          value: /var/lib/grafana/plugins
        - name: GF_PATHS_PROVISIONING
          value: /etc/grafana/provisioning
        image: grafana/grafana:9.3.0
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 10
          httpGet:
            path: /api/health
            port: 3000
            scheme: HTTP
          initialDelaySeconds: 60
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 30
        name: grafana
        ports:
        - containerPort: 3000
          name: grafana
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /api/health
            port: 3000
            scheme: HTTP
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /etc/grafana/grafana.ini
          name: config
          subPath: grafana.ini
        - mountPath: /etc/grafana/provisioning/alerting
          name: grafana-alerting
        - mountPath: /var/lib/grafana
          name: storage
      dnsPolicy: ClusterFirst
      enableServiceLinks: true
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext:
        fsGroup: 472
        runAsGroup: 472
        runAsUser: 472
      serviceAccount: grafana
      serviceAccountName: grafana
      terminationGracePeriodSeconds: 30
      volumes:
      - configMap:
          defaultMode: 420
          name: grafana-alerting
        name: grafana-alerting
      - configMap:
          defaultMode: 420
          name: grafana
        name: config
      - emptyDir: {}
        name: storage
</code>```

However, grafana fail to start with this error:

Failed to start grafana. error: failure to map file alerting.yaml: failure parsing rules: rule group has no name set

I fixed above error by adding Group Name, but similar errors about other missing elements kept showing up again and again (to the point that I stopped chasing, as I couldn't figure out what exactly the correct schema is). Digging in, it looks like the format/schema returned from API in step 2, is different than the schema that's pointed out in the documentation.

Why is the schema of the alert-rule returned from API different? Am I supposed to convert it, and if so how? Otherwise, what am I doing wrong?

Edit: Replaced Statefulset with deployment, since I was able to reproduce this in a normal/minimal Grafana deployment too.

Title: Grafana alert provisioning issue

Body:
I'd like to be able to provision alerts, and try to follow this instructions, but no luck!

OS Grafana version: 9.2.0 Running in Kubernetes

Steps that I take:

Created a new alert rule from UI.

Extract alert rule from API:
curl -k https://<my-grafana-url>/api/v1/provisioning/alert-rules/-4pMuQFVk -u admin:<my-admin-password>

It returns the following:

---
id: 18
uid: "-4pMuQFVk"
orgID: 1
folderUID: 3i72aQKVk
ruleGroup: cpu_alert_group
title: my_cpu_alert
condition: B
data:
- refId: A
  queryType: ''
  relativeTimeRange:
    from: 600
    to: 0
  datasourceUid: _SaubQF4k
  model:
    editorMode: code
    expr: system_cpu_usage
    hide: false
    intervalMs: 1000
    legendFormat: __auto
    maxDataPoints: 43200
    range: true
    refId: A
- refId: B
  queryType: ''
  relativeTimeRange:
    from: 0
    to: 0
  datasourceUid: "-100"
  model:
    conditions:
    - evaluator:
        params:
        - 3
        type: gt
      operator:
        type: and
      query:
        params:
        - A
      reducer:
        params: []
        type: last
      type: query
    datasource:
      type: __expr__
      uid: "-100"
    expression: A
    hide: false
    intervalMs: 1000
    maxDataPoints: 43200
    refId: B
    type: classic_conditions
updated: '2022-12-07T20:01:47Z'
noDataState: NoData
execErrState: Error
for: 5m

Deleted the alert rule from UI.

Made a configmap from above alert-rule, as such:

apiVersion: v1
kind: ConfigMap
metadata:
  name: grafana-alerting
data:
  alerting.yaml: |-
    apiVersion: 1
    groups:
      - id: 18
        uid: "-4pMuQFVk"
        orgID: 1
        folderUID: 3i72aQKVk
        ruleGroup: cpu_alert_group
        title: my_cpu_alert
        condition: B
        data:
        - refId: A
          queryType: ''
          relativeTimeRange:
            from: 600
            to: 0
          datasourceUid: _SaubQF4k
          model:
            editorMode: code
            expr: system_cpu_usage
            hide: false
            intervalMs: 1000
            legendFormat: __auto
            maxDataPoints: 43200
            range: true
            refId: A
        - refId: B
          queryType: ''
          relativeTimeRange:
            from: 0
            to: 0
          datasourceUid: "-100"
          model:
            conditions:
            - evaluator:
                params:
                - 3
                type: gt
              operator:
                type: and
              query:
                params:
                - A
              reducer:
                params: []
                type: last
              type: query
            datasource:
              type: __expr__
              uid: "-100"
            expression: A
            hide: false
            intervalMs: 1000
            maxDataPoints: 43200
            refId: B
            type: classic_conditions
        updated: '2022-12-07T20:01:47Z'
        noDataState: NoData
        execErrState: Error
        for: 5m

I mount above configmap in grafana container (in /etc/grafna/provisioning/alerting).
The full manifest of the deployment is as follow:

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "2"
    meta.helm.sh/release-name: grafana
    meta.helm.sh/release-namespace: monitoring
  creationTimestamp: "2022-12-08T18:31:30Z"
  generation: 4
  labels:
    app.kubernetes.io/instance: grafana
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: grafana
    app.kubernetes.io/version: 9.3.0
    helm.sh/chart: grafana-6.46.1
  name: grafana
  namespace: monitoring
  resourceVersion: "648617"
  uid: dc06b802-5281-4f31-a2b2-fef3cf53a70b
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app.kubernetes.io/instance: grafana
      app.kubernetes.io/name: grafana
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      annotations:
        checksum/config: 98cac51656714db48a116d3109994ee48c401b138bc8459540e1a497f994d197
        checksum/dashboards-json-config: 01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b
        checksum/sc-dashboard-provider-config: 01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b
        checksum/secret: 203f0e4d883461bdd41fe68515fc47f679722dc2fdda49b584209d1d288a5f07
      creationTimestamp: null
      labels:
        app.kubernetes.io/instance: grafana
        app.kubernetes.io/name: grafana
    spec:
      automountServiceAccountToken: true
      containers:
      - env:
        - name: GF_SECURITY_ADMIN_USER
          valueFrom:
            secretKeyRef:
              key: admin-user
              name: grafana
        - name: GF_SECURITY_ADMIN_PASSWORD
          valueFrom:
            secretKeyRef:
              key: admin-password
              name: grafana
        - name: GF_PATHS_DATA
          value: /var/lib/grafana/
        - name: GF_PATHS_LOGS
          value: /var/log/grafana
        - name: GF_PATHS_PLUGINS
          value: /var/lib/grafana/plugins
        - name: GF_PATHS_PROVISIONING
          value: /etc/grafana/provisioning
        image: grafana/grafana:9.3.0
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 10
          httpGet:
            path: /api/health
            port: 3000
            scheme: HTTP
          initialDelaySeconds: 60
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 30
        name: grafana
        ports:
        - containerPort: 3000
          name: grafana
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /api/health
            port: 3000
            scheme: HTTP
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /etc/grafana/grafana.ini
          name: config
          subPath: grafana.ini
        - mountPath: /etc/grafana/provisioning/alerting
          name: grafana-alerting
        - mountPath: /var/lib/grafana
          name: storage
      dnsPolicy: ClusterFirst
      enableServiceLinks: true
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext:
        fsGroup: 472
        runAsGroup: 472
        runAsUser: 472
      serviceAccount: grafana
      serviceAccountName: grafana
      terminationGracePeriodSeconds: 30
      volumes:
      - configMap:
          defaultMode: 420
          name: grafana-alerting
        name: grafana-alerting
      - configMap:
          defaultMode: 420
          name: grafana
        name: config
      - emptyDir: {}
        name: storage

However, grafana fail to start with this error:

Failed to start grafana. error: failure to map file alerting.yaml: failure parsing rules: rule group has no name set

I fixed above error by adding Group Name, but similar errors about other missing elements kept showing up again and again (to the point that I stopped chasing, as I couldn't figure out what exactly the correct schema is). Digging in, it looks like the format/schema returned from API in step 2, is different than the schema that's pointed out in the documentation.

Why is the schema of the alert-rule returned from API different? Am I supposed to convert it, and if so how? Otherwise, what am I doing wrong?

Edit: Replaced Statefulset with deployment, since I was able to reproduce this in a normal/minimal Grafana deployment too.


问:
Electron require() is not defined - Electron version > 12 - NodeIntegration change
To begin, I would just like to thank you for taking the time to read this post. I would also like to mention that I took the time to read and try to understand most of the exchanges that are made on the subject. Example here : I also took the time to read the "Ultimate Electron Guide" created by reZach at [https://www.debugandrelease.com/the-ultimate-electron-guide/].  I understand the theory behind "electron main process access to require, and anytime our renderer process needs to use require, marshal a request to the main process." ... I took the time to analyze several code examples, I took the time to read the tutorial on preload script here https://www.electronjs.org/docs/latest/tutorial/tutorial-preload but despite all that, I can't adjust an extremely simple code.

Here is my problem, very simple though, but I'm too stupid to find the solution ;). I had no problem to run this code with an Electron versions below v12, but since the adjustment of the security of the nodeintegration, I can't do it anymore. So basically,

in my main.js I create a "browserwindow", standard, with nothing spécial

```<code>  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: false,
    }
  });
</code>```

in my html file, I simply have this line

```<code><script src="js/client.js"></script>
</code>```

in my client.js I have

```<code>let net;
net = require('net');
this.soc = new net.Socket();
</code>```

How to make so that the module "net" is imported ? ... I know it should be simple though, but I tried a lot of things with a preload.js, a renderer.js, but no way i'm able to make this simple code work without the error "Electron require() is not defined". Someone would be kind enough to help me ? Everything works fine with versions below 12, but I want to adjust to new versions of Electron

Body:
To begin, I would just like to thank you for taking the time to read this post. I would also like to mention that I took the time to read and try to understand most of the exchanges that are made on the subject. Example here : I also took the time to read the "Ultimate Electron Guide" created by reZach at [https://www.debugandrelease.com/the-ultimate-electron-guide/].  I understand the theory behind "electron main process access to require, and anytime our renderer process needs to use require, marshal a request to the main process." ... I took the time to analyze several code examples, I took the time to read the tutorial on preload script here https://www.electronjs.org/docs/latest/tutorial/tutorial-preload but despite all that, I can't adjust an extremely simple code.

Here is my problem, very simple though, but I'm too stupid to find the solution ;). I had no problem to run this code with an Electron versions below v12, but since the adjustment of the security of the nodeintegration, I can't do it anymore. So basically,

in my main.js I create a "browserwindow", standard, with nothing spécial

  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: false,
    }
  });

in my html file, I simply have this line

in my client.js I have

let net;
net = require('net');
this.soc = new net.Socket();

How to make so that the module "net" is imported ? ... I know it should be simple though, but I tried a lot of things with a preload.js, a renderer.js, but no way i'm able to make this simple code work without the error "Electron require() is not defined". Someone would be kind enough to help me ? Everything works fine with versions below 12, but I want to adjust to new versions of Electron


问:
How to make a request to a URL with gRPC Transcoding Syntax with a standard POST request?
I am attempting to use the endpoint https://firestore.googleapis.com/v1/{parent=projects/*}/databases with more data needed per the  documentation on Google's docs.

The goal is to be able to make this request with a standard http utility such as cURL.

I have attempted performing the request manually through the GUI with the Chrome network tab open, and I saw a request being made: https://firebasedatabase.clients6.google.com/v1beta/projects/XXXXXXXXXX/locations/us-central1/instances?databaseId=my-database&validateOnly=true&alt=json&key=secretkey

Per trial and error on another endpoint, I have found that the key parameter can be replaced with a Bearer Auth token in the header. Other than that I am at a dead end.


问:
I would like to use 3 main and one conditional components for my pages in react app
I am building a react app with tailwind css . I would like to use 3 main required components for all pages (Navbar,Left Part and Right Part) , also I would like to use 1 conditional component which change each page (Middle Part of Website)

This is my app . Red ones is my main components that I would like to use all pages , blue one is up to pages ( For example "/" , "/home" , "/dashboard" etc ...)

Could u help me about it ? Is it possible ? Thanks for help .

```<code>function App() {

  return (
    <div>
      <Navbar/>
      <div className="flex justify-between max-w-8xl sm:px-2 md:px-4">
        <Left/>
        <Middle/> // This will be "/" routes
        <Right/>
      </div>
    </div>
  );
}
</code>```

This is my app.js . I wrote this code but it did not work (tailwind style) clearly. Also I dont know it is true or not .

Body:
I am building a react app with tailwind css . I would like to use 3 main required components for all pages (Navbar,Left Part and Right Part) , also I would like to use 1 conditional component which change each page (Middle Part of Website)

This is my app . Red ones is my main components that I would like to use all pages , blue one is up to pages ( For example "/" , "/home" , "/dashboard" etc ...)

Could u help me about it ? Is it possible ? Thanks for help .

function App() {

  return (

      <Navbar/>

        <Left/>
        <Middle/> // This will be "/" routes
        <Right/>

  );
}

This is my app.js . I wrote this code but it did not work (tailwind style) clearly. Also I dont know it is true or not .


问:
Writing custom QGIS function in Python - is there a difference between "feature" and "$currentfeature"
I wrote the following custom qgsfunction:

```<code>@qgsfunction(args='auto', group='Custom', referenced_columns=[])
def f1(currentfeature, feature, parent):
    return "%s\n%s" % (repr(currentfeature),repr(feature))
</code>```

In the config for the label I enter the following expression:

```<code>f1($currentfeature)
</code>```

And here is the result:

I always believed that the $currentfeature would hold the same value as the implicitly passed argument feature, but they appear to be separate objects.

Can someone please either

confirm that they should be the same value, or

explain the difference between the two

(I also experience other odd things when executing my own custom functions, and I suspect something is not behaving as it should. Sometimes the addresss of the object changes when I zoom in or out, the address seems to cycle between af few values, and simply takes the next value in the cycle when I do any kind of zoom action. And the reason why I got to experiment with this in the first place is because I did not get the expected/correct attribute values back)

Body:
I wrote the following custom qgsfunction:

@qgsfunction(args='auto', group='Custom', referenced_columns=[])
def f1(currentfeature, feature, parent):
    return "%s\n%s" % (repr(currentfeature),repr(feature))

In the config for the label I enter the following expression:

f1($currentfeature)

And here is the result:

I always believed that the $currentfeature would hold the same value as the implicitly passed argument feature, but they appear to be separate objects.

Can someone please either

confirm that they should be the same value, or

explain the difference between the two

(I also experience other odd things when executing my own custom functions, and I suspect something is not behaving as it should. Sometimes the addresss of the object changes when I zoom in or out, the address seems to cycle between af few values, and simply takes the next value in the cycle when I do any kind of zoom action. And the reason why I got to experiment with this in the first place is because I did not get the expected/correct attribute values back)


问:
Is it possible to strip a shared library such that it can be run-time linked but not compile-time linked? Can the symbols be reconstructed?
Similar to this question: Is it safe to strip a shared library after linking?

I am curious if it is possible to strip a shared library such that one can no longer compile against it, but where binaries that have been compiled against it can still be linked at run-time?

I have an OpenWrt-based system.  The OpenWrt devs ship several (open source) libraries that appear to have had symbols necessary for compile-time linking against removed.  I don't have a deep knowledge of ELF shared libraries, but had not thought this was even possible.  However gcc reports undefined references to all the libraries functions. Rather than recompile every library so butchered, is there any way to rebuild those symbols in the shipped libs?  The symbols are still in the shared library in some way, as they can be seen with "strings".


问:
2 buttons in changepasswordtemplate validate differently
I added one more submit button (Button1) to my changepasswordtemplate. I added the same validationgroup as original (ChangePasswordPushButton) to button1 but this one only validates/shows after Postback. The first one behaves as expected.

```<code><asp:ChangePassword ID="ChangePwd" runat="server" >
        <ChangePasswordTemplate>
            <table cellpadding="1" style="border-collapse:collapse;">
                <tr>
                    <td>
                        <table cellspacing="5" cellpadding="5">

                            <tr>
                                <td align="right">
                                    <asp:Label ID="CurrentPasswordLabel" runat="server" AssociatedControlID="CurrentPassword">Password:</asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="CurrentPassword" runat="server" TextMode="Password"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="CurrentPasswordRequired" runat="server" ControlToValidate="CurrentPassword" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="ChangePwd">*</asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">
                                    <asp:Label ID="NewPasswordLabel" runat="server" AssociatedControlID="NewPassword">New Password:</asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="NewPassword" runat="server" TextMode="Password"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="NewPasswordRequired" runat="server" ControlToValidate="NewPassword" ErrorMessage="New Password is required." ToolTip="New Password is required." ValidationGroup="ChangePwd">*</asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">
                                    <asp:Label ID="ConfirmNewPasswordLabel" runat="server" AssociatedControlID="ConfirmNewPassword">Confirm New Password:</asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="ConfirmNewPassword" runat="server" TextMode="Password"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="ConfirmNewPasswordRequired" runat="server" ControlToValidate="ConfirmNewPassword" ErrorMessage="Confirm New Password is required." ToolTip="Confirm New Password is required." ValidationGroup="ChangePwd">*</asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td align="center" colspan="2">
                                    <asp:CompareValidator ID="NewPasswordCompare" runat="server" ControlToCompare="NewPassword" ControlToValidate="ConfirmNewPassword" Display="Dynamic" ErrorMessage="The Confirm New Password must match the New Password entry." ValidationGroup="ChangePwd"></asp:CompareValidator>
                                </td>
                            </tr>
                            <tr>
                                <td align="center" colspan="2" style="color:Red;">
                                    <asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
                                </td>
                            </tr>
                            <tr>
                                <td align="center">
                                    <asp:Button ID="ChangePasswordPushButton" class="orangeButton" runat="server" CommandName="ChangePassword" Text="Change Password" ValidationGroup="ChangePwd"/>
                                </td>
                                <td align="center">
                                    <asp:Button ID="CancelPushButton" class="orangeButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
                                </td>
                                <td align="center">
                                    <asp:Button ID="Button1" class="orangeButton" runat="server" CommandName="Upgrade" Text="Upgrade User Password" OnClick="Upgrade_Click" ValidationGroup="ChangePwd"/>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </ChangePasswordTemplate>
  ...
</asp:ChangePassword>
</code>```

What is the catch here? Button1 explicitly uses asp.net membership

MembershipUser.ChangePassword

whereas the other one has no code behind and just works!

Body:
I added one more submit button (Button1) to my changepasswordtemplate. I added the same validationgroup as original (ChangePasswordPushButton) to button1 but this one only validates/shows after Postback. The first one behaves as expected.

<asp:ChangePassword ID="ChangePwd" runat="server" >
        <ChangePasswordTemplate>

                                    <asp:Label ID="CurrentPasswordLabel" runat="server" AssociatedControlID="CurrentPassword">Password:</asp:Label>

                                    <asp:TextBox ID="CurrentPassword" runat="server" TextMode="Password"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="CurrentPasswordRequired" runat="server" ControlToValidate="CurrentPassword" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="ChangePwd">*</asp:RequiredFieldValidator>

                                    <asp:Label ID="NewPasswordLabel" runat="server" AssociatedControlID="NewPassword">New Password:</asp:Label>

                                    <asp:TextBox ID="NewPassword" runat="server" TextMode="Password"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="NewPasswordRequired" runat="server" ControlToValidate="NewPassword" ErrorMessage="New Password is required." ToolTip="New Password is required." ValidationGroup="ChangePwd">*</asp:RequiredFieldValidator>

                                    <asp:Label ID="ConfirmNewPasswordLabel" runat="server" AssociatedControlID="ConfirmNewPassword">Confirm New Password:</asp:Label>

                                    <asp:TextBox ID="ConfirmNewPassword" runat="server" TextMode="Password"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="ConfirmNewPasswordRequired" runat="server" ControlToValidate="ConfirmNewPassword" ErrorMessage="Confirm New Password is required." ToolTip="Confirm New Password is required." ValidationGroup="ChangePwd">*</asp:RequiredFieldValidator>

                                    <asp:CompareValidator ID="NewPasswordCompare" runat="server" ControlToCompare="NewPassword" ControlToValidate="ConfirmNewPassword" Display="Dynamic" ErrorMessage="The Confirm New Password must match the New Password entry." ValidationGroup="ChangePwd"></asp:CompareValidator>

                                    <asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>

                                    <asp:Button ID="ChangePasswordPushButton" class="orangeButton" runat="server" CommandName="ChangePassword" Text="Change Password" ValidationGroup="ChangePwd"/>

                                    <asp:Button ID="CancelPushButton" class="orangeButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />

                                    <asp:Button ID="Button1" class="orangeButton" runat="server" CommandName="Upgrade" Text="Upgrade User Password" OnClick="Upgrade_Click" ValidationGroup="ChangePwd"/>

        </ChangePasswordTemplate>
  ...
</asp:ChangePassword>

What is the catch here? Button1 explicitly uses asp.net membership

MembershipUser.ChangePassword

whereas the other one has no code behind and just works!


问:
How do I push selected checkboxes into an array?
I'm having trouble getting the checkboxes in my rows to work.

All my checkboxes are showing up as selected and I am getting the following error Error in v-on handler:"referenceError: networkAudience is not defined
How do I fix this error? or is there a better way to push selected checkboxes into an array?

data()
{
networkAudiences: {},
selected: []
},
methods:
{
 selectedNetAudience()
  {
  this.selected = [];
  for (networkAudience in this.networkAudiences)

  this.selected.push(this.networkAudiences[networkAudience].id);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr
v-for="(networkAudience) in fixedNetworkAudiences(audience)"
:key="audience.id + networkAudience.id"
 >
  <td>
   <input
     class="form-check-input"
     type="checkbox"
     autocomplete="off"
     :checked="selected"
     @change="selectedNetAudience()">
  </td>
</tr></code>```

Thanks in advance!

Body:
I'm having trouble getting the checkboxes in my rows to work.

All my checkboxes are showing up as selected and I am getting the following error Error in v-on handler:"referenceError: networkAudience is not defined
How do I fix this error? or is there a better way to push selected checkboxes into an array?

data()
{
networkAudiences: {},
selected: []
},
methods:
{
 selectedNetAudience()
  {
  this.selected = [];
  for (networkAudience in this.networkAudiences)

  this.selected.push(this.networkAudiences[networkAudience].id);
  }
}

   <input
     class="form-check-input"
     type="checkbox"
     autocomplete="off"
     :checked="selected"
     @change="selectedNetAudience()">

Thanks in advance!


问:
How do I fix ValueError: No objects to concatenate in this code?
The following code is used to open .txt files. Yet I have encountered ValueError. I searched this error on Stack Overflow before but couldn't find any solutions. Below is the code:

```<code>from pathlib import Path

data=Path('/work/')
DATA = Path(data/"nlp"/"zh"/"cc_vs_zh")
TO_CLASSICAL = True

all_file = list(DATA.rglob("work/data/*"))

import os
import glob

def open_file_to_lines(file):
    with open(file) as f:
        lines = f.read().splitlines()
    return lines

def pairing_the_file(files,kw):
    pairs = []
    for file in files:
        if kw not in file.name:
            file1 = file
            file2 = f"{file}{kw}"
            pairs.append((file1,file2))
    return pairs

import pandas as pd
from tqdm import *
pairs = pairing_the_file(all_file,"翻译")

def open_pairs(pairs):
    chunks = []
    for pair in tqdm(pairs, leave=False):
        file1,file2 = pair
        lines1 = open_file_to_lines(file1)
        lines2 = open_file_to_lines(file2)
        chunks.append(pd.DataFrame({"classical":lines1,"modern":lines2}))
    return pd.concat(chunks).sample(frac=1.).reset_index(drop=True)

data_df=open_pairs(pairs)

df=data_df.rename(columns = dict(zip(["modern","classical"],["source","target"] if TO_CLASSICAL else ["target","source",])))

df.head()
</code>```

I've got the following error:

enter image description here

How should I fixed this error?

Body:
The following code is used to open .txt files. Yet I have encountered ValueError. I searched this error on Stack Overflow before but couldn't find any solutions. Below is the code:

from pathlib import Path

data=Path('/work/')
DATA = Path(data/"nlp"/"zh"/"cc_vs_zh")
TO_CLASSICAL = True

all_file = list(DATA.rglob("work/data/*"))

import os
import glob

def open_file_to_lines(file):
    with open(file) as f:
        lines = f.read().splitlines()
    return lines

def pairing_the_file(files,kw):
    pairs = []
    for file in files:
        if kw not in file.name:
            file1 = file
            file2 = f"{file}{kw}"
            pairs.append((file1,file2))
    return pairs

import pandas as pd
from tqdm import *
pairs = pairing_the_file(all_file,"翻译")

def open_pairs(pairs):
    chunks = []
    for pair in tqdm(pairs, leave=False):
        file1,file2 = pair
        lines1 = open_file_to_lines(file1)
        lines2 = open_file_to_lines(file2)
        chunks.append(pd.DataFrame({"classical":lines1,"modern":lines2}))
    return pd.concat(chunks).sample(frac=1.).reset_index(drop=True)

data_df=open_pairs(pairs)

df=data_df.rename(columns = dict(zip(["modern","classical"],["source","target"] if TO_CLASSICAL else ["target","source",])))

df.head()

I've got the following error:

enter image description here

How should I fixed this error?


问:
Compact Hashing
Looking to implement a hashing process so that we can redact aged sensitive details such as email addresses or phone numbers, but without losing the signature of the original value.

In other words, we can still find someone if their email presents again, by hashing it and checking it again our stored email hashes in existing records.

The algorithm needs to have:

one-way process, unfeasible to reverse

same input always produces same output

same output only ever produced by same input

These are the standard features of hashing, but we are finding that most common algorithms have their output determined by their block size, for example 160 bits (SHA-1) or 256/384/512 bits (SHA-2).

What we are looking for is a hash algorithm that produces output of the same size text that the original value was represented with.  That way it can simply be stored back into the database columns that the original value came from.

I'm not seeing this concept being discussed much anywhere.  Are there any hashing techniques that work with this goal in mind, or is there some reason that makes it impractical?

Title: Compact Hashing


问:
Problem connecting a Socket.io client in a Unity3d project configured with MRTK2
```<code>hi, i'm trying to implement a socket.io client inside a unity3d project configured with mrtk2.
Using the library recommended by Socket.io for a C# client I was able
to establish the connection to the server, but as soon as I insert the
code inside a Unity3d project configured with MRTK2 with the appropriate
[SocketIoCLient][1](https://github.com/doghappy/socket.io-client-csharp) library,
the client does not connect it connects to the server without throwing any exception or error,
can anyone help me?

</code>```

I've included the library inside the project via NuGet to manage the dependencies, the only client that didn't throw me any exceptions with the MRTK2 configuration is SocketIOClient.NetFx 2.0.2.10
NuGet\Install-Package SocketIOClient.NetFx -Version 2.0.2.10

I use a server for Socket.io written in Node.js which essentially prints a string when a client connects, and as tested the client I made and the server only work if the Unity3d project hasn't been configured for MRTK2

Body:
hi, i'm trying to implement a socket.io client inside a unity3d project configured with mrtk2.
Using the library recommended by Socket.io for a C# client I was able
to establish the connection to the server, but as soon as I insert the
code inside a Unity3d project configured with MRTK2 with the appropriate
[SocketIoCLient][1](https://github.com/doghappy/socket.io-client-csharp) library,
the client does not connect it connects to the server without throwing any exception or error,
can anyone help me?

I've included the library inside the project via NuGet to manage the dependencies, the only client that didn't throw me any exceptions with the MRTK2 configuration is SocketIOClient.NetFx 2.0.2.10
NuGet\Install-Package SocketIOClient.NetFx -Version 2.0.2.10

I use a server for Socket.io written in Node.js which essentially prints a string when a client connects, and as tested the client I made and the server only work if the Unity3d project hasn't been configured for MRTK2