问:
How to count the difference between a random int array elements values in Java
I'm a beginner and need help with following:-)There is a random int array, the values(0-10) are showing the level of terrain, I need to count first how much water can be stored on this ground structure. For example int[] randomTerrain = {8, 4, 8, 2, 6, 3, 2, 1, 6, 9}; the water strorage capacity of this groundstructure is 0+4+0+6+2+5+6+7+2+0=32. I have two questions, first how to count it from a random int array?
Second is a bit different as I need to print out and visualize it in a 2D string array [10][10] where string ground = "*"; string water = "-"; and the air is empty space.
Thanks in advance for Your help! below You can se what I've done, but it is not wotrking as expected.
GhostCats resolution is perfect but as we did not learn still about stream methods it would be apreciate if somebody could help with a bit different resolution using only simple methods.
package Rezervoir;

import java.util.Arrays;
import java.util.Random;

public class Rezervoir {

```<code>private static final int TERRAIN_HEIGHT = 10;
private static final int TERRAIN_WIDTH = 10;

public static void main(String[] args) {

    int[] randomTerrain = createRandomTerrain();
    System.out.println(Arrays.toString(randomTerrain));

    int waterStorageCapacity = countWaterCapacity(randomTerrain);
    System.out.println(waterStorageCapacity);
    System.out.println();
    String[][] terrain = {
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "}
    };

    int row = 0;
    int column = 0;

    for (column = 0 ; column < terrain[0].length ; column++) {

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

            if ((terrain.length -1) -row <= randomTerrain[column]) {

                terrain[column][row] = "*";
            }
            System.out.print(terrain[terrain.length-1-row][column] + "\t");
        }
        System.out.println();
    }
}
private static int countWaterCapacity(int[] randomTerrain) {
    int capacitySum = 0;
    int firstTop = 0;

    for (int i = 0 ; i < randomTerrain.length -1 ; i++) {

        if (randomTerrain[i] >= randomTerrain[i+1]) {
            firstTop = randomTerrain[i];
        }
            else if (randomTerrain[i+1] >= randomTerrain[i])    {
                firstTop = randomTerrain[i+1];
            }
        int capacity = 0;
        capacity = firstTop - randomTerrain[i];
        capacitySum += capacity;
    }
    return capacitySum;
}
private static int[] createRandomTerrain() {
    int[] randomTerrain = new int[TERRAIN_WIDTH];

    for (int i = 0 ; i < randomTerrain.length ; i ++) {
        randomTerrain[i] = (int) (Math.random() * TERRAIN_HEIGHT + 1);

    }
    return randomTerrain;
}
</code>```

}

答:
the code's meaning is basically explained in the comments. this may solve your problem but maybe it's not the most efficient way. You can explore more ways by yourself.

public class Main {

    public static void main(String[] args) {
        int[] terrain = { 8, 4, 8, 2, 6, 3, 2, 1, 6, 9 };
        int[] capacity = countCapacity(terrain);
        int sum = Arrays.stream(capacity).sum();
        System.out.println(Arrays.toString(capacity));
        System.out.println(sum);
        printGraph(terrain,capacity);
    }

    public static void printGraph(int[] terrain, int[] capacity) {
        // find the max height, and it will be the row numbers of console output.
        int maxHeight = Arrays.stream(terrain).max().orElse(0);
        for (int j = maxHeight; j > 0; j--) {
            for (int i = 0; i < terrain.length; i++) {
                // if terrain height is lower than current printing height.
                if (terrain[i] < j){
                    // and terrain's capacity + height is lower, just print space
                    if (capacity[i] + terrain[i] < j){
                        System.out.print("   ");
                    // otherwise, print water
                    }else {
                        System.out.print(" - ");
                    }
                // if terrain height is higher than current printing height. print terrain
                }else {
                    System.out.print(" * ");
                }
            }
            // make a new row.
            System.out.println();
        }
    }

    public static int[] countCapacity(int[] terrain) {
        List<Integer> terranList = Arrays.stream(terrain).boxed().collect(Collectors.toList());
        int[] capacity = new int[terrain.length];
        // the first and last terrain's capacity must be 0. just set it first.
        capacity[0] = 0;
        capacity[capacity.length - 1] = 0;
        for (int i = 1; i < terrain.length - 1; i++) {
            // if there's no terrain higher than current terrain at left. then it can not hold water.
            // so it's capacity is 0, and skip to next terrain.
            int currentHeight = terrain[i];
            int leftHighest = Collections.max(terranList.subList(0, i));
            if (leftHighest <= currentHeight) {
                capacity[i] = 0;
                continue;
            }
            // if there's no higher terrain in the right. the same as above.
            int rightHighest = Collections.max(terranList.subList(i + 1, terranList.size()));
            if (rightHighest <= currentHeight) {
                capacity[i] = 0;
                continue;
            }
            // if there are higher terrain int both direction. this terrain can hold water.
            // and its capacity is the lower one minus this terrain's height.
            capacity[i] = Math.min(leftHighest, rightHighest) - currentHeight;
        }
        return capacity;
    }
}
```
<p>the output may like:</p>
```[0, 4, 0, 6, 2, 5, 6, 7, 2, 0]
32
                            *
 *  -  *  -  -  -  -  -  -  *
 *  -  *  -  -  -  -  -  -  *
 *  -  *  -  *  -  -  -  *  *
 *  -  *  -  *  -  -  -  *  *
 *  *  *  -  *  -  -  -  *  *
 *  *  *  -  *  *  -  -  *  *
 *  *  *  *  *  *  *  -  *  *
 *  *  *  *  *  *  *  *  *  *
```

Body:
I'm a beginner and need help with following:-)There is a random int array, the values(0-10) are showing the level of terrain, I need to count first how much water can be stored on this ground structure. For example int[] randomTerrain = {8, 4, 8, 2, 6, 3, 2, 1, 6, 9}; the water strorage capacity of this groundstructure is 0+4+0+6+2+5+6+7+2+0=32. I have two questions, first how to count it from a random int array?
Second is a bit different as I need to print out and visualize it in a 2D string array [10][10] where string ground = "*"; string water = "-"; and the air is empty space.
Thanks in advance for Your help! below You can se what I've done, but it is not wotrking as expected.
GhostCats resolution is perfect but as we did not learn still about stream methods it would be apreciate if somebody could help with a bit different resolution using only simple methods.
package Rezervoir;

import java.util.Arrays;
import java.util.Random;

public class Rezervoir {

private static final int TERRAIN_HEIGHT = 10;
private static final int TERRAIN_WIDTH = 10;

public static void main(String[] args) {

    int[] randomTerrain = createRandomTerrain();
    System.out.println(Arrays.toString(randomTerrain));

    int waterStorageCapacity = countWaterCapacity(randomTerrain);
    System.out.println(waterStorageCapacity);
    System.out.println();
    String[][] terrain = {
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "},
            {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "}
    };

    int row = 0;
    int column = 0;

    for (column = 0 ; column < terrain[0].length ; column++) {

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

            if ((terrain.length -1) -row <= randomTerrain[column]) {

                terrain[column][row] = "*";
            }
            System.out.print(terrain[terrain.length-1-row][column] + "\t");
        }
        System.out.println();
    }
}
private static int countWaterCapacity(int[] randomTerrain) {
    int capacitySum = 0;
    int firstTop = 0;

    for (int i = 0 ; i < randomTerrain.length -1 ; i++) {

        if (randomTerrain[i] >= randomTerrain[i+1]) {
            firstTop = randomTerrain[i];
        }
            else if (randomTerrain[i+1] >= randomTerrain[i])    {
                firstTop = randomTerrain[i+1];
            }
        int capacity = 0;
        capacity = firstTop - randomTerrain[i];
        capacitySum += capacity;
    }
    return capacitySum;
}
private static int[] createRandomTerrain() {
    int[] randomTerrain = new int[TERRAIN_WIDTH];

    for (int i = 0 ; i < randomTerrain.length ; i ++) {
        randomTerrain[i] = (int) (Math.random() * TERRAIN_HEIGHT + 1);

    }
    return randomTerrain;
}

}

Body:
the code's meaning is basically explained in the comments. this may solve your problem but maybe it's not the most efficient way. You can explore more ways by yourself.

public class Main {

    public static void main(String[] args) {
        int[] terrain = { 8, 4, 8, 2, 6, 3, 2, 1, 6, 9 };
        int[] capacity = countCapacity(terrain);
        int sum = Arrays.stream(capacity).sum();
        System.out.println(Arrays.toString(capacity));
        System.out.println(sum);
        printGraph(terrain,capacity);
    }

    public static void printGraph(int[] terrain, int[] capacity) {
        // find the max height, and it will be the row numbers of console output.
        int maxHeight = Arrays.stream(terrain).max().orElse(0);
        for (int j = maxHeight; j > 0; j--) {
            for (int i = 0; i < terrain.length; i++) {
                // if terrain height is lower than current printing height.
                if (terrain[i] < j){
                    // and terrain's capacity + height is lower, just print space
                    if (capacity[i] + terrain[i] < j){
                        System.out.print("   ");
                    // otherwise, print water
                    }else {
                        System.out.print(" - ");
                    }
                // if terrain height is higher than current printing height. print terrain
                }else {
                    System.out.print(" * ");
                }
            }
            // make a new row.
            System.out.println();
        }
    }

    public static int[] countCapacity(int[] terrain) {
        List<Integer> terranList = Arrays.stream(terrain).boxed().collect(Collectors.toList());
        int[] capacity = new int[terrain.length];
        // the first and last terrain's capacity must be 0. just set it first.
        capacity[0] = 0;
        capacity[capacity.length - 1] = 0;
        for (int i = 1; i < terrain.length - 1; i++) {
            // if there's no terrain higher than current terrain at left. then it can not hold water.
            // so it's capacity is 0, and skip to next terrain.
            int currentHeight = terrain[i];
            int leftHighest = Collections.max(terranList.subList(0, i));
            if (leftHighest <= currentHeight) {
                capacity[i] = 0;
                continue;
            }
            // if there's no higher terrain in the right. the same as above.
            int rightHighest = Collections.max(terranList.subList(i + 1, terranList.size()));
            if (rightHighest <= currentHeight) {
                capacity[i] = 0;
                continue;
            }
            // if there are higher terrain int both direction. this terrain can hold water.
            // and its capacity is the lower one minus this terrain's height.
            capacity[i] = Math.min(leftHighest, rightHighest) - currentHeight;
        }
        return capacity;
    }
}

the output may like:

[0, 4, 0, 6, 2, 5, 6, 7, 2, 0]
32
                            *
 *  -  *  -  -  -  -  -  -  *
 *  -  *  -  -  -  -  -  -  *
 *  -  *  -  *  -  -  -  *  *
 *  -  *  -  *  -  -  -  *  *
 *  *  *  -  *  -  -  -  *  *
 *  *  *  -  *  *  -  -  *  *
 *  *  *  *  *  *  *  -  *  *
 *  *  *  *  *  *  *  *  *  *


来源: stackexchange

问:
AttributeError: 'str' object has no attribute 'request' - googletrans
I am trying to use this google translate python library googletrans 3.0.0, which I installed from pypi.

I used this code to start with:

```<code>from googletrans import Translator

proxies = {'http': 'http://myproxy.com:8080', 'https': 'http://myproxy.com:8080'}
translator = Translator(proxies=proxies)
translator.translate("colour")
</code>```

When I call the translator in the last line above, I got this error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/client.py", line 182, in translate
    data = self._translate(text, dest, src, kwargs)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/client.py", line 78, in _translate
    token = self.token_acquirer.do(text)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/gtoken.py", line 194, in do
    self._update()
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/gtoken.py", line 54, in _update
    r = self.client.get(self.host)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 755, in get
    return self.request(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 600, in request
    return self.send(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 620, in send
    response = self.send_handling_redirects(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 647, in send_handling_redirects
    response = self.send_handling_auth(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 684, in send_handling_auth
    response = self.send_single_request(request, timeout)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 714, in send_single_request
    ) = transport.request(
AttributeError: 'str' object has no attribute 'request'
</code>```

Is it the way I am inputting the proxies information to the Translator that makes it unhappy?

答:
This seems to be very confusing according to the official docs, but this github issue has a solution.

For some reason the docs specify both strings and HTTPTransports but this has been clarified in the issue above.

Basically:

from httpcore import SyncHTTPProxy
from googletrans import Translator

http_proxy = SyncHTTPProxy((b'http', b'myproxy.com', 8080, b''))
proxies = {'http': http_proxy, 'https': http_proxy }

translator = Translator(proxies=proxies)
translator.translate("colour")
```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use this google translate python library googletrans 3.0.0, which I installed from pypi.

I used this code to start with:

from googletrans import Translator

proxies = {'http': 'http://myproxy.com:8080', 'https': 'http://myproxy.com:8080'}
translator = Translator(proxies=proxies)
translator.translate("colour")

When I call the translator in the last line above, I got this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/client.py", line 182, in translate
    data = self._translate(text, dest, src, kwargs)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/client.py", line 78, in _translate
    token = self.token_acquirer.do(text)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/gtoken.py", line 194, in do
    self._update()
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/gtoken.py", line 54, in _update
    r = self.client.get(self.host)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 755, in get
    return self.request(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 600, in request
    return self.send(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 620, in send
    response = self.send_handling_redirects(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 647, in send_handling_redirects
    response = self.send_handling_auth(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 684, in send_handling_auth
    response = self.send_single_request(request, timeout)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 714, in send_single_request
    ) = transport.request(
AttributeError: 'str' object has no attribute 'request'

Is it the way I am inputting the proxies information to the Translator that makes it unhappy?


问:
Android Studio suddenly can't find ANY drawable components
Like the title suggests, all of a sudden, my Android Studio projects simply can't locate any of my drawable resources that I call when using android:background="@drawable/serving_editor_background" for example, it'll just give me this error code for every single drawable that has been called:

```<code>AAPT: error: resource drawable/serving_editor_background (aka com.example.poop123:drawable/serving_editor_background) not found.
</code>```
```<code>Execution failed for task ':app:mergeDebugResources'.
> com.android.build.gradle.tasks.ResourceException (no error message)
</code>```
```<code>ParseError at [row,col]:[2,6]
Message: The processing instruction target matching "[xX][mM][lL]" is not allowed.
</code>```

It literally does it for every single one (with their respective names and file path), all of the ones that used to work up until now, not a single one works, and I never changed anything in the gradle, but I'll still provide it:

```<code>plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.poop123"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'com.ismaeldivita.chipnavigation:chip-navigation-bar:1.3.2'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.72'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.github.devlight.navigationtabstrip:navigationtabstrip:+'
    implementation 'com.google.firebase:firebase-database:20.0.2'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    implementation 'androidx.wear:wear:1.0.0'

    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    compileOnly 'com.google.android.wearable:wearable:2.6.0'
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.poop123">

    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Poop123">
        <activity android:name=".EditAddition"></activity>
        <activity android:name=".ConfirmAddition" />
        <activity android:name=".Goal" />
        <activity android:name=".ActivityLevel" />
        <activity android:name=".newFoodMenu" />
        <activity android:name=".foodLibrary" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

I'm getting really frustrated at this, because I changed absolutely nothing (just a specific XML code for a certain activity), and now none of the drawables can be found.
If any more info, let me know.

答: First of all locate the drawable folder of your project and see the resources. if you found the resources try android:src="@drawable/resource"</p>

Body:
Like the title suggests, all of a sudden, my Android Studio projects simply can't locate any of my drawable resources that I call when using android:background="@drawable/serving_editor_background" for example, it'll just give me this error code for every single drawable that has been called:

AAPT: error: resource drawable/serving_editor_background (aka com.example.poop123:drawable/serving_editor_background) not found.

Execution failed for task ':app:mergeDebugResources'.
> com.android.build.gradle.tasks.ResourceException (no error message)

ParseError at [row,col]:[2,6]
Message: The processing instruction target matching "[xX][mM][lL]" is not allowed.

It literally does it for every single one (with their respective names and file path), all of the ones that used to work up until now, not a single one works, and I never changed anything in the gradle, but I'll still provide it:

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.poop123"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'com.ismaeldivita.chipnavigation:chip-navigation-bar:1.3.2'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.72'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.github.devlight.navigationtabstrip:navigationtabstrip:+'
    implementation 'com.google.firebase:firebase-database:20.0.2'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    implementation 'androidx.wear:wear:1.0.0'

    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    compileOnly 'com.google.android.wearable:wearable:2.6.0'

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.poop123">

    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Poop123">
        <activity android:name=".EditAddition"></activity>
        <activity android:name=".ConfirmAddition" />
        <activity android:name=".Goal" />
        <activity android:name=".ActivityLevel" />
        <activity android:name=".newFoodMenu" />
        <activity android:name=".foodLibrary" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I'm getting really frustrated at this, because I changed absolutely nothing (just a specific XML code for a certain activity), and now none of the drawables can be found.
If any more info, let me know.


问:
Having a common YAML file for PUSH and TAG based trigger in Google cloud build
I am trying to build a common YAML file for both push and tag-based triggers. I can build two YAML files and pass them to the triggers setting page in Google cloud build, but I want to have a common file for both of them.

In the push trigger, the YAML consists of unit testing and in the tag-based trigger, the YAML consists of unit testing and containerizing the application to be pushed to the artifact registry. As YAML is a text-formatting language and if/else conditions cannot be incorporated in it, how can I do this in one single file?

If you want any other information, please let me know and looking forward to help, thanks in advance

答: You are right, YAML doesn’t support conditional statements, but you can use GitLab to help you parse if statements as mentioned in If condition is possible in YAML file. With the help of this you will be able to add the respective code for Push and tag trigger in the same file.


问:
CSS Overflow issue in IE
I having problem to make the overflow hidden if the width is over the line
anyone know how to do it?

It does not work for IE at all.

```<code><style type="text/css">
body{
    font-family:Calibri;
    font-size:12pt;
}
table.excel {
    border-collapse:collapse;
    color:#000000;
    font-weight:400;
    font-style:inherit;
    text-align:left;
    vertical-align:bottom;
    border:1px solid #C0C0C0;
}

.datacell {
    border: 1px solid #C0C0C0;
}
</style>

<table class="excel" width="194px">
    <tr>
        <td style="width:30px;"> </td>
        <td style="width:64px;">A</td>
        <td style="width:100px;">B</td>
    </tr>
    <tr>
        <td style="height:50px;">1</td>
        <td class="datacell" style="max-width:64px;">
            <div style="float:left;min-width:160px;white-space: nowrap; overflow: hidden; position:relative;background-color:#FFFFFF;">I like to eat McDonalds double<br>cheese burger, i am lovin it!</div>
        </td>
        <td class="datacell">aa</td>
    </tr>
</table>
</code>```

答: I try changing min-width:160px; in div's style to width:160px; & it solved your problem.

ContentLicense: CC BY-SA 3.0

Title: CSS Overflow issue in IE

Body:
I having problem to make the overflow hidden if the width is over the line
anyone know how to do it?

It does not work for IE at all.

        A
        B

        1

I like to eat McDonalds double
cheese burger, i am lovin it!

        aa


问:
error TS2554: Expected 1 arguments, but got 2. State, React
I am working on a InfiniteScroll with React and TypeScript.
When I am setting Posts state using setPosts and setting there a page using setPage I have an error Expected 1 arguments, but got 2. How can I declare in state that I am going to use two parameters and one of them is a setPage?

```<code>  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const lastItemRef = useRef(null);
  const observer = useRef<IntersectionObserver>();

  useEffect(() => {
    fetchPosts().then((res: any) => {
      setPosts([...res.posts], setPage(res.page));
    });
  }, []);

</code>```

答:
setPosts() can have only one arguments.
if you want save both posts and page.
your code should be looks like this

```<code>setPosts([...posts, res.posts])
setPage(res.page) or setPage([...page, res.page])
</code>```

I am not sure why you are using page hook, but I think this will be better to manage posts.

```<code>setPosts([...posts, {post: res.posts, page: res.page}])
</code>```

or

```<code>setPosts([...posts, res])
</code>```

and use posts.posts, and posts.page

Body:
I am working on a InfiniteScroll with React and TypeScript.
When I am setting Posts state using setPosts and setting there a page using setPage I have an error Expected 1 arguments, but got 2. How can I declare in state that I am going to use two parameters and one of them is a setPage?

  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const lastItemRef = useRef(null);
  const observer = useRef<IntersectionObserver>();

  useEffect(() => {
    fetchPosts().then((res: any) => {
      setPosts([...res.posts], setPage(res.page));
    });
  }, []);

Body:
setPosts() can have only one arguments.
if you want save both posts and page.
your code should be looks like this

setPosts([...posts, res.posts])
setPage(res.page) or setPage([...page, res.page])

I am not sure why you are using page hook, but I think this will be better to manage posts.

setPosts([...posts, {post: res.posts, page: res.page}])

or

setPosts([...posts, res])

and use posts.posts, and posts.page


问:
How to get Substr when annotate Django
I'm try to sort by order_number had many kind

Input:

```<code>ADC123
ADC14
ADC23
ERD324
ERD12
</code>```

Sort default just sort by alphabet

Expected results (Sort only by number):

```<code>ERD12
ADC14
ADC23
ADC123
ERD324
</code>```

Code example:

```<code>Person.objects.annotate(
    order_only_number=AddField(Substr("order_number", 1))
).order_by("order_only_number")
</code>```

答:
Please don't do this. If your order number contains an alpha part and a numerical part, you can use two fields, like:

```<code>class Person(models.Model):
    order_alpha_part = models.CharField()
    order_number_part = models.IntegerField()

    @property
    def order_number(self):
        return f'{self.order_alpha_part}{order_number_part}'
</code>```

then you thus can use .order_by('order_number_part'). The property allows you to access the .order_number which will concatenate the alpha part with the number part.

Title: How to get Substr when annotate Django

Body:
I'm try to sort by order_number had many kind

Input:

ADC123
ADC14
ADC23
ERD324
ERD12

Sort default just sort by alphabet

Expected results (Sort only by number):

ERD12
ADC14
ADC23
ADC123
ERD324

Code example:

Person.objects.annotate(
    order_only_number=AddField(Substr("order_number", 1))
).order_by("order_only_number")

Body:
Please don't do this. If your order number contains an alpha part and a numerical part, you can use two fields, like:

class Person(models.Model):
    order_alpha_part = models.CharField()
    order_number_part = models.IntegerField()

    @property
    def order_number(self):
        return f'{self.order_alpha_part}{order_number_part}'

then you thus can use .order_by('order_number_part'). The property allows you to access the .order_number which will concatenate the alpha part with the number part.


问:
assign the value returned from .invoke() into a variable in Cypress
i am using the following code to get a text value from a  :

```<code> let serviceName;
    cy.get('tr').eq(1).then(row => {
        cy.wrap(row).find('td').eq(1).invoke('prop', 'innerText').then(val => { serviceName = val });
    })
</code>```

its working fine on some of pages and not on some others with the same table type/class/etc..
front end is built with Angular

using the same code like this also fails :

```<code>let serviceName;
    cy.get('tr').eq(1).find('td').eq(1).invoke('prop', 'innerText').then(val => { serviceName = val });
    })
</code>```

答:
You can use aliases for this.

cy.get('tr')
  .eq(1)
  .find('td', {timeout: 5000})
  .eq(1)
  .should('be.visible')
  .invoke('prop', 'innerText')
  .as('text')

cy.get('@text').then((text) => {
  //access text here
})
```

Body:
i am using the following code to get a text value from a  :

 let serviceName;
    cy.get('tr').eq(1).then(row => {
        cy.wrap(row).find('td').eq(1).invoke('prop', 'innerText').then(val => { serviceName = val });
    })

its working fine on some of pages and not on some others with the same table type/class/etc..
front end is built with Angular

using the same code like this also fails :

let serviceName;
    cy.get('tr').eq(1).find('td').eq(1).invoke('prop', 'innerText').then(val => { serviceName = val });
    })


问:
chai-as-promised rejection doesn't fail test but only print warning instead
I'm using chai-as-promised to test my readIndex(path): string function.

readIndex() returns a promise which in turn try to open and parse to JSON a file named index.json in target folder.

See the following extract :

```<code>// readIndex.js
module.exports = path =>
  new Promise((resolve, reject) => {
    try {
      const buffer = fs.readFileSync(path + '/index.json')
      const data = JSON.parse(buffer.toString())
      resolve(data)
    } catch (err) {
      if (err.code === 'ENOENT') {
        reject(Error('file not found'))
      } else if (err instanceof SyntaxError) {
        reject(Error('format not json'))
      } else {
        reject(err)
      }
    }
  })
</code>```

With my case test's mock, the returned promise reject with the error "file not found".

But actually I'm testing with a (supposed to be) valid case, that should pass only if the promise resolved succesfully ...

At least this is what I understood of the promise.should.be.fulfilled usage.

See the test in question :

```<code>// readIndex.test.js
chai.use(chaiAsPromised)
chai.should()

describe('SUCCESS :', () =>
  it('should resolve with a (markdown) string extrapoled from target folder index file', done => {
    const key = 'content success'
    mock(_mocks[key])
    const promise = readIndex('test')
    promise.should.be.fulfilled
    mock.restore()
    done()
  }))
</code>```

With such a setup, running the test does not make it fail; it prints this message instead :

    SUCCESS :
          √ should resolve with a (markdown) string extrapoled from target folder index file
    (node:183516) UnhandledPromiseRejectionWarning: AssertionError: expected promise to be fulfilled but it was rejected with 'Error: file not found'
    (node:183516) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 10)
    (node:183516) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
```

<p>Of course, expected outcome should be a failed test run, and something like this in the console :</p>

<pre class="lang-sh prettyprint-override"><code>SUCCESS :
         1) should resolve with a (markdown) string extrapoled from target folder index file:

      AssertionError: expected '1' to equal '2'
</code>```

This strange behaviour even lead to (funny and) incoherent warnings.

Using promise.should.not.be.rejected, I got "expected promise not to be rejected but it was rejected" but test still passed :

SUCCESS :
      √ should resolve with a (markdown) string extrapoled from target folder index file
(node:225676) UnhandledPromiseRejectionWarning: AssertionError: expected promise not to be rejected but it was rejected with 'Error: file not found'
```

Actually my thoughts are that :

A solution would to increase the level of test fail to warnings, but I didn't found it in the chai-as-promised documentation.

Another solution would be to understand what layer is catching the Error/rejection, and is lowering it to a warning. Maybe a chai-as-promised default parameter ?

答:
I initially was using chai-as-promised there was some issue with promises not being correctly awaited that lead to hours of debugging my tests.

In the end I rolled my own solution.

EDIT v2 - more concise

```<code>// test-utils.ts

import { expect } from "chai";

export const expectRejection = async (
  promise: Promise<any>,
  errMsg: string
): Promise<void> => {
  try {
    await promise;
  } catch (err) {
    expect(err.message).eq(errMsg);
    return;
  }
  throw Error('Promise was not rejected');
};

</code>```

You can use the function like this in your tests

```<code>it('Function that fails', async () => {
  const errMsg = 'My example';
  const functionThatRejects = async () => {
    throw Error(errMsg);
  };
  await expectRejection(functionThatRejects(), errMsg);
});
</code>```

And for completeness here is a unit test for the function.

```<code>import { expectRejection } from './test-utils';
import { expect } from 'chai';

describe('test-utils.ts', () => {
  describe('expectRejection(..)', () => {
    it('Function that fails', async () => {
      const errMsg = 'My example';
      const functionThatRejects = async () => {
        throw Error(errMsg);
      };
      await expectRejection(functionThatRejects(), errMsg);
    });

    it("Function that doesn't fail", async () => {
      const functionThatResolves = async () => null;
      try {
        await expectRejection(functionThatResolves(), "Random error message");
      } catch (err) {
        expect(err).match(/Promise was not rejected/);
        return;
      }
      throw Error('Should have already returned');
    });
  });
});

</code>```

v1 - more flexable

```<code>// test-utils.ts

import { expect } from "chai";

export const expectRejection = async (promise: Promise<any>) => {
  try {
    await promise;
  } catch (err) {
    return expect(err);
  }
  throw Error('Promise was not rejected');
};

</code>```

You can use the function like this in your tests

```<code>it('Function that fails', async () => {
  const functionThatRejects = async () => {
    throw Error('My example');
  };
  const rejection = await expectRejection(functionThatRejects());
  rejection.match(/My example/);
});
</code>```

And for completeness here is a unit test for the function.

```<code>// test-utils.spec.ts

import { expectRejection } from './test-utils';
import { expect } from 'chai';

describe('expectRejection(..)', () => {
  it('Function that fails', async () => {
    const functionThatRejects = async () => {
      throw Error('My example');
    };
    const rejection = await expectRejection(functionThatRejects());
    rejection.match(/My example/);
  });

  it("Function that doesn't fail", async () => {
    const functionThatResolves = async () => null;
    try {
      await expectRejection(functionThatResolves());
    } catch (err) {
      expect(err).match(/Promise was not rejected/);
      return;
    }
    throw Error('Should have already returned');
  });
});

</code>```

Body:
I'm using chai-as-promised to test my readIndex(path): string function.

readIndex() returns a promise which in turn try to open and parse to JSON a file named index.json in target folder.

See the following extract :

// readIndex.js
module.exports = path =>
  new Promise((resolve, reject) => {
    try {
      const buffer = fs.readFileSync(path + '/index.json')
      const data = JSON.parse(buffer.toString())
      resolve(data)
    } catch (err) {
      if (err.code === 'ENOENT') {
        reject(Error('file not found'))
      } else if (err instanceof SyntaxError) {
        reject(Error('format not json'))
      } else {
        reject(err)
      }
    }
  })

With my case test's mock, the returned promise reject with the error "file not found".

But actually I'm testing with a (supposed to be) valid case, that should pass only if the promise resolved succesfully ...

At least this is what I understood of the promise.should.be.fulfilled usage.

See the test in question :

// readIndex.test.js
chai.use(chaiAsPromised)
chai.should()

describe('SUCCESS :', () =>
  it('should resolve with a (markdown) string extrapoled from target folder index file', done => {
    const key = 'content success'
    mock(_mocks[key])
    const promise = readIndex('test')
    promise.should.be.fulfilled
    mock.restore()
    done()
  }))

With such a setup, running the test does not make it fail; it prints this message instead :

    SUCCESS :
          √ should resolve with a (markdown) string extrapoled from target folder index file
    (node:183516) UnhandledPromiseRejectionWarning: AssertionError: expected promise to be fulfilled but it was rejected with 'Error: file not found'
    (node:183516) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 10)
    (node:183516) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Of course, expected outcome should be a failed test run, and something like this in the console :

SUCCESS :
         1) should resolve with a (markdown) string extrapoled from target folder index file:

      AssertionError: expected '1' to equal '2'

This strange behaviour even lead to (funny and) incoherent warnings.

Using promise.should.not.be.rejected, I got "expected promise not to be rejected but it was rejected" but test still passed :

SUCCESS :
      √ should resolve with a (markdown) string extrapoled from target folder index file
(node:225676) UnhandledPromiseRejectionWarning: AssertionError: expected promise not to be rejected but it was rejected with 'Error: file not found'

Actually my thoughts are that :

A solution would to increase the level of test fail to warnings, but I didn't found it in the chai-as-promised documentation.

Another solution would be to understand what layer is catching the Error/rejection, and is lowering it to a warning. Maybe a chai-as-promised default parameter ?

Body:
I initially was using chai-as-promised there was some issue with promises not being correctly awaited that lead to hours of debugging my tests.

In the end I rolled my own solution.

EDIT v2 - more concise

// test-utils.ts

import { expect } from "chai";

export const expectRejection = async (
  promise: Promise<any>,
  errMsg: string
): Promise<void> => {
  try {
    await promise;
  } catch (err) {
    expect(err.message).eq(errMsg);
    return;
  }
  throw Error('Promise was not rejected');
};

You can use the function like this in your tests

it('Function that fails', async () => {
  const errMsg = 'My example';
  const functionThatRejects = async () => {
    throw Error(errMsg);
  };
  await expectRejection(functionThatRejects(), errMsg);
});

And for completeness here is a unit test for the function.

import { expectRejection } from './test-utils';
import { expect } from 'chai';

describe('test-utils.ts', () => {
  describe('expectRejection(..)', () => {
    it('Function that fails', async () => {
      const errMsg = 'My example';
      const functionThatRejects = async () => {
        throw Error(errMsg);
      };
      await expectRejection(functionThatRejects(), errMsg);
    });

    it("Function that doesn't fail", async () => {
      const functionThatResolves = async () => null;
      try {
        await expectRejection(functionThatResolves(), "Random error message");
      } catch (err) {
        expect(err).match(/Promise was not rejected/);
        return;
      }
      throw Error('Should have already returned');
    });
  });
});

v1 - more flexable

// test-utils.ts

import { expect } from "chai";

export const expectRejection = async (promise: Promise<any>) => {
  try {
    await promise;
  } catch (err) {
    return expect(err);
  }
  throw Error('Promise was not rejected');
};

You can use the function like this in your tests

it('Function that fails', async () => {
  const functionThatRejects = async () => {
    throw Error('My example');
  };
  const rejection = await expectRejection(functionThatRejects());
  rejection.match(/My example/);
});

And for completeness here is a unit test for the function.

// test-utils.spec.ts

import { expectRejection } from './test-utils';
import { expect } from 'chai';

describe('expectRejection(..)', () => {
  it('Function that fails', async () => {
    const functionThatRejects = async () => {
      throw Error('My example');
    };
    const rejection = await expectRejection(functionThatRejects());
    rejection.match(/My example/);
  });

  it("Function that doesn't fail", async () => {
    const functionThatResolves = async () => null;
    try {
      await expectRejection(functionThatResolves());
    } catch (err) {
      expect(err).match(/Promise was not rejected/);
      return;
    }
    throw Error('Should have already returned');
  });
});


问:
Madge skips imported typescript file
I want to print a Javascript dependency graph using madge. It prints all dependencies of a given file successfully. Unfortunately, it skips the imported .ts files and subsequently does not show them in the graph.

Here is my config (.madgerc):

```<code>{
    "fileExtensions": ["js", "ts"],
    "tsConfig": "./tsconfig.json",
    "graphVizOptions": {
        "G": {
            "splines": "ortho"
        }
    }
}
</code>```

Here is my tsconfig.json:

```<code>{
  "compilerOptions": {
    "esModuleInterop": true,
    "allowJs": true,
    "preserveConstEnums": true,
    "module": "commonjs",
    "target": "ES2018",
    "moduleResolution": "node",
    "noEmit": true,
    "rootDir": "../"
  }
}
</code>```

I run madge like so:

```<code>madge src/main/path/to/file/view-model.js --warning --debug -i ~/Desktop/graph/view-model.png
</code>```

It prints:

```<code>✔ Image created at /Users/patrick/Desktop/graph/view-model.png

✖ Skipped 1 file

./transform-sponsor
</code>```

transform-sponsor is imported in my Javascript file like so:

```<code>const {transformSponsors} = require('./transform-sponsor');
</code>```

So my question is, why does madge skip my typescript file. Even though I specifically added a tsconfig file as explained in the documentation?

答: Just add --extensions ts to the runned script

Title: Madge skips imported typescript file

Body:
I want to print a Javascript dependency graph using madge. It prints all dependencies of a given file successfully. Unfortunately, it skips the imported .ts files and subsequently does not show them in the graph.

Here is my config (.madgerc):

{
    "fileExtensions": ["js", "ts"],
    "tsConfig": "./tsconfig.json",
    "graphVizOptions": {
        "G": {
            "splines": "ortho"
        }
    }
}

Here is my tsconfig.json:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "allowJs": true,
    "preserveConstEnums": true,
    "module": "commonjs",
    "target": "ES2018",
    "moduleResolution": "node",
    "noEmit": true,
    "rootDir": "../"
  }
}

I run madge like so:

madge src/main/path/to/file/view-model.js --warning --debug -i ~/Desktop/graph/view-model.png

It prints:

✔ Image created at /Users/patrick/Desktop/graph/view-model.png

✖ Skipped 1 file

./transform-sponsor

transform-sponsor is imported in my Javascript file like so:

const {transformSponsors} = require('./transform-sponsor');

So my question is, why does madge skip my typescript file. Even though I specifically added a tsconfig file as explained in the documentation?


问:
Redirect to last browser history location in React
I am working on my personal React project.
The React app has a login page. After successfully logging in, the user is redirected to homepage i.e. on path / . And if the user again tries to navigate to login page i.e.  path
/login , then the user will be redirected back to homepage

The app also has protected route on path /profile which is accessible only if the user is authenticated.

But the problem is, when the user navigates to protected route and then refreshes the page, it is redirecting to the  homepage.
How can I make it redirect back to the same protected route from where the user had refreshed?

Here is Login.js

```<code>// Login.js
      if (isUserLoggedIn) {
        return <Redirect to="/" />;
      }
      // else render login page
</code>```

And here is ProtectedRoute.js

```<code>import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { Redirect, Route } from "react-router";

export default function ProtectedRoute({ component: Component, ...rest }) {

  const { isUserLoggedIn } = useSelector((state) => state.common);

  return (
    <Route
      {...rest}
      render={(props) =>
        !isUserLoggedIn ? <Redirect to="/login" /> : <Component {...props} />
      }
    />
  );
}
</code>```

And this is how I'm getting the value of isUserLoggedIn  from cookies and then setting it to the Redux state.

```<code> const [authenticated] = useState(() =>
    Boolean(Number(Cookies.get("isUserLoggedIn")))
  );
  useEffect(() => {
    if (!authenticated) {
      return dispatch({
        type: NOT_AUTHENTICATED,
      });
    } else {
      return dispatch({
        type: AUTHENTICATED,
      });
    }
  }, [authenticated]);
</code>```

答:
It happened same with me. I have solved this problem by using a variable that will be in Local storage so when siging in also set localstorage variable  isLogged to true localStorage.setItem("isLogged", true) so in case he is already logged and refreshed the page the user will redirected to profile page.
The switch statement is used bacause we get string value from localstorage and we have to convert it to boolean

```<code>function App() {
  const token = localStorage.getItem("isLogged");
  let auth = null;
  switch (token) {
    case "true":
      auth = true;
      break;
    case "false":
      auth = false;
      break;

    default:
      break;
  }}
</code>```

as the code above you can now pass the variable auth to the component in protected route like this

```<code><PrivateRoute
          path="/main"
          component={Main}
          isAuthenticated={auth}
        ></PrivateRoute>
</code>```

and in the Private Route Component add the isAuthenticated props

```<code>const PrivateRoute = ({ component: Component, isAuthenticated, ...props }) => {
  return (
    <Route
      {...props}
      render={(props) =>
        isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
            }}
          />
        )
      }
    />
  );
};
</code>```

This is the Login Component

```<code>const Login = () => {
  const history = useHistory();

  async function onSubmit(data) {
    try {
      await signin(data.userName, data.password);
      localStorage.setItem("isLogged", true);
      toast.success("Registerd successfully");
      history.go("/main");
    } catch {
      toast.error("Error");
    }
  }

  return (
    <div className="form-container">
      <img src={Logo} alt="logo" className="logo-img"></img>
      <h1>Login to Your Account</h1>
      <Form onSubmit={onSubmit} className="form-items">
        {({ handleSubmit }) => (
          <form onSubmit={handleSubmit}>
            <Field name="userName">
              {({ input }) => (
                <TextField
                  name="userName"
                  type="input"
                  id="standard-basic"
                  label="user Name"
                  variant="standard"
                  fullWidth
                  {...input}
                />
              )}
            </Field>
            <Field name="password">
              {({ input }) => (
                <TextField
                  name="password"
                  type="password"
                  id="standard-basic"
                  label="Password"
                  variant="standard"
                  fullWidth
                  {...input}
                />
              )}
            </Field>
            <Button
              type="submit"
              sx={{
                width: "100%",
                backgroundColor: "rgba(56, 211, 159, 255)",
                marginTop: "40px",
                color: "white",
              }}
            >
              Login
            </Button>
            <div>
              Don't Have an Account <Link to="/register">Sign up</Link>
            </div>
          </form>
        )}
      </Form>
    </div>
  );
};
</code>```

Body:
I am working on my personal React project.
The React app has a login page. After successfully logging in, the user is redirected to homepage i.e. on path / . And if the user again tries to navigate to login page i.e.  path
/login , then the user will be redirected back to homepage

The app also has protected route on path /profile which is accessible only if the user is authenticated.

But the problem is, when the user navigates to protected route and then refreshes the page, it is redirecting to the  homepage.
How can I make it redirect back to the same protected route from where the user had refreshed?

Here is Login.js

// Login.js
      if (isUserLoggedIn) {
        return <Redirect to="/" />;
      }
      // else render login page

And here is ProtectedRoute.js

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { Redirect, Route } from "react-router";

export default function ProtectedRoute({ component: Component, ...rest }) {

  const { isUserLoggedIn } = useSelector((state) => state.common);

  return (
    <Route
      {...rest}
      render={(props) =>
        !isUserLoggedIn ? <Redirect to="/login" /> : <Component {...props} />
      }
    />
  );
}

And this is how I'm getting the value of isUserLoggedIn  from cookies and then setting it to the Redux state.

 const [authenticated] = useState(() =>
    Boolean(Number(Cookies.get("isUserLoggedIn")))
  );
  useEffect(() => {
    if (!authenticated) {
      return dispatch({
        type: NOT_AUTHENTICATED,
      });
    } else {
      return dispatch({
        type: AUTHENTICATED,
      });
    }
  }, [authenticated]);

Body:
It happened same with me. I have solved this problem by using a variable that will be in Local storage so when siging in also set localstorage variable  isLogged to true localStorage.setItem("isLogged", true) so in case he is already logged and refreshed the page the user will redirected to profile page.
The switch statement is used bacause we get string value from localstorage and we have to convert it to boolean

function App() {
  const token = localStorage.getItem("isLogged");
  let auth = null;
  switch (token) {
    case "true":
      auth = true;
      break;
    case "false":
      auth = false;
      break;

    default:
      break;
  }}

as the code above you can now pass the variable auth to the component in protected route like this

<PrivateRoute
          path="/main"
          component={Main}
          isAuthenticated={auth}
        ></PrivateRoute>

and in the Private Route Component add the isAuthenticated props

const PrivateRoute = ({ component: Component, isAuthenticated, ...props }) => {
  return (
    <Route
      {...props}
      render={(props) =>
        isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
            }}
          />
        )
      }
    />
  );
};

This is the Login Component

const Login = () => {
  const history = useHistory();

  async function onSubmit(data) {
    try {
      await signin(data.userName, data.password);
      localStorage.setItem("isLogged", true);
      toast.success("Registerd successfully");
      history.go("/main");
    } catch {
      toast.error("Error");
    }
  }

  return (
    <div className="form-container">
      <img src={Logo} alt="logo" className="logo-img"></img>
      <h1>Login to Your Account</h1>
      <Form onSubmit={onSubmit} className="form-items">
        {({ handleSubmit }) => (
          <form onSubmit={handleSubmit}>
            <Field name="userName">
              {({ input }) => (
                <TextField
                  name="userName"
                  type="input"
                  id="standard-basic"
                  label="user Name"
                  variant="standard"
                  fullWidth
                  {...input}
                />
              )}
            </Field>
            <Field name="password">
              {({ input }) => (
                <TextField
                  name="password"
                  type="password"
                  id="standard-basic"
                  label="Password"
                  variant="standard"
                  fullWidth
                  {...input}
                />
              )}
            </Field>
            <Button
              type="submit"
              sx={{
                width: "100%",
                backgroundColor: "rgba(56, 211, 159, 255)",
                marginTop: "40px",
                color: "white",
              }}
            >
              Login
            </Button>
            <div>
              Don't Have an Account <Link to="/register">Sign up</Link>
            </div>
          </form>
        )}
      </Form>
    </div>
  );
};


问:
BigTable schema design
Playing around with BigTable and trying to understand if my schema design has flaws.

We have thousands of sensors that are submitting data with different frequencies. Between once a second and every 15 seconds or slower.

My idea is to have sensorId:year-month as a row key, a static name "data" as the family and multiple columns to split the data in buckets of days for example.

So there should be no hotspotting, rows wont grow too large. Is there anything wrong with this approach? Im not sure, if creating those "1-10" and "16-31" columns makes sense, but having all data in one column doesnt feel right as well. Additionally having these "day-bucket" columns would help keeping column data below 10MB

UI-wise this data is usually queried like "show me the data for sensors A, B, C for the past 1 day, 1 week, 1 month".

答:
I think you schema design is correct according to the BigTable best practices.

Specially when it comes about what this documentation states about rows:

Don't store more than 100 MB of data in a single row. Rows that exceed this limit can result in reduced read performance.

Keep all information for an entity in a single row.

Store related entities in adjacent rows, to make reads more efficient.

Also regarding to columns you are following too the best practices by avoiding using too many columns in any single row.

Nonetheless once you have created your schema you can analyze it with the Key Visualizer which will help you to figure out it your performance is good.

Title: BigTable schema design


问:
IntelliJ gradle project error "Unsupported class file major version 61"
Hi All I am getting this error while build my gradle project, tried everything found online here How can I fix "unsupported class file major version 60" in IntelliJ IDEA?

checked java version and also gradle version .. still not bale to resolve the issue , I am not sure what I am doing wrong. here is the gradle setting in intelliJ

I have 3 Java version(17 , 11, 1.8) installed my in computer and I am using mac.
could anyone look and help what is wrong here.
Thanks in advance.:)
stacktrace:

```<code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':ess-all:buildSrc:compileGroovy'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:200)
    at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:263)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:198)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:179)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:109)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:41)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:372)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:359)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:352)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:338)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
Caused by: BUG! exception in phase 'semantic analysis' in source unit 'buildSrc/src/main/groovy/DependencyVersionsPlugin.groovy' Unsupported class file major version 61
    at org.gradle.api.internal.tasks.compile.ApiGroovyCompiler.execute(ApiGroovyCompiler.java:277)
    at org.gradle.api.internal.tasks.compile.ApiGroovyCompiler.execute(ApiGroovyCompiler.java:67)
    at org.gradle.api.internal.tasks.compile.GroovyCompilerFactory$DaemonSideCompiler.execute(GroovyCompilerFactory.java:98)
    at org.gradle.api.internal.tasks.compile.GroovyCompilerFactory$DaemonSideCompiler.execute(GroovyCompilerFactory.java:77)
    at org.gradle.api.internal.tasks.compile.daemon.AbstractDaemonCompiler$CompilerWorkAction.execute(AbstractDaemonCompiler.java:135)
    at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:63)
    at org.gradle.workers.internal.AbstractClassLoaderWorker$1.create(AbstractClassLoaderWorker.java:49)
    at org.gradle.workers.internal.AbstractClassLoaderWorker$1.create(AbstractClassLoaderWorker.java:43)
    at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:97)
    at org.gradle.workers.internal.AbstractClassLoaderWorker.executeInClassLoader(AbstractClassLoaderWorker.java:43)
    at org.gradle.workers.internal.IsolatedClassloaderWorker.run(IsolatedClassloaderWorker.java:49)
    at org.gradle.workers.internal.IsolatedClassloaderWorker.run(IsolatedClassloaderWorker.java:30)
    at org.gradle.workers.internal.WorkerDaemonServer.run(WorkerDaemonServer.java:85)
    at org.gradle.workers.internal.WorkerDaemonServer.run(WorkerDaemonServer.java:55)
    at org.gradle.process.internal.worker.request.WorkerAction$1.call(WorkerAction.java:138)
    at org.gradle.process.internal.worker.child.WorkerLogEventListener.withWorkerLoggingProtocol(WorkerLogEventListener.java:41)
    at org.gradle.process.internal.worker.request.WorkerAction.run(WorkerAction.java:135)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
Caused by: java.lang.IllegalArgumentException: Unsupported class file major version 61
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:196)
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:177)
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:163)
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:284)
    ... 28 more
</code>```

I solved the problem by removing java 17 from my computer .. but don't want to remove the java 17 version and still want to compile my code

答:
Use Java 17 instead of Java 11.

Reference: List of Java class file format major version numbers?

https://docs.oracle.com/javase/specs/jvms/se17/html/jvms-4.html#jvms-4.1-200-B.2

Body:
Hi All I am getting this error while build my gradle project, tried everything found online here How can I fix "unsupported class file major version 60" in IntelliJ IDEA?

checked java version and also gradle version .. still not bale to resolve the issue , I am not sure what I am doing wrong. here is the gradle setting in intelliJ

I have 3 Java version(17 , 11, 1.8) installed my in computer and I am using mac.
could anyone look and help what is wrong here.
Thanks in advance.:)
stacktrace:

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':ess-all:buildSrc:compileGroovy'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:200)
    at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:263)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:198)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:179)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:109)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:41)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:372)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:359)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:352)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:338)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
Caused by: BUG! exception in phase 'semantic analysis' in source unit 'buildSrc/src/main/groovy/DependencyVersionsPlugin.groovy' Unsupported class file major version 61
    at org.gradle.api.internal.tasks.compile.ApiGroovyCompiler.execute(ApiGroovyCompiler.java:277)
    at org.gradle.api.internal.tasks.compile.ApiGroovyCompiler.execute(ApiGroovyCompiler.java:67)
    at org.gradle.api.internal.tasks.compile.GroovyCompilerFactory$DaemonSideCompiler.execute(GroovyCompilerFactory.java:98)
    at org.gradle.api.internal.tasks.compile.GroovyCompilerFactory$DaemonSideCompiler.execute(GroovyCompilerFactory.java:77)
    at org.gradle.api.internal.tasks.compile.daemon.AbstractDaemonCompiler$CompilerWorkAction.execute(AbstractDaemonCompiler.java:135)
    at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:63)
    at org.gradle.workers.internal.AbstractClassLoaderWorker$1.create(AbstractClassLoaderWorker.java:49)
    at org.gradle.workers.internal.AbstractClassLoaderWorker$1.create(AbstractClassLoaderWorker.java:43)
    at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:97)
    at org.gradle.workers.internal.AbstractClassLoaderWorker.executeInClassLoader(AbstractClassLoaderWorker.java:43)
    at org.gradle.workers.internal.IsolatedClassloaderWorker.run(IsolatedClassloaderWorker.java:49)
    at org.gradle.workers.internal.IsolatedClassloaderWorker.run(IsolatedClassloaderWorker.java:30)
    at org.gradle.workers.internal.WorkerDaemonServer.run(WorkerDaemonServer.java:85)
    at org.gradle.workers.internal.WorkerDaemonServer.run(WorkerDaemonServer.java:55)
    at org.gradle.process.internal.worker.request.WorkerAction$1.call(WorkerAction.java:138)
    at org.gradle.process.internal.worker.child.WorkerLogEventListener.withWorkerLoggingProtocol(WorkerLogEventListener.java:41)
    at org.gradle.process.internal.worker.request.WorkerAction.run(WorkerAction.java:135)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
Caused by: java.lang.IllegalArgumentException: Unsupported class file major version 61
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:196)
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:177)
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:163)
    at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:284)
    ... 28 more

I solved the problem by removing java 17 from my computer .. but don't want to remove the java 17 version and still want to compile my code


问:
vite replace an import statement
I have a vue file

```<code>// myComponent.vue
import { something } from 'some-module'
...
</code>```

I want to replace this import statement into

```<code>import { something } from '@/utils/myModule'
</code>```

in case when running the vitest command.
Do we have some plugin which I can use to get the above result?

答:
you can use jsconfig.json file to achieve this.</p>
```<code>{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/utils/*": ["componentpath/*"],
    }
  }
}
</code>```

Title: vite replace an import statement

Body:
I have a vue file

// myComponent.vue
import { something } from 'some-module'
...

I want to replace this import statement into

import { something } from '@/utils/myModule'

in case when running the vitest command.
Do we have some plugin which I can use to get the above result?

Body:
you can use jsconfig.json file to achieve this.

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/utils/*": ["componentpath/*"],
    }
  }
}


问:
How to subset R data frame based on duplicates in one column and unique values in another
This seems pretty straightforward but I am stumped. I have a data frame that looks like this:

```<code>df1 %>% head()
  values  paired
  <ch>     <int>
1 apples      1
2 x           1
3 oranges     2
4 z           2
5 bananas     3
6 y           3
7 apples      4
8 p           4

</code>```

I would like to create a new data frame that extracts all paired values based on a search criteria. So if I want all pairs that correspond to apples I would like to end up with something like this:

```<code>df1 %>% head()
  values  paired
  <ch>     <int>
1 apples      1
2 x           1
3 apples      4
4 p           4
</code>```

I have tried using:

```<code>new_pairs <- df1 %>%
  arrange(values, paired) %>%
  filter(duplicated(paired) == TRUE,
         values=="apples")
</code>```

But I am getting only the apple rows back

答:
In base R, find the values of the pairs of interest

```<code>pairs = subset(df1, values %in% "apples")$paired
</code>```

and create a subset of the data

```<code>subset(df1, paired %in% pairs)
</code>```

Body:
This seems pretty straightforward but I am stumped. I have a data frame that looks like this:

df1 %>% head()
  values  paired
  <ch>     <int>
1 apples      1
2 x           1
3 oranges     2
4 z           2
5 bananas     3
6 y           3
7 apples      4
8 p           4

I would like to create a new data frame that extracts all paired values based on a search criteria. So if I want all pairs that correspond to apples I would like to end up with something like this:

df1 %>% head()
  values  paired
  <ch>     <int>
1 apples      1
2 x           1
3 apples      4
4 p           4

I have tried using:

new_pairs <- df1 %>%
  arrange(values, paired) %>%
  filter(duplicated(paired) == TRUE,
         values=="apples")

But I am getting only the apple rows back

Body:
In base R, find the values of the pairs of interest

pairs = subset(df1, values %in% "apples")$paired

and create a subset of the data

subset(df1, paired %in% pairs)


问:
How to read json file with node.js using P5.js
I just want the word "flower" to show up

I have test terminal for Node and using the preload() and loadJSON(), it work just fine but the word flower not show up, meaning the "js file" does not run on "json file", but the terminal said on console it work for node(meaning it read the json file on terminal)

How do I debug this?

The below is what I use for learning and working on this project
>

The Coding Train

10.2: What is JSON? Part I - p5.js Tutorial
https://www.youtube.com/watch?v=_NFkzw6oFtQ

8.5: Saving Data to JSON File with Node.js - Programming with Text
https://www.youtube.com/watch?v=6iZiqQZBQJY

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">

```
</div>
</div>
</p>
<p><strong>infoJSON5.js</strong></p>

<pre class="lang-js prettyprint-override"><code>//var flower;

//function preload() {
//    flower = loadJSON("Data3.json")
    var fs = require('fs');
    var data = fs.readFileSync('Data3.json');
    var flower = JSON.parse(data);
    console.log(flower);
//}
    //Test Terminal
  /*
  node infoJSON5.js
  */

function setup() {
    createCanvas(400, 400);
}

  function draw() {
    background(0);

    fill(flower.r, flower.g, flower.b);
    text(flower.name, 10, 50);
  }

</code>```

Data3.json

```<code>    {
"name":"sunflower",
"r":255,
"g":200,
"b":0
}
</code>```

答:
JavaScript itself doesn't do input/output. If you want to read a JSON file you need to use an API provided by the host environment. Different host environments provide different APIs.

If the host environment is Node.js then, as you've found, you can use the fs module.

Web browsers are different. There would be major security problems if any webpage you visited could read files (specified by the JS code) from the user's disk.

In a web browser, you can use Ajax to fetch data from a URL. So you can host your JSON on a web server (usually alongside the webpage) and read it from there. MSN has a tutorial on Using Fetch for Ajax.

You can also use a file <input> and have the user select a JSON from file their hard disk (giving permission to read it) and then use the FileReader API.

Body:
I just want the word "flower" to show up

I have test terminal for Node and using the preload() and loadJSON(), it work just fine but the word flower not show up, meaning the "js file" does not run on "json file", but the terminal said on console it work for node(meaning it read the json file on terminal)

How do I debug this?

The below is what I use for learning and working on this project
>

The Coding Train

10.2: What is JSON? Part I - p5.js Tutorial
https://www.youtube.com/watch?v=_NFkzw6oFtQ

8.5: Saving Data to JSON File with Node.js - Programming with Text
https://www.youtube.com/watch?v=6iZiqQZBQJY

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">

infoJSON5.js

//var flower;

//function preload() {
//    flower = loadJSON("Data3.json")
    var fs = require('fs');
    var data = fs.readFileSync('Data3.json');
    var flower = JSON.parse(data);
    console.log(flower);
//}
    //Test Terminal
  /*
  node infoJSON5.js
  */

function setup() {
    createCanvas(400, 400);
}

  function draw() {
    background(0);

    fill(flower.r, flower.g, flower.b);
    text(flower.name, 10, 50);
  }

Data3.json

    {
"name":"sunflower",
"r":255,
"g":200,
"b":0
}


问:
jQuery, new line and enter button
I'm using following code for textarea:

```<code>$('#ajaxSendMessage').live('keyup', function(event) {
    if (event.keyCode == 13) {
        controller.sendMessage($(this).val(), $("#ajaxAnswerTo").val());
    }
});
</code>```

This code works, but $("#ajaxAnswerTo").val() have new line characte when I click enter...
For example: I entered: helo world and then moved cursor to helo world, updated it to hello and clicked enter. The result code will be: hell\no world.

How to remove this \n?

答:
I think you want to catch it on keydown

see it working here on jsfiddle

If you want to go the regex route, you can simply use

```<code>$("#ajaxAnswerTo").val().replace(/\r?\n/, '');
</code>```

Title: jQuery, new line and enter button

Body:
I'm using following code for textarea:

$('#ajaxSendMessage').live('keyup', function(event) {
    if (event.keyCode == 13) {
        controller.sendMessage($(this).val(), $("#ajaxAnswerTo").val());
    }
});

This code works, but $("#ajaxAnswerTo").val() have new line characte when I click enter...
For example: I entered: helo world and then moved cursor to helo world, updated it to hello and clicked enter. The result code will be: hell\no world.

How to remove this \n?

Body:
I think you want to catch it on keydown

see it working here on jsfiddle

If you want to go the regex route, you can simply use

$("#ajaxAnswerTo").val().replace(/\r?\n/, '');


问:
How to Mock HttpClient using NSubstitute
I am trying to use NSubstitute to mock HttpClient. Here's the code:

```<code>public static HttpClient GetHttpClient(bool isSucess = true, string methodType = "GET")
        {
            var mockIHttpMessageHandler = Substitute.For<IMockHttpMessageHandler>();
            var mockHttpMessageHandler = Substitute.For<MockHttpMessageHandler>(mockIHttpMessageHandler);
            var httpResponse = Substitute.For<HttpResponseMessage>();
            httpResponse.Content = new StringContent("\"test\"");
            if (isSucess)
                httpResponse.StatusCode = HttpStatusCode.OK;
            else
                httpResponse.StatusCode = HttpStatusCode.NotFound;

            var mockHttpClient = Substitute.For<HttpClient>(mockHttpMessageHandler);
            mockHttpClient.BaseAddress = new Uri("http://localhost");

            if(methodType != "POST"){
                mockHttpClient.GetAsync(Arg.Any<Uri>()).ReturnsForAnyArgs(httpResponse);
            }
            return mockHttpClient;
        }
</code>```

However, I got an error at this line:

```<code>mockHttpClient.GetAsync(Arg.Any<Uri>()).ReturnsForAnyArgs(httpResponse);
</code>```

And the error is

NSubstitute.Exceptions.RedundantArgumentMatcherException: 'Some
argument specifications (e.g. Arg.Is, Arg.Any) were left over after
the last call.

This is often caused by using an argument spec with a call to a member
NSubstitute does not handle (such as a non-virtual member or a call to
an instance which is not a substitute), or for a purpose other than
specifying a call (such as using an arg spec as a return value). For
example:

```<code>var sub = Substitute.For<SomeClass>();
var realType = new MyRealType(sub);
// INCORRECT, arg spec used on realType, not a substitute:
realType.SomeMethod(Arg.Any<int>()).Returns(2);
// INCORRECT, arg spec used as a return value, not to specify a call:
sub.VirtualMethod(2).Returns(Arg.Any<int>());
// INCORRECT, arg spec used with a non-virtual method:
sub.NonVirtualMethod(Arg.Any<int>()).Returns(2);
// CORRECT, arg spec used to specify virtual call on a substitute:
sub.VirtualMethod(Arg.Any<int>()).Returns(2);
</code>```

To fix this make sure you only use argument specifications with calls
to substitutes. If your substitute is a class, make sure the member is
virtual.

Another possible cause is that the argument spec type does not match
the actual argument type, but code compiles due to an implicit cast.
For example, Arg.Any() was used, but Arg.Any() was
required.

NOTE: the cause of this exception can be in a previously executed
test. Use the diagnostics below to see the types of any redundant arg
specs, then work out where they are being created.

Diagnostic information:

Remaining (non-bound) argument specifications:
any Uri

All argument specifications:
any Uri

Are they suggesting I need to change the getAsync method? There's no virtual method for GetAsync

Edit:

I have also tried to remove NSubstitute for HttpClient as follows, but I still got the same error:

```<code>public static HttpClient GetHttpClient(bool isSucess = true, string methodType = "GET")
            {
                var mockIHttpMessageHandler = Substitute.For<IMockHttpMessageHandler>();
                var mockHttpMessageHandler = Substitute.For<MockHttpMessageHandler>(mockIHttpMessageHandler);
                var httpResponse = Substitute.For<HttpResponseMessage>();
                httpResponse.Content = new StringContent("\"test\"");
                if (isSucess)
                    httpResponse.StatusCode = HttpStatusCode.OK;
                else
                    httpResponse.StatusCode = HttpStatusCode.NotFound;

                 var httpClient = new HttpClient(mockHttpMessageHandler);
                httpClient = new Uri("http://localhost");

                if(methodType != "POST"){
                    httpClient .GetAsync(Arg.Any<Uri>()).ReturnsForAnyArgs(httpResponse);
                }
                return httpClient
            }
</code>```

答:
I appreciate this is an old(ish) question, but it's at the top of the Google Search results for "c# mock httpclient using nsubstitute" today, so I figured an answer would be useful.

First we need to create a mock implemenation of HttpMessageHandler. As you can see, we're overriding the protected SendAsync() method and exposing its body via our public Send() method.

```<code>public class MockHttpMessageHandler : HttpMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Send(request, cancellationToken);
    }

    public virtual Task<HttpResponseMessage> Send(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}
</code>```

Next we need to set up our mocks. Note that I'm using Substitute.ForPartsOf<T> instead of Substitute.For<T>.

```<code>var mockHttpMessageHandler = Substitute.ForPartsOf<MockHttpMessageHandler>();
var httpClient = new HttpClient(mockHttpMessageHandler);
</code>```

Finally, we can now use NSubstitute to intercept the call to Send() on our handler, which is called by the HttpClient for every request, and return our mocked HttpResponseMessage back via the client.

```<code>var mockResponse = new HttpResponseMessage(HttpStatusCode.OK);

mockHttpMessageHandler.Send(Arg.Any<AnyHttpRequestMessage>(), Arg.Any<CancellationToken>())
   .Returns(mockResponse);

var result = await httpClient.GetAsync<string>("https://tempuri.org");
</code>```

Edit for .NET 6

As .NET 6 introduces a protected virtual Send() method to the HttpMessageHandler class (which will also need overriding if you're using the synchronous HttpClient calls), some modifications are required to our MockHttpMessageHandler:

```<code>public class MockHttpMessageHandler : HttpMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(MockSend(request, cancellationToken));
    }

    protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return MockSend(request, cancellationToken);
    }

    public virtual HttpResponseMessage MockSend(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}
</code>```

Body:
I am trying to use NSubstitute to mock HttpClient. Here's the code:

public static HttpClient GetHttpClient(bool isSucess = true, string methodType = "GET")
        {
            var mockIHttpMessageHandler = Substitute.For<IMockHttpMessageHandler>();
            var mockHttpMessageHandler = Substitute.For<MockHttpMessageHandler>(mockIHttpMessageHandler);
            var httpResponse = Substitute.For<HttpResponseMessage>();
            httpResponse.Content = new StringContent("\"test\"");
            if (isSucess)
                httpResponse.StatusCode = HttpStatusCode.OK;
            else
                httpResponse.StatusCode = HttpStatusCode.NotFound;

            var mockHttpClient = Substitute.For<HttpClient>(mockHttpMessageHandler);
            mockHttpClient.BaseAddress = new Uri("http://localhost");

            if(methodType != "POST"){
                mockHttpClient.GetAsync(Arg.Any<Uri>()).ReturnsForAnyArgs(httpResponse);
            }
            return mockHttpClient;
        }

However, I got an error at this line:

mockHttpClient.GetAsync(Arg.Any<Uri>()).ReturnsForAnyArgs(httpResponse);

And the error is

NSubstitute.Exceptions.RedundantArgumentMatcherException: 'Some
argument specifications (e.g. Arg.Is, Arg.Any) were left over after
the last call.

This is often caused by using an argument spec with a call to a member
NSubstitute does not handle (such as a non-virtual member or a call to
an instance which is not a substitute), or for a purpose other than
specifying a call (such as using an arg spec as a return value). For
example:

var sub = Substitute.For<SomeClass>();
var realType = new MyRealType(sub);
// INCORRECT, arg spec used on realType, not a substitute:
realType.SomeMethod(Arg.Any<int>()).Returns(2);
// INCORRECT, arg spec used as a return value, not to specify a call:
sub.VirtualMethod(2).Returns(Arg.Any<int>());
// INCORRECT, arg spec used with a non-virtual method:
sub.NonVirtualMethod(Arg.Any<int>()).Returns(2);
// CORRECT, arg spec used to specify virtual call on a substitute:
sub.VirtualMethod(Arg.Any<int>()).Returns(2);

To fix this make sure you only use argument specifications with calls
to substitutes. If your substitute is a class, make sure the member is
virtual.

Another possible cause is that the argument spec type does not match
the actual argument type, but code compiles due to an implicit cast.
For example, Arg.Any() was used, but Arg.Any() was
required.

NOTE: the cause of this exception can be in a previously executed
test. Use the diagnostics below to see the types of any redundant arg
specs, then work out where they are being created.

Diagnostic information:

Remaining (non-bound) argument specifications:
any Uri

All argument specifications:
any Uri

Are they suggesting I need to change the getAsync method? There's no virtual method for GetAsync

Edit:

I have also tried to remove NSubstitute for HttpClient as follows, but I still got the same error:

public static HttpClient GetHttpClient(bool isSucess = true, string methodType = "GET")
            {
                var mockIHttpMessageHandler = Substitute.For<IMockHttpMessageHandler>();
                var mockHttpMessageHandler = Substitute.For<MockHttpMessageHandler>(mockIHttpMessageHandler);
                var httpResponse = Substitute.For<HttpResponseMessage>();
                httpResponse.Content = new StringContent("\"test\"");
                if (isSucess)
                    httpResponse.StatusCode = HttpStatusCode.OK;
                else
                    httpResponse.StatusCode = HttpStatusCode.NotFound;

                 var httpClient = new HttpClient(mockHttpMessageHandler);
                httpClient = new Uri("http://localhost");

                if(methodType != "POST"){
                    httpClient .GetAsync(Arg.Any<Uri>()).ReturnsForAnyArgs(httpResponse);
                }
                return httpClient
            }

Body:
I appreciate this is an old(ish) question, but it's at the top of the Google Search results for "c# mock httpclient using nsubstitute" today, so I figured an answer would be useful.

First we need to create a mock implemenation of HttpMessageHandler. As you can see, we're overriding the protected SendAsync() method and exposing its body via our public Send() method.

public class MockHttpMessageHandler : HttpMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Send(request, cancellationToken);
    }

    public virtual Task<HttpResponseMessage> Send(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}

Next we need to set up our mocks. Note that I'm using Substitute.ForPartsOf<T> instead of Substitute.For<T>.

var mockHttpMessageHandler = Substitute.ForPartsOf<MockHttpMessageHandler>();
var httpClient = new HttpClient(mockHttpMessageHandler);

Finally, we can now use NSubstitute to intercept the call to Send() on our handler, which is called by the HttpClient for every request, and return our mocked HttpResponseMessage back via the client.

var mockResponse = new HttpResponseMessage(HttpStatusCode.OK);

mockHttpMessageHandler.Send(Arg.Any<AnyHttpRequestMessage>(), Arg.Any<CancellationToken>())
   .Returns(mockResponse);

var result = await httpClient.GetAsync<string>("https://tempuri.org");

Edit for .NET 6

As .NET 6 introduces a protected virtual Send() method to the HttpMessageHandler class (which will also need overriding if you're using the synchronous HttpClient calls), some modifications are required to our MockHttpMessageHandler:

public class MockHttpMessageHandler : HttpMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(MockSend(request, cancellationToken));
    }

    protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return MockSend(request, cancellationToken);
    }

    public virtual HttpResponseMessage MockSend(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}