问:
CameraX can't initialize
I try to use CameraView. And I'm a beginner in Android. I read some articles and information on class but I am not able to make it works.
I have the following errors :

Caused by: java.lang.IllegalStateException: CameraX is not initialized properly. Either CameraX.initialize() needs to have been called or the CameraXConfig.Provider interface must be implemented by your Application class

Here is my code :

activity_main.xml

```<code>   <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:theme="@style/AppTheme">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.camera.view.CameraView
    android:id="@+id/view_camera"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

MainActivity.java:

```<code>    package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.camera2.Camera2Config;
import androidx.camera.core.CameraX;
import androidx.camera.core.CameraXConfig;
import androidx.camera.core.impl.CameraFactory;
import androidx.camera.core.impl.PreviewConfig;
import androidx.camera.view.CameraView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements CameraXConfig.Provider {

    private CameraView view_camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view_camera = findViewById(R.id.view_camera);
        view_camera.bindToLifecycle(this);
    }

    @NonNull
    @Override
    public CameraXConfig getCameraXConfig() {
        return Camera2Config.defaultConfig();
    }
}
</code>```

And the manifest :

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.CAMERA" />

<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/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

The gradle file for app:

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.1"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 26
        targetSdkVersion 29
        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 fileTree(dir: 'libs', include: ['*.jar'])
    def camerax_version = "1.0.0-alpha10"// Add the CameraX core dependency implementation
    implementation "androidx.camera:camera-core:${camerax_version}"// Add the CameraX Camera2 API interop support dependency
    implementation "androidx.camera:camera-camera2:${camerax_version}"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation "androidx.camera:camera-view:1.0.0-alpha06"
    // If you want to use the CameraX Extensions library
    implementation "androidx.camera:camera-extensions:1.0.0-alpha06"
    // If you want to use the CameraX Lifecycle library
    implementation "androidx.camera:camera-lifecycle:1.0.0-alpha03"
}
</code>```

Thanks for your help.

答:
Non of all this suggestion doesn't help me. My PreviewView was on Fragment not in Activity.

In my case I have to add class MyApplication which implements CameraXConfig.Provider

```<code>public class MyApp extends Application implements CameraXConfig.Provider {
@Override
public CameraXConfig getCameraXConfig() {
    return CameraXConfig.Builder.fromConfig(Camera2Config.defaultConfig())
            //.setCameraExecutor(myExecutor)
            //.setSchedulerHandler(mySchedulerHandler)
            .build();
}
</code>```

}

Next thing I got to do it was to change from getInstance(this) to:

```<code>cameraProviderFuture = ProcessCameraProvider.getInstance(getActivity().getApplicationContext());
</code>```

Full code:

```<code>private void startCamera() {
    Log.d(TAG, "startCamera: starting camera");
    cameraProviderFuture = ProcessCameraProvider.getInstance(getActivity().getApplicationContext());
    cameraProviderFuture.addListener(() -> {
        try {
            ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
            bindCameraPreview(cameraProvider);
        } catch (ExecutionException | InterruptedException e)
            Log.e(TAG, "startCamera: Error during starting camera", e);
        }
    }, ContextCompat.getMainExecutor(requireContext()));
}

private void bindCameraPreview(@NonNull ProcessCameraProvider cameraProvider) {
    Log.d(TAG, "bindCameraPreview: start");
    previewView.setImplementationMode(PreviewView.ImplementationMode.PERFORMANCE);

    Preview preview = new Preview.Builder()
            .build();

    preview.setSurfaceProvider(previewView.getSurfaceProvider());

    CameraSelector cameraSelector = new CameraSelector.Builder()
            .requireLensFacing(CameraSelector.LENS_FACING_BACK)
            .build();

    Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector, preview);
}
</code>```

Title: CameraX can't initialize

Body:
I try to use CameraView. And I'm a beginner in Android. I read some articles and information on class but I am not able to make it works.
I have the following errors :

Caused by: java.lang.IllegalStateException: CameraX is not initialized properly. Either CameraX.initialize() needs to have been called or the CameraXConfig.Provider interface must be implemented by your Application class

Here is my code :

activity_main.xml

   <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:theme="@style/AppTheme">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.camera.view.CameraView
    android:id="@+id/view_camera"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

MainActivity.java:

    package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.camera2.Camera2Config;
import androidx.camera.core.CameraX;
import androidx.camera.core.CameraXConfig;
import androidx.camera.core.impl.CameraFactory;
import androidx.camera.core.impl.PreviewConfig;
import androidx.camera.view.CameraView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements CameraXConfig.Provider {

    private CameraView view_camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view_camera = findViewById(R.id.view_camera);
        view_camera.bindToLifecycle(this);
    }

    @NonNull
    @Override
    public CameraXConfig getCameraXConfig() {
        return Camera2Config.defaultConfig();
    }
}

And the manifest :

<?xml version="1.0" encoding="utf-8"?>

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

<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/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

The gradle file for app:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.1"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 26
        targetSdkVersion 29
        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 fileTree(dir: 'libs', include: ['*.jar'])
    def camerax_version = "1.0.0-alpha10"// Add the CameraX core dependency implementation
    implementation "androidx.camera:camera-core:${camerax_version}"// Add the CameraX Camera2 API interop support dependency
    implementation "androidx.camera:camera-camera2:${camerax_version}"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation "androidx.camera:camera-view:1.0.0-alpha06"
    // If you want to use the CameraX Extensions library
    implementation "androidx.camera:camera-extensions:1.0.0-alpha06"
    // If you want to use the CameraX Lifecycle library
    implementation "androidx.camera:camera-lifecycle:1.0.0-alpha03"
}

Thanks for your help.

Body:
Non of all this suggestion doesn't help me. My PreviewView was on Fragment not in Activity.

In my case I have to add class MyApplication which implements CameraXConfig.Provider

public class MyApp extends Application implements CameraXConfig.Provider {
@Override
public CameraXConfig getCameraXConfig() {
    return CameraXConfig.Builder.fromConfig(Camera2Config.defaultConfig())
            //.setCameraExecutor(myExecutor)
            //.setSchedulerHandler(mySchedulerHandler)
            .build();
}

}

Next thing I got to do it was to change from getInstance(this) to:

cameraProviderFuture = ProcessCameraProvider.getInstance(getActivity().getApplicationContext());

Full code:

private void startCamera() {
    Log.d(TAG, "startCamera: starting camera");
    cameraProviderFuture = ProcessCameraProvider.getInstance(getActivity().getApplicationContext());
    cameraProviderFuture.addListener(() -> {
        try {
            ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
            bindCameraPreview(cameraProvider);
        } catch (ExecutionException | InterruptedException e)
            Log.e(TAG, "startCamera: Error during starting camera", e);
        }
    }, ContextCompat.getMainExecutor(requireContext()));
}

private void bindCameraPreview(@NonNull ProcessCameraProvider cameraProvider) {
    Log.d(TAG, "bindCameraPreview: start");
    previewView.setImplementationMode(PreviewView.ImplementationMode.PERFORMANCE);

    Preview preview = new Preview.Builder()
            .build();

    preview.setSurfaceProvider(previewView.getSurfaceProvider());

    CameraSelector cameraSelector = new CameraSelector.Builder()
            .requireLensFacing(CameraSelector.LENS_FACING_BACK)
            .build();

    Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector, preview);
}


来源: stackexchange

问:
How to test button click on jest/enzyme without props
I want to test is the button clicked and some actions happens but I fail the test and receive 0 number of calls when clicked. Im not passing onclick function from props.
I'm using materialUi Button

```<code>const LoginFunction = () => {

  const handleClick = () => {
    console.log('some action here')
  };

  return (
    <Button
        data-test="btn"
        className='btn'
        onClick={() => {
            handleClick();
        }}
    >
       Some text
    </Button>
 )};
</code>```

I wrote test like this

```<code>describe('Test Login component', () => {

  it('should trigger click event', () => {
    const mockCallBack = jest.fn();
    const wrapper = shallow(<LoginFunction />);

    wrapper.simulate('click');
    expect(mockCallBack.mock.calls.length).toBe(1);
   });
 });
</code>```

Tried this way too

```<code> describe('Test Login component', () => {

  it('should trigger click event', () => {
    const mockCallBack = jest.fn();
    const wrapper = shallow(<LoginFunction />);

    wrapper.find('.btn').simulate('click');
    expect(mockCallBack.mock.calls.length).toBe(1);
   });
 });
</code>```

答:
```<code>**Also in the main component you can directly call the handler in onclick like this**

     <Button
            data-test="btn"
            className='btn'
            onClick={handleClick}
        >
           Some text
        </Button>

describe('Test Login component', () => {

  it('should trigger click event', () => {
  const wrapper=mount( <LoginFunction />);
    const result=wrapper.find('button').simulate('click')
   expect(result).toBe('some action here')
 });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to test is the button clicked and some actions happens but I fail the test and receive 0 number of calls when clicked. Im not passing onclick function from props.
I'm using materialUi Button

const LoginFunction = () => {

  const handleClick = () => {
    console.log('some action here')
  };

  return (
    <Button
        data-test="btn"
        className='btn'
        onClick={() => {
            handleClick();
        }}
    >
       Some text
    </Button>
 )};

I wrote test like this

describe('Test Login component', () => {

  it('should trigger click event', () => {
    const mockCallBack = jest.fn();
    const wrapper = shallow(<LoginFunction />);

    wrapper.simulate('click');
    expect(mockCallBack.mock.calls.length).toBe(1);
   });
 });

Tried this way too

 describe('Test Login component', () => {

  it('should trigger click event', () => {
    const mockCallBack = jest.fn();
    const wrapper = shallow(<LoginFunction />);

    wrapper.find('.btn').simulate('click');
    expect(mockCallBack.mock.calls.length).toBe(1);
   });
 });


问:
DB2 to Snowflake Migration - SQL: Deriving a result table using 'values' clause
We are migrating off DB2 to Snowflake, and we have run into an issue with a lack of scope when using the 'values' clause.  DB2 scope extends to all tables within the select query; while Snowflake is limited to that within the clause:

Valid in DB2:

```<code>select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2
</code>```

Not valid in Snowflake (slightly different syntax - remove 'table'):

```<code>select * from
t_1
join

(values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2
</code>```

This throws an error saying "...t_1 is undefined".

Does anyone know of an equivalent capability in Snowflake?

For some context:  This construct sits behind a well embedded process for our business, and to rework it would mean significant investment.

It forms the basis for a dynamic ETL query which is passed into an ADF pipeline.  There is a frontend which deploys components into this query - this deployable piece needs to be kept as simple as possible.  It is the equivalent to the "(t_1.c1, ‘foo’)" line, so ideally any solution would keep this piece the same.

EDIT:

For some additional context...

In the example above, we have a placeholder which identifies the insert point of newly deployed items from the front end, like this:

```<code>select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
/*client_X_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

union

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
,(t_1.c2, 'barfoo')
/*client_Y_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2
</code>```

We are pulling a series of metrics associated with clients, where the label is t_2.c2 and the result is t2.c1.  This is still highly simplified relative to the real world.  We need a simple way to update the placeholder with a new metric and its calculation - t2.c1 may be wrapped in a pile of functions and/or reside inside case statements, etc.

答:
Lennart deserve this one, his code is so close

```<code>WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select *
from t_1
join lateral (values
    (t_1.c1, 'foo'),
    (t_1.c1, 'bar')
    )  as t_2(c1,c2)
    on t_1.c5 = t_2.c2;
</code>```

but that causes an internal error:

000603 (XX000): SQL execution internal error:
Processing aborted due to error 300002:4143448929; incident 4919401.

But if you put a SELECT * FROM in there:

```<code>WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select *
from t_1
join lateral (select * from values
    (t_1.c1, 'foo'),
    (t_1.c1, 'bar')
    ) as t_2(c1,c2)
    on t_1.c5 = t_2.c2;
</code>```

it works:

C1
C5
C1
C2

a
bar
a
bar

Lenart's try more brackets works also:

```<code>WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select *
from t_1
join lateral (
    select * from (
        values
        (t_1.c1, 'foo'),
        (t_1.c1, 'bar')
    )
) as t_2(c1,c2)
    on t_1.c5 = t_2.c2;

</code>```

Body:
We are migrating off DB2 to Snowflake, and we have run into an issue with a lack of scope when using the 'values' clause.  DB2 scope extends to all tables within the select query; while Snowflake is limited to that within the clause:

Valid in DB2:

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

Not valid in Snowflake (slightly different syntax - remove 'table'):

select * from
t_1
join

(values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

This throws an error saying "...t_1 is undefined".

Does anyone know of an equivalent capability in Snowflake?

For some context:  This construct sits behind a well embedded process for our business, and to rework it would mean significant investment.

It forms the basis for a dynamic ETL query which is passed into an ADF pipeline.  There is a frontend which deploys components into this query - this deployable piece needs to be kept as simple as possible.  It is the equivalent to the "(t_1.c1, ‘foo’)" line, so ideally any solution would keep this piece the same.

EDIT:

For some additional context...

In the example above, we have a placeholder which identifies the insert point of newly deployed items from the front end, like this:

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
/*client_X_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

union

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
,(t_1.c2, 'barfoo')
/*client_Y_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

We are pulling a series of metrics associated with clients, where the label is t_2.c2 and the result is t2.c1.  This is still highly simplified relative to the real world.  We need a simple way to update the placeholder with a new metric and its calculation - t2.c1 may be wrapped in a pile of functions and/or reside inside case statements, etc.

Body:
Lennart deserve this one, his code is so close

WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select *
from t_1
join lateral (values
    (t_1.c1, 'foo'),
    (t_1.c1, 'bar')
    )  as t_2(c1,c2)
    on t_1.c5 = t_2.c2;

but that causes an internal error:

000603 (XX000): SQL execution internal error:
Processing aborted due to error 300002:4143448929; incident 4919401.

But if you put a SELECT * FROM in there:

WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select *
from t_1
join lateral (select * from values
    (t_1.c1, 'foo'),
    (t_1.c1, 'bar')
    ) as t_2(c1,c2)
    on t_1.c5 = t_2.c2;

it works:

C1
C5
C1
C2

a
bar
a
bar

Lenart's try more brackets works also:

WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select *
from t_1
join lateral (
    select * from (
        values
        (t_1.c1, 'foo'),
        (t_1.c1, 'bar')
    )
) as t_2(c1,c2)
    on t_1.c5 = t_2.c2;


问:
Flutter if email correct show pop-up
I'm trying to this condition:

if email is correct, show pop-up before going to the next page

if email is not correct, then there is a warning in the textfield

Here is my code:

```<code>Scaffold (
 body: Padding(
         Form(
            key: _formKey,
            child: TextFormField(
              cursorColor: Color(0xFF2481CF),
              autofocus: true,
              validator: (value) {
                if (value == null || value.isEmpty || !EmailValidator.validate(value.trim())) {
                  return 'Email is not valid!';
                }
                return null;
              },
              controller: _controller,
              decoration: InputDecoration(
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Color(0xFF2481CF)),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Color(0xFF2481CF)),
                  ),
                  labelText: 'Enter your email :',
                  labelStyle: TextStyle(
                    color: Color(0xFF2481CF)
                  )
                ),
              style: TextStyle(
                fontSize: 19.0,
                height: 1.3,
              ),
            ),
          ),
        ),

 floatingActionButton: FloatingActionButton(
      onPressed: () => showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
          content: Container(
            height: 110,
            child: Column(
              children: [
                Text('We will be verifying the email address'),
                SizedBox(
                  height: 30,
                ),
                Text('Is this OK or would you like to edit the email address?'),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.pop(context, 'Cancel'),
              child: const Text('Edit',
              style: TextStyle(
                color: Color(0xFF2481CF)
              ),),
            ),
            TextButton(
              onPressed: _submit,
              child: const Text('Yes',
              style: TextStyle(
                color: Color(0xFF2481CF)
              ),),
            ),
          ],
        ),
      ),
      child: const Icon(Icons.send),
    ),
);

void _submit(){
    if (_formKey.currentState!.validate()) {
      /*ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Sedang memproses.')),
      );*/
      //kirim email

      sendEmail(_controller.text.trim());

      Navigator.of(context).push(
        MaterialPageRoute(builder: (context) =>  PinVerification(_controller.text.trim())),
      );
    }
  }
</code>```

This is the output when I type in the wrong email format, it shows the popup then the warning:

What I want is if the email format is not correct then it shows only the warning.

Any solution?

答:
You have displayed a dialog on floatingActionButton. So you need to check the validation of the email first and then display the dialog. Check out the code below.

```<code>floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            showDialog<String>(
              context: context,
              builder: (BuildContext context) =>
                  AlertDialog(
                    content: Container(
                      height: 110,
                      child: Column(
                        children: [
                          Text('We will be verifying the email address'),
                          SizedBox(
                            height: 30,
                          ),
                          Text(
                              'Is this OK or would you like to edit the email address?'),
                        ],
                      ),
                    ),
                    actions: <Widget>[
                      TextButton(
                        onPressed: () => Navigator.pop(context, 'Cancel'),
                        child: const Text('Edit',
                          style: TextStyle(
                              color: Color(0xFF2481CF)
                          ),),
                      ),
                      TextButton(
                        onPressed: _submit,
                        child: const Text('Yes',
                          style: TextStyle(
                              color: Color(0xFF2481CF)
                          ),),
                      ),
                    ],
                  ),
            );
          }
        },
        child: const Icon(Icons.send),
      ),
</code>```

Title: Flutter if email correct show pop-up

Body:
I'm trying to this condition:

if email is correct, show pop-up before going to the next page

if email is not correct, then there is a warning in the textfield

Here is my code:

Scaffold (
 body: Padding(
         Form(
            key: _formKey,
            child: TextFormField(
              cursorColor: Color(0xFF2481CF),
              autofocus: true,
              validator: (value) {
                if (value == null || value.isEmpty || !EmailValidator.validate(value.trim())) {
                  return 'Email is not valid!';
                }
                return null;
              },
              controller: _controller,
              decoration: InputDecoration(
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Color(0xFF2481CF)),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Color(0xFF2481CF)),
                  ),
                  labelText: 'Enter your email :',
                  labelStyle: TextStyle(
                    color: Color(0xFF2481CF)
                  )
                ),
              style: TextStyle(
                fontSize: 19.0,
                height: 1.3,
              ),
            ),
          ),
        ),

 floatingActionButton: FloatingActionButton(
      onPressed: () => showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
          content: Container(
            height: 110,
            child: Column(
              children: [
                Text('We will be verifying the email address'),
                SizedBox(
                  height: 30,
                ),
                Text('Is this OK or would you like to edit the email address?'),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.pop(context, 'Cancel'),
              child: const Text('Edit',
              style: TextStyle(
                color: Color(0xFF2481CF)
              ),),
            ),
            TextButton(
              onPressed: _submit,
              child: const Text('Yes',
              style: TextStyle(
                color: Color(0xFF2481CF)
              ),),
            ),
          ],
        ),
      ),
      child: const Icon(Icons.send),
    ),
);

void _submit(){
    if (_formKey.currentState!.validate()) {
      /*ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Sedang memproses.')),
      );*/
      //kirim email

      sendEmail(_controller.text.trim());

      Navigator.of(context).push(
        MaterialPageRoute(builder: (context) =>  PinVerification(_controller.text.trim())),
      );
    }
  }

This is the output when I type in the wrong email format, it shows the popup then the warning:

What I want is if the email format is not correct then it shows only the warning.

Any solution?

Body:
You have displayed a dialog on floatingActionButton. So you need to check the validation of the email first and then display the dialog. Check out the code below.

floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            showDialog<String>(
              context: context,
              builder: (BuildContext context) =>
                  AlertDialog(
                    content: Container(
                      height: 110,
                      child: Column(
                        children: [
                          Text('We will be verifying the email address'),
                          SizedBox(
                            height: 30,
                          ),
                          Text(
                              'Is this OK or would you like to edit the email address?'),
                        ],
                      ),
                    ),
                    actions: <Widget>[
                      TextButton(
                        onPressed: () => Navigator.pop(context, 'Cancel'),
                        child: const Text('Edit',
                          style: TextStyle(
                              color: Color(0xFF2481CF)
                          ),),
                      ),
                      TextButton(
                        onPressed: _submit,
                        child: const Text('Yes',
                          style: TextStyle(
                              color: Color(0xFF2481CF)
                          ),),
                      ),
                    ],
                  ),
            );
          }
        },
        child: const Icon(Icons.send),
      ),


问:
confusionMatrix for knn classification in R
I wanted to use the optimal k value to conduct kNN clasification and predict the dependent variable diabetes in test set using train set and compare the results with the real values.

I've already got optimal k value and got the accruacy already. After that, I wanted to compare the results with the real value with using confussionMatrix but I got the problem with the different length.

I've already checked that nrow and length quantities are same(with 74) but it still have same problem.

Could you help me to overcome this problem?

My codes are as like below

```<code>install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

set.seed(3333)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

set.seed(3333)

NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 3)

NN

Accuracy3 <- sum(NN == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

Accuracy3

nrow(TrainXNormDF)
length(MLTrainY$'MLTrain[, 9]')

set.seed(3333)

AccuracyK <- NULL

for(kk in c(1:nrow(TrainXNormDF))){
Knn_K <- knn(train = TrainXNormDF,
             test = ValidXNormDF,
             cl = MLTrainY$`MLTrain[, 9]`,
             k = kk)
AccuracyK <- c(AccuracyK, sum(Knn_K == MLTrainY$'MLTrain[, 9]') / length(MLTrainY$'MLTrain[, 9]'))

ValidK <- data.frame(k = c(1:nrow(TrainXNormDF)), accuracy = AccuracyK)

min(ValidK[ValidK$accuracy %in% max(AccuracyK), "k"])

plot(formula = accuracy ~ k,
 data = ValidK,
 type = "o",
 pch = 5,
 main = "Optimal K Validation")

with(ValidK, text(accuracy ~ k, labels = rownames(ValidK), pos = 2, cex = 0.5))

set.seed(3333)

NN120 <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 120)

Accuracy120 <- sum(NN120 == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

Accuracy120

set.seed(3333)

FinalNN <- knn(train = TrainXNormDF,
           test = TestXNormDF,
           cl = MLTrainY$`MLTrain[, 9]`,
           k = 120)

AccuracyFinal <- sum(FinalNN == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

AccuracyFinal
</code>```

And here I got the problem.

```<code>Result <- confusionMatrix(FinalNN, TestXNormDF)
</code>```

答:
AugPelle has answered your question on how to get a confusion matrix.

I just wanted to point out that you're calculating accuracy incorrectly throughout your code. You should calculate accuracy based on the validation set or test set, not on the training set. This is why you're getting warnings, and it's giving you incorrect answers with a non-optimal k.

Below is the corrected code:

```<code>install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

set.seed(3333)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

set.seed(3333)

NN <- knn(train = TrainXNormDF,
          test = ValidXNormDF,
          cl = MLTrainY$`MLTrain[, 9]`,
          k = 3)

NN

Accuracy3 <- sum(NN == MLValidY$`MLValid[, 9]`) / length(MLValidY$`MLValid[, 9]`)

Accuracy3

nrow(TrainXNormDF)
length(MLTrainY$'MLTrain[, 9]')

set.seed(3333)

AccuracyK <- NULL

for(kk in c(1:nrow(TrainXNormDF))){
  Knn_K <- knn(train = TrainXNormDF,
               test = ValidXNormDF,
               cl = MLTrainY$`MLTrain[, 9]`,
               k = kk)
  AccuracyK <- c(AccuracyK, sum(Knn_K == MLValidY$`MLValid[, 9]`) / length(MLValidY$`MLValid[, 9]`))}

ValidK <- data.frame(k = c(1:nrow(TrainXNormDF)), accuracy = AccuracyK)

min(ValidK[ValidK$accuracy %in% max(AccuracyK), "k"])

plot(formula = accuracy ~ k,
     data = ValidK,
     type = "o",
     pch = 5,
     main = "Optimal K Validation")

with(ValidK, text(accuracy ~ k, labels = rownames(ValidK), pos = 2, cex = 0.5))

set.seed(3333)

NN120 <- knn(train = TrainXNormDF,
             test = ValidXNormDF,
             cl = MLTrainY$`MLTrain[, 9]`,
             k = 36)

Accuracy36 <- sum(NN120 == MLValidY$`MLValid[, 9]`) / length(MLValidY$`MLValid[, 9]`)

Accuracy36

set.seed(3333)

FinalNN <- knn(train = TrainXNormDF,
               test = TestXNormDF,
               cl = MLTrainY$`MLTrain[, 9]`,
               k = 36)

AccuracyFinal <- sum(FinalNN == MLTestY$`MLTest[, 9]`) / length(MLTestY$`MLTest[, 9]`)

AccuracyFinal

Result <- confusionMatrix(FinalNN, MLTestY$`MLTest[, 9]` )
</code>```

Body:
I wanted to use the optimal k value to conduct kNN clasification and predict the dependent variable diabetes in test set using train set and compare the results with the real values.

I've already got optimal k value and got the accruacy already. After that, I wanted to compare the results with the real value with using confussionMatrix but I got the problem with the different length.

I've already checked that nrow and length quantities are same(with 74) but it still have same problem.

Could you help me to overcome this problem?

My codes are as like below

install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

set.seed(3333)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

set.seed(3333)

NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 3)

NN

Accuracy3 <- sum(NN == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

Accuracy3

nrow(TrainXNormDF)
length(MLTrainY$'MLTrain[, 9]')

set.seed(3333)

AccuracyK <- NULL

for(kk in c(1:nrow(TrainXNormDF))){
Knn_K <- knn(train = TrainXNormDF,
             test = ValidXNormDF,
             cl = MLTrainY$`MLTrain[, 9]`,
             k = kk)
AccuracyK <- c(AccuracyK, sum(Knn_K == MLTrainY$'MLTrain[, 9]') / length(MLTrainY$'MLTrain[, 9]'))

ValidK <- data.frame(k = c(1:nrow(TrainXNormDF)), accuracy = AccuracyK)

min(ValidK[ValidK$accuracy %in% max(AccuracyK), "k"])

plot(formula = accuracy ~ k,
 data = ValidK,
 type = "o",
 pch = 5,
 main = "Optimal K Validation")

with(ValidK, text(accuracy ~ k, labels = rownames(ValidK), pos = 2, cex = 0.5))

set.seed(3333)

NN120 <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 120)

Accuracy120 <- sum(NN120 == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

Accuracy120

set.seed(3333)

FinalNN <- knn(train = TrainXNormDF,
           test = TestXNormDF,
           cl = MLTrainY$`MLTrain[, 9]`,
           k = 120)

AccuracyFinal <- sum(FinalNN == MLTrainY$`MLTrain[, 9]`) / length(MLTrainY$`MLTrain[, 9]`)

AccuracyFinal

And here I got the problem.

Result <- confusionMatrix(FinalNN, TestXNormDF)

Body:
AugPelle has answered your question on how to get a confusion matrix.

I just wanted to point out that you're calculating accuracy incorrectly throughout your code. You should calculate accuracy based on the validation set or test set, not on the training set. This is why you're getting warnings, and it's giving you incorrect answers with a non-optimal k.

Below is the corrected code:

install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

set.seed(3333)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

set.seed(3333)

NN <- knn(train = TrainXNormDF,
          test = ValidXNormDF,
          cl = MLTrainY$`MLTrain[, 9]`,
          k = 3)

NN

Accuracy3 <- sum(NN == MLValidY$`MLValid[, 9]`) / length(MLValidY$`MLValid[, 9]`)

Accuracy3

nrow(TrainXNormDF)
length(MLTrainY$'MLTrain[, 9]')

set.seed(3333)

AccuracyK <- NULL

for(kk in c(1:nrow(TrainXNormDF))){
  Knn_K <- knn(train = TrainXNormDF,
               test = ValidXNormDF,
               cl = MLTrainY$`MLTrain[, 9]`,
               k = kk)
  AccuracyK <- c(AccuracyK, sum(Knn_K == MLValidY$`MLValid[, 9]`) / length(MLValidY$`MLValid[, 9]`))}

ValidK <- data.frame(k = c(1:nrow(TrainXNormDF)), accuracy = AccuracyK)

min(ValidK[ValidK$accuracy %in% max(AccuracyK), "k"])

plot(formula = accuracy ~ k,
     data = ValidK,
     type = "o",
     pch = 5,
     main = "Optimal K Validation")

with(ValidK, text(accuracy ~ k, labels = rownames(ValidK), pos = 2, cex = 0.5))

set.seed(3333)

NN120 <- knn(train = TrainXNormDF,
             test = ValidXNormDF,
             cl = MLTrainY$`MLTrain[, 9]`,
             k = 36)

Accuracy36 <- sum(NN120 == MLValidY$`MLValid[, 9]`) / length(MLValidY$`MLValid[, 9]`)

Accuracy36

set.seed(3333)

FinalNN <- knn(train = TrainXNormDF,
               test = TestXNormDF,
               cl = MLTrainY$`MLTrain[, 9]`,
               k = 36)

AccuracyFinal <- sum(FinalNN == MLTestY$`MLTest[, 9]`) / length(MLTestY$`MLTest[, 9]`)

AccuracyFinal

Result <- confusionMatrix(FinalNN, MLTestY$`MLTest[, 9]` )


问:
How to align the items to the start and center the flex container?
I have <s>this plunker</s> this plunker.

I'm trying to horizontal align the flex container while maintaining their items aligned to the start.
<s>
I'm trying to align-content: flex-start while using the justify-content: center. </s>

Right now, if the last row has less items it will be centered to the flex container instead of the start of the row.

Update 1

Here is the expected result:

答:
I found a solution with grid:

It's a bit complex, but it works, if you nest two grids like this:

.grid {
    overflow: hidden;

    --grid__col-width: 200px;
    --grid__column-gap: 20px;
    --grid__row-gap: 20px;

  max-width: 1200px;
  margin: 0 auto;
}

.grid__outer-grid {
    display: grid;
    margin: 0 calc(var(--grid__column-gap) * -1);

    column-gap: var(--grid__column-gap);
    row-gap: var(--grid__row-gap);

    --grid__column-gap-double: calc(var(--grid__column-gap) * 2);
    --grid__column-gap-half: calc(var(--grid__column-gap) / 2);
    --grid__row-gap-half: calc(var(--grid__row-gap) / 2);
    --grid__inner-grid: repeat(auto-fit, minmax(min(var(--grid__col-width), calc(100% - var(--grid__column-gap-double))), var(--grid__col-width)));
    grid-template-columns: minmax(0, 1fr) [grid-start] var(--grid__inner-grid) [grid-end] minmax(0, 1fr);
}

.grid__inner-grid {
    display: grid;

    grid-column-start: grid-start;
    grid-column-end: grid-end;

    column-gap: var(--grid__column-gap);
    row-gap: var(--grid__row-gap);

    grid-template-columns: var(--grid__inner-grid);
}

.box {
  background: red;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
    <div class="grid__outer-grid">
        <div class="grid__inner-grid">
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
        </div>
    </div>
</div></code>```

Demo

ContentLicense: CC BY-SA 3.0

Body:
I found a solution with grid:

It's a bit complex, but it works, if you nest two grids like this:

.grid {
    overflow: hidden;

    --grid__col-width: 200px;
    --grid__column-gap: 20px;
    --grid__row-gap: 20px;

  max-width: 1200px;
  margin: 0 auto;
}

.grid__outer-grid {
    display: grid;
    margin: 0 calc(var(--grid__column-gap) * -1);

    column-gap: var(--grid__column-gap);
    row-gap: var(--grid__row-gap);

    --grid__column-gap-double: calc(var(--grid__column-gap) * 2);
    --grid__column-gap-half: calc(var(--grid__column-gap) / 2);
    --grid__row-gap-half: calc(var(--grid__row-gap) / 2);
    --grid__inner-grid: repeat(auto-fit, minmax(min(var(--grid__col-width), calc(100% - var(--grid__column-gap-double))), var(--grid__col-width)));
    grid-template-columns: minmax(0, 1fr) [grid-start] var(--grid__inner-grid) [grid-end] minmax(0, 1fr);
}

.grid__inner-grid {
    display: grid;

    grid-column-start: grid-start;
    grid-column-end: grid-end;

    column-gap: var(--grid__column-gap);
    row-gap: var(--grid__row-gap);

    grid-template-columns: var(--grid__inner-grid);
}

.box {
  background: red;
  height: 200px;
}

<div class="grid">
    <div class="grid__outer-grid">
        <div class="grid__inner-grid">
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
        </div>
    </div>
</div>

Demo


问:
Convert part of the values in rows in a data frame
I have a data frame which looks like this:

df

```<code>colA colB
0     0
1     1
0     1
0     1
0     1
1     0
0     0
1     1
0     1
</code>```

I would like to convert a certain proportion of the 0 in colA to NA and a certain proportion of 1 in colB to NA

if I do this:

```<code>df["colA"][df["colA"] == 0] <- NA
</code>```

all the 0 in columns A will be converted to NA, however I just want half of them to be converted

Similarly, for colB I want only 1/3 of the 1 to be converted:

```<code>df["colB"][df["colB"] == 1] <- NA
</code>```

Expected output:

```<code>   colA colB
    0     0
    1     1
    NA    1
    0     1
    NA    1
    1     0
    0     0
    1     NA
    NA    NA
</code>```

答:
One way

```<code>tmp=which(df["colA"]==0)
df$colA[sample(tmp,round(length(tmp)/2))]=NA
</code>```

similar for colB

```<code>tmp=which(df["colB"]==1)
df$colB[sample(tmp,round(length(tmp)/3))]=NA
</code>```

Body:
I have a data frame which looks like this:

df

colA colB
0     0
1     1
0     1
0     1
0     1
1     0
0     0
1     1
0     1

I would like to convert a certain proportion of the 0 in colA to NA and a certain proportion of 1 in colB to NA

if I do this:

df["colA"][df["colA"] == 0] <- NA

all the 0 in columns A will be converted to NA, however I just want half of them to be converted

Similarly, for colB I want only 1/3 of the 1 to be converted:

df["colB"][df["colB"] == 1] <- NA

Expected output:

   colA colB
    0     0
    1     1
    NA    1
    0     1
    NA    1
    1     0
    0     0
    1     NA
    NA    NA

Body:
One way

tmp=which(df["colA"]==0)
df$colA[sample(tmp,round(length(tmp)/2))]=NA

similar for colB

tmp=which(df["colB"]==1)
df$colB[sample(tmp,round(length(tmp)/3))]=NA


问:
Why I am getting wrong bytes when converting struct to byte array?
I was trying to convert a c++ struct variable to a byte array. But unfortunately, I am getting a weird output.

Code:

```<code>#include <bits/stdc++.h>

using namespace std;

struct A{
    int  x;
};

int main ()
{
    A obj;
    obj.x = 892323;

    char *x =(char *)malloc(sizeof(obj));
    memcpy(x, (unsigned char *)&obj, sizeof(obj));

    for(int i=0; i < sizeof(obj); i++)
        printf("%02X\n",x[i]);

    return 0;
}
</code>```

output:

```<code>FFFFFFA3
FFFFFF9D
0D
00
</code>```

Can anyone tell me why I am getting this kind out output?

答:
The output is correct, even if not be what you would expect. The underlying cause is that it is implementation defined whether the char type is signed or unsigned. In your platform, it is signed so the byte 0xA3 is -93. When you pass it to the printf function it is promoted to an int. But the %x modifier will convert it to an unsigned value by adding 0x100000000 when int (and unsigned int) use 32 bits to give 4294967203 or 0xffffffa3.

If you want to get only 2 character per byte, you should use unsigned char. With

```<code>...
unsigned char* x = (unsigned char*)malloc(sizeof(obj));
...
</code>```

You would get:

```<code>A3
9D
0D
00
</code>```

which is indeed the byte representation of 892323 or 0xd9da3 on a little endian system with 32 bits integers.

BTW, your code heavily uses the C standard library. While it is not wrong because the C++ standard explicitely includes it in the C++ standard library there are 2 weak points:

your code cannot benefit of all the type safety provided by the C++ language and its library

you will fail to learn how to use modern C++

Body:
I was trying to convert a c++ struct variable to a byte array. But unfortunately, I am getting a weird output.

Code:

#include <bits/stdc++.h>

using namespace std;

struct A{
    int  x;
};

int main ()
{
    A obj;
    obj.x = 892323;

    char *x =(char *)malloc(sizeof(obj));
    memcpy(x, (unsigned char *)&obj, sizeof(obj));

    for(int i=0; i < sizeof(obj); i++)
        printf("%02X\n",x[i]);

    return 0;
}

output:

FFFFFFA3
FFFFFF9D
0D
00

Can anyone tell me why I am getting this kind out output?

Body:
The output is correct, even if not be what you would expect. The underlying cause is that it is implementation defined whether the char type is signed or unsigned. In your platform, it is signed so the byte 0xA3 is -93. When you pass it to the printf function it is promoted to an int. But the %x modifier will convert it to an unsigned value by adding 0x100000000 when int (and unsigned int) use 32 bits to give 4294967203 or 0xffffffa3.

If you want to get only 2 character per byte, you should use unsigned char. With

...
unsigned char* x = (unsigned char*)malloc(sizeof(obj));
...

You would get:

A3
9D
0D
00

which is indeed the byte representation of 892323 or 0xd9da3 on a little endian system with 32 bits integers.

BTW, your code heavily uses the C standard library. While it is not wrong because the C++ standard explicitely includes it in the C++ standard library there are 2 weak points:

your code cannot benefit of all the type safety provided by the C++ language and its library

you will fail to learn how to use modern C++


问:
Shopify Store Refresh cart content. AJAX request
I have product page on which I have shop now btn. When user clicks on this button, page opens cart drawer with custom ajax template content.

I rewrited click event with my own logic. I use AJAX and send request for adding product by myself. Products are adding but is not showing in the cart drawer. Only after reloading page it is appearing.

Question is to can I refresh cart content? I'm trying to past content template via inner html. But it is looks like not liquid format.

Here is the template

```<code> <script id="CartTemplate" type="text/template">
{% render 'banana-stand-cart-top-container' %}
{% raw %}
<div class="drawer__scrollable">
  {{#items}}
  <div class="ajaxcart__product appear-animation appear-delay-{{animationRow}}">
  <div class="ajaxcart__row">
    <div class="grid">
      <div class="grid__item one-third">
        <a href="{{url}}" class="ajaxcart__product-image"><img src="{{img}}" alt="{{name}}"></a>
      </div>
      <div class="grid__item two-thirds">
        <div class="ajaxcart__product-name--wrapper">
          <a href="{{url}}" class="ajaxcart__product-name">{{{name}}}</a>
          {{#if variation}}
            <div class="ajaxcart__product-meta">{{variation}}</div>
          {{/if}}
          {{#if selling_plan_name}}
            <div class="ajaxcart__product-meta">{{selling_plan_name}}</div>
          {{/if}}
          {{#properties}}
            {{#each this}}
              {{#if this}}
                <span class="ajaxcart__product-meta">{{@key}}: {{this}}</span>
              {{/if}}
            {{/each}}
          {{/properties}}
        </div>

        <div class="grid grid--full display-table">
          <div class="grid__item display-table-cell one-half">
            <label for="updates_{{key}}" class="visually-hidden">{% endraw %}{{ 'products.product.quantity' | t }}{% raw %}</label>
            <div class="js-qty__wrapper">
              <input type="text" id="updates_{{key}}"
                class="js-qty__num"
                value="{{itemQty}}"
                data-id="{{key}}"
                min="0"
                aria-label="quantity"
                pattern="[0-9]*"
                name="updates[]">
              <button type="button"
                class="js-qty__adjust js-qty__adjust--minus"
                aria-label="{% endraw %}{{ 'cart.general.reduce_quantity' | t }}{% raw %}">
                  {% endraw %}<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-minus" viewBox="0 0 20 20"><path fill="#444" d="M17.543 11.029H2.1A1.032 1.032 0 0 1 1.071 10c0-.566.463-1.029 1.029-1.029h15.443c.566 0 1.029.463 1.029 1.029 0 .566-.463 1.029-1.029 1.029z"/></svg>{% raw %}
                  <span class="icon__fallback-text" aria-hidden="true">−</span>
              </button>
              <button type="button"
                class="js-qty__adjust js-qty__adjust--plus"
                aria-label="{% endraw %}{{ 'cart.general.increase_quantity' | t }}{% raw %}">
                  {% endraw %}<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-plus" viewBox="0 0 20 20"><path fill="#444" d="M17.409 8.929h-6.695V2.258c0-.566-.506-1.029-1.071-1.029s-1.071.463-1.071 1.029v6.671H1.967C1.401 8.929.938 9.435.938 10s.463 1.071 1.029 1.071h6.605V17.7c0 .566.506 1.029 1.071 1.029s1.071-.463 1.071-1.029v-6.629h6.695c.566 0 1.029-.506 1.029-1.071s-.463-1.071-1.029-1.071z"/></svg>{% raw %}
                  <span class="icon__fallback-text" aria-hidden="true">+</span>
              </button>
            </div>
          </div>
          <div class="grid__item display-table-cell one-half text-right">
            {{#if discountsApplied}}
              <small class="cart__price--strikethrough">{{{price}}}</small>
              <span class="ajaxcart__price">
                {{{discountedPrice}}}
              </span>
            {{else}}
              <span class="ajaxcart__price">
                {{{price}}}
              </span>
            {{/if}}
          </div>
        </div>
        <div class="grid grid--full display-table">
          {{#if discountsApplied}}
            <div class="grid__item text-right">
              {{#each discounts}}
                <small class="ajaxcart__discount cart__discount">
                  {{this.discount_application.title}} (-{{{this.formattedAmount}}})
                </small>
              {{/each}}
            </div>
          {{/if}}

          {{#if unitBase}}
            <div class="grid__item text-right">
              <div class="product__unit-price">
                {{{ unitPrice }}}/{{{ unitBase }}}
              </div>
            </div>
          {{/if}}
        </div>
      </div>
    </div>
  </div>
</div>
{{/items}}

  {% endraw %}{% if settings.cart_notes_enable %}{% raw %}
  <div class="appear-animation appear-delay-{{lastAnimationRow}}">
    <label for="CartSpecialInstructions" class="ajaxcart__note">{% endraw %}{{ 'cart.general.note' | t }}{% raw %}</label>
    <textarea name="note" class="input-full cart-notes" id="CartSpecialInstructions">{{note}}</textarea>
  </div>
{% endraw %}{% endif %}{% raw %}
   </div>
    <div class="drawer__footer appear-animation appear-delay-{{lastAnimationRow}}">
   {{#if cartDiscounts }}
    <div class="grid grid--full">
     <div class="grid__item one-half">
      <p class="ajaxcart__subtotal">{% endraw %}{{ 'cart.general.discounts' | t }}{% raw %}</p>
    </div>
      <div class="grid__item one-half text-right">
      {{#each cartDiscounts}}
        <p class="ajaxcart__price cart__discount">
          {{this.title}} (-{{{this.formattedAmount}}})
        </p>
      {{/each}}
    </div>
  </div>
{{/if}}
<div class="grid grid--full">
  <div class="grid__item one-half">
    <p class="ajaxcart__subtotal">{% endraw %}{{ 'cart.general.subtotal' | t }}{% raw %}</p>
  </div>
  <div class="grid__item one-half text-right">
    <p class="ajaxcart__price"><span class="tdf-cart-total-parent">{{totalPrice}}</span></p>
  </div>
</div>
<p class="ajaxcart__note">
  {% endraw %}{{ 'cart.general.shipping_at_checkout' | t }}{% raw %}
</p>
{% endraw %}{% if settings.cart_terms_conditions_enable %}
  <p class="ajaxcart__note ajaxcart__note--terms">
    <input type="checkbox" id="CartAgree" />
    <label for="CartAgree">
      {% if settings.cart_terms_conditions_link != blank %}
        {{ 'cart.general.terms_html' | t: url: settings.cart_terms_conditions_link }}
      {% else %}
        {{ 'cart.general.terms' | t }}
      {% endif %}
    </label>
  </p>
   {% endif %}{% raw %}
   {% endraw %}
   {% if additional_checkout_buttons and settings.cart_additional_buttons %}
      <div class="additional-checkout-buttons additional-checkout-buttons--vertical">{{ content_for_additional_checkout_buttons }}</div>
   {% endif %}
  {% raw %}
  <button type="submit" class="btn btn--full cart__checkout{% endraw %}{% if settings.cart_terms_conditions_enable %}{% raw %} cart__checkout--ajax{% endraw %}{% endif %}{% raw %}" name="checkout">
  {% endraw %}{{ 'cart.general.checkout' | t }}{% raw %}
</button>
</div>
{% endraw %}
</code>```

答:
So, need fire some event that you can find in your theme.js file. In my case I needed to add this:</p>
```<code> document.dispatchEvent(new CustomEvent('cart:build', {
    detail: {
      cart: cart
    }
 }));
</code>```

Body:
So, need fire some event that you can find in your theme.js file. In my case I needed to add this:

 document.dispatchEvent(new CustomEvent('cart:build', {
    detail: {
      cart: cart
    }
 }));


问:
"NOT IN"/"NOT EXISTS" for pairwise column comparison not working in Redshift
I would like to rewrite the below statement in redshift. Redshift does not support IN/NOT IN for multiple column comparison. I get the following error when I try the same query with NOT EXISTS as well:

Invalid operation: This type of correlated subquery pattern is not supported due to internal error;

```<code>select count(distinct item) from tbl1
where (item,store) not in (
select distint item, store form tbl1
where *store changed* -- some filters
)
</code>```

答:
Tim's idea seems cool, but you can also use the following code:</p>
```<code>select     count(distinct t1.item)
from       tbl1 t1
left join
(
        select distinct item, store
        form   tbl1
        where  *store changed* -- some filters
) t2
on t2.item = t1.item
and t2.store = t1.store

where t2.item is null
and   t2.store is null
</code>```

Body:
I would like to rewrite the below statement in redshift. Redshift does not support IN/NOT IN for multiple column comparison. I get the following error when I try the same query with NOT EXISTS as well:

Invalid operation: This type of correlated subquery pattern is not supported due to internal error;

select count(distinct item) from tbl1
where (item,store) not in (
select distint item, store form tbl1
where *store changed* -- some filters
)

Body:
Tim's idea seems cool, but you can also use the following code:

select     count(distinct t1.item)
from       tbl1 t1
left join
(
        select distinct item, store
        form   tbl1
        where  *store changed* -- some filters
) t2
on t2.item = t1.item
and t2.store = t1.store

where t2.item is null
and   t2.store is null


问:
i am unable to initilize vector with initilize elements
I am unable to initialize the vector with initial elements.

I am receiving this error:

no instance of constructor "std::__1::vector<_Tp, _Allocator>::vector
[with _Tp=int, _Allocator=std::__1::allocator]" matches the
argument list

I am using VS Code on a MacBook Air M1.

答:
Thanks @BoP.
I have just changed my settings to c++14 and it worked image.


问:
How to check if a checkbox has been selected using ShinyDashboard?
I have created an app using ShinyDashboard that has one checkboxInput. If you click on it, you will see two checkboxGroupInput where you can select 1 or 2 choices.

The idea is that if you click 1 option, you will subset your dataframe with your individual choice, or if you click both options, you will subset your dataframe with those two options.

However, I am having problems to verify which option of the checkboxGroupInput the user has selected.

Here is a reproducible example. As you can see, if you select both, you end in the first if statement, subsetting two columns. However, if you select one option (setosa, for example), you are still subsetting by the two, because it doesn't recognise the choice that you have selected. However, if you select "virginica" it is subsetted.

Moreover, it appears this warning all the time.

Warning in if (c("setosa", "virginica") %in% input$species_choice) { :
the condition has length > 1 and only the first element will be used

The code:

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(

  dashboardHeader(title = "Dashboard"),
  ## Sidebar content
  dashboardSidebar(
    sidebarMenu(
      menuItem("App1", tabName = "App1", icon = icon("th"))

    )
  ),

  dashboardBody(
    fluidRow(
      tabItems(

        tabItem(tabName = "App1",
                sidebarPanel(
                  checkboxInput(inputId = "species", label = "Select species"),

                  conditionalPanel(
                    condition = "input.species",
                    style = "margin-left: 20px;",

                    checkboxGroupInput("species_choice", "Choose the species:",
                                       choices = c("setosa", "virginica"), selected = c("setosa", "virginica"))),
                ),
                mainPanel(
                  dataTableOutput("table")

                )
        )
      )
    )
  )
)

server <- function(input, output, session) {

  mytables <- reactive({
   if(input$species){

     df_setosa <- iris[iris$Species=="setosa",]
     df_virginica <- iris[iris$Species=="virginica",]
     df_both <- rbind(df_setosa, df_virginica)

     if(c("setosa", "virginica") %in% input$species_choice){
       print("both")
       return(df_both)
     }

     if("setosa" %in% input$species_choice){
       print("setosa")
       return(df_setosa)
     }

     if("virginica" %in% input$species_choice){
       print("virginica")
       return(df_virginica)
     }
   }
  })

  output$table <- renderDataTable({
    mytables()
  })

}

shinyApp(ui, server)
</code>```

I have tried this way too, but it doesn't work:

```<code>if(input$species_choice == "setosa"){
        print("setosa")
        return(df_setosa)
      }

      if(input$species_choice == "virginica"){
        print("virginica")
        return(df_virginica)
      }

      if(input$species_choice == c("setosa, virginica"){
        print("both")
        return(df_both)
      }
</code>```

Does anyone know how to help me, please?

Thanks in advance

答:
I found another solution:

I just have to include if(all(c(OPTIONS) ....

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(

  dashboardHeader(title = "Dashboard"),
  ## Sidebar content
  dashboardSidebar(
    sidebarMenu(
      menuItem("App1", tabName = "App1", icon = icon("th"))

    )
  ),

  dashboardBody(
    fluidRow(
      tabItems(

        tabItem(tabName = "App1",
                sidebarPanel(
                  checkboxInput(inputId = "species", label = "Select species"),

                  conditionalPanel(
                    condition = "input.species",
                    style = "margin-left: 20px;",

                    checkboxGroupInput("species_choice", "Choose the species:",
                                       choices = c("setosa", "virginica"), selected = c("setosa", "virginica"))),
                ),
                mainPanel(
                  dataTableOutput("table")

                )
        )
      )
    )
  )
)

server <- function(input, output, session) {

  mytables <- reactive({
    if(input$species){

      df_setosa <- iris[iris$Species=="setosa",]
      df_virginica <- iris[iris$Species=="virginica",]
      df_both <- rbind(df_setosa, df_virginica)

      if(all(c("setosa", "virginica") %in% input$species_choice)){
        print("both")
        return(df_both)
      }

      if(all(c("setosa") %in% input$species_choice)){
        print("setosa")
        return(df_setosa)
      }

      if(all(c("virginica") %in% input$species_choice)){
        print("virginica")
        return(df_virginica)
      }
    }
  })

  output$table <- renderDataTable({
    mytables()
  })

}

shinyApp(ui, server)
</code>```

Body:
I have created an app using ShinyDashboard that has one checkboxInput. If you click on it, you will see two checkboxGroupInput where you can select 1 or 2 choices.

The idea is that if you click 1 option, you will subset your dataframe with your individual choice, or if you click both options, you will subset your dataframe with those two options.

However, I am having problems to verify which option of the checkboxGroupInput the user has selected.

Here is a reproducible example. As you can see, if you select both, you end in the first if statement, subsetting two columns. However, if you select one option (setosa, for example), you are still subsetting by the two, because it doesn't recognise the choice that you have selected. However, if you select "virginica" it is subsetted.

Moreover, it appears this warning all the time.

Warning in if (c("setosa", "virginica") %in% input$species_choice) { :
the condition has length > 1 and only the first element will be used

The code:

library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(

  dashboardHeader(title = "Dashboard"),
  ## Sidebar content
  dashboardSidebar(
    sidebarMenu(
      menuItem("App1", tabName = "App1", icon = icon("th"))

    )
  ),

  dashboardBody(
    fluidRow(
      tabItems(

        tabItem(tabName = "App1",
                sidebarPanel(
                  checkboxInput(inputId = "species", label = "Select species"),

                  conditionalPanel(
                    condition = "input.species",
                    style = "margin-left: 20px;",

                    checkboxGroupInput("species_choice", "Choose the species:",
                                       choices = c("setosa", "virginica"), selected = c("setosa", "virginica"))),
                ),
                mainPanel(
                  dataTableOutput("table")

                )
        )
      )
    )
  )
)

server <- function(input, output, session) {

  mytables <- reactive({
   if(input$species){

     df_setosa <- iris[iris$Species=="setosa",]
     df_virginica <- iris[iris$Species=="virginica",]
     df_both <- rbind(df_setosa, df_virginica)

     if(c("setosa", "virginica") %in% input$species_choice){
       print("both")
       return(df_both)
     }

     if("setosa" %in% input$species_choice){
       print("setosa")
       return(df_setosa)
     }

     if("virginica" %in% input$species_choice){
       print("virginica")
       return(df_virginica)
     }
   }
  })

  output$table <- renderDataTable({
    mytables()
  })

}

shinyApp(ui, server)

I have tried this way too, but it doesn't work:

if(input$species_choice == "setosa"){
        print("setosa")
        return(df_setosa)
      }

      if(input$species_choice == "virginica"){
        print("virginica")
        return(df_virginica)
      }

      if(input$species_choice == c("setosa, virginica"){
        print("both")
        return(df_both)
      }

Does anyone know how to help me, please?

Thanks in advance

Body:
I found another solution:

I just have to include if(all(c(OPTIONS) ....

library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(

  dashboardHeader(title = "Dashboard"),
  ## Sidebar content
  dashboardSidebar(
    sidebarMenu(
      menuItem("App1", tabName = "App1", icon = icon("th"))

    )
  ),

  dashboardBody(
    fluidRow(
      tabItems(

        tabItem(tabName = "App1",
                sidebarPanel(
                  checkboxInput(inputId = "species", label = "Select species"),

                  conditionalPanel(
                    condition = "input.species",
                    style = "margin-left: 20px;",

                    checkboxGroupInput("species_choice", "Choose the species:",
                                       choices = c("setosa", "virginica"), selected = c("setosa", "virginica"))),
                ),
                mainPanel(
                  dataTableOutput("table")

                )
        )
      )
    )
  )
)

server <- function(input, output, session) {

  mytables <- reactive({
    if(input$species){

      df_setosa <- iris[iris$Species=="setosa",]
      df_virginica <- iris[iris$Species=="virginica",]
      df_both <- rbind(df_setosa, df_virginica)

      if(all(c("setosa", "virginica") %in% input$species_choice)){
        print("both")
        return(df_both)
      }

      if(all(c("setosa") %in% input$species_choice)){
        print("setosa")
        return(df_setosa)
      }

      if(all(c("virginica") %in% input$species_choice)){
        print("virginica")
        return(df_virginica)
      }
    }
  })

  output$table <- renderDataTable({
    mytables()
  })

}

shinyApp(ui, server)


问:
Capturing innerHTML of a web page via ADB Command line
I am wondering if it is possible to pull the innerHTML of a web page once it is loaded via ADB command line only.

I want to check my public IP address of my android device to verify the Proxy is active before running additional commands/services. I plan to validate the known Proxy using https://api.ipify.org

I can run the following command:
adb shell am start -a android.intent.action.VIEW -d https://api.ipify.org
Only problem is i have no way of grabbing the result and relaying it back via command line. I also want to avoid opening a web page on the device and have this query be done in the background.

Just to add that I am rooted which may help with the solution.

I have done a lot of research and came across this tool: https://www.cyberciti.biz/faq/unix-linux-get-the-contents-of-a-webpage-in-a-terminal but have no idea how to get this to work or even if this is the way to go.

I know how to do this using VB with the post method using a WinHttp request, but when it comes to android/linux I am completely lost!

Thanks in advance

Kind regards,
Maddis :)

答:
Using am start to execute something you want to get the response of is a bad idea because am start works asynchronously and thus can not give you any direct response.

As it is your phone only I recommend to install a a Linux command-line tool like curl or wget to /data/local/tmp or /data/local depending on your Android version. A simple wget version is usually included in busybox so there should be a number of precompiled binaries available you can simply push to thed evice, copy to /data/local/tmp or /data/local, make it executable via chmod and then use to request your public IP using the mentioned API.


问:
For how long does Android save a killed activity's state?
I just did a little test: I started my app, went to a certain screen, pressed the home button and killed the process via Advanced Task Killer.

Now, if I go back to my app just a few moments later, I come back to that very screen. I also know that onRestoreInstanceState() is called in this case, as I have played around with this method quite a bit.

However, just out of curiosity, I did all the same, but let my phone lie around for some time (an hour or something). When I restarted my app, it went straight to the main activity.

So my question is: for how long does Android keep the saved state? or what determines if it throws it away or not? I already figured out it had nothing to do with lockscreen on/off.

Kind regards,
jellyfish

答:
The activity is restored because such applications as Advanced Task Killer use "illegal" methods for killing applications. Android kills application is a similar way when it's low on memory and when killed application is launched again its state is restored.

Android keeps an application state for some time. Usually it's about 15-30 minutes but I think it depends on the device. But you can ask Android to keep an activity state "forever" (until the activity is finished) using android:alwaysRetainTaskState="true" attribute.


问:
Remove digits in CSV headers
I have a CSV file that has been converted from a dict - witch has added Numbers to get the columns unique. Now I want to remove the numbers.

Example of CSV headers now:

```<code>User,Comment,Comment1,Comment2,Created
</code>```

I would like to use something like this:

```<code>header = ''.join([i for i in header if not i.isdigit()])
</code>```

I uses this code to create the CSV without any empty columns.

```<code>with open('input.csv') as fd, open('output.csv', 'w', newline='') as fdout:
    rd = csv.reader(fd)
    cols = set()
    _ = next(rd)  # skip header line
    for row in rd:
        for i, val in enumerate(row):
            if val != '':
                cols.add(i)
    _ = fd.seek(io.SEEK_SET)
    wr = csv.writer(fdout)
    for row in rd:
        _ = wr.writerow(val for i, val in enumerate(row) if i in cols)
</code>```

And my desired output are the same file but headers like this:

```<code>User,Comment,Comment,Comment,Created
</code>```

答:
Sounds like

```<code>import csv
import re

with open("input.csv") as fd, open("output.csv", "w", newline="") as fdout:
    rd = csv.reader(fd)
    wr = csv.writer(fdout)
    # read header line, remove trailing numbers from each column
    header = [re.sub(r"\d+$", "", col) for col in next(rd)]
    # write processed header out
    wr.writerow(header)
    for row in rd:  # just copy other lines
        wr.writerow(row)
</code>```

should do the trick, then.

Title: Remove digits in CSV headers

Body:
I have a CSV file that has been converted from a dict - witch has added Numbers to get the columns unique. Now I want to remove the numbers.

Example of CSV headers now:

User,Comment,Comment1,Comment2,Created

I would like to use something like this:

header = ''.join([i for i in header if not i.isdigit()])

I uses this code to create the CSV without any empty columns.

with open('input.csv') as fd, open('output.csv', 'w', newline='') as fdout:
    rd = csv.reader(fd)
    cols = set()
    _ = next(rd)  # skip header line
    for row in rd:
        for i, val in enumerate(row):
            if val != '':
                cols.add(i)
    _ = fd.seek(io.SEEK_SET)
    wr = csv.writer(fdout)
    for row in rd:
        _ = wr.writerow(val for i, val in enumerate(row) if i in cols)

And my desired output are the same file but headers like this:

User,Comment,Comment,Comment,Created

Body:
Sounds like

import csv
import re

with open("input.csv") as fd, open("output.csv", "w", newline="") as fdout:
    rd = csv.reader(fd)
    wr = csv.writer(fdout)
    # read header line, remove trailing numbers from each column
    header = [re.sub(r"\d+$", "", col) for col in next(rd)]
    # write processed header out
    wr.writerow(header)
    for row in rd:  # just copy other lines
        wr.writerow(row)

should do the trick, then.


问:
Django Rest Framework ModelViewSet ManyToMany Field override partial_update Method is not working update_or_create
I have a question here

I have two models

Tag Model

```<code>class Tag(models.Model):
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author')
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name
</code>```

Profile Model

```<code>class Profile(models.Model):
    profiler = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='contour')
    bio = models.TextField(blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True, related_name='keywords')
    image = models.ImageField(default='avatar.jpg', upload_to='images', blank=True, null=True)

    def __str__(self):
        return f'{self.profiler}'
</code>```

Tag Serializer

```<code>class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = '__all__'
</code>```

Profile Serializer

```<code>class ProfileSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, read_only=True)

    class Meta:
        model = Profile
        fields = ['id',  # List All fields Exclude profiler => OneToOne field name
                  'bio', 'description',
                  'tags',
                  'image',
                  'birthDate', 'created', 'updated',
                  ]
        depth = 1
</code>```

Profile Viewset

```<code>class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = [IsAuthenticated]

def partial_update(self, request, *args, **kwargs):
    data = request.data

    profile_obj = Profile.objects.update(
        profiler=self.request.user,
        bio=data['bio'],
        image=data['image'],
    )

    profile_obj.save()

    for tag in data['tags']:
        tag_obj = Tag.objects.update_or_create(
            creator=self.request.user,
            name=tag['name'],  # name => Field Name in Tag Model
        )

        print(tag_obj)
        profile_obj.tags.add(tag_obj)  # tags => ManyToMany Field Name in Profile Model

    serializer = ProfileSerializer(profile_obj)

    return Response(serializer.data)
</code>```

my aim is to create a new tag if this name is not exist, and also update profile tags

but my code is not working, and I don't know why

Can Any body help please ?

答:
Finally I found the solution, But it still missing some steps

Profile Serializer

```<code>class ProfileSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True)  # tags = ManyToMany Field Name

    class Meta:
        model = Profile

        fields = ['id',  # List All fields Exclude profiler => OneToOne field name
                  'bio', 'description',
                  'tags',
                  'image', 'get_image',
                  'birthDate', 'created', 'updated',
                  ]

    def update(self, instance, validated_data):
        # Clear Existing Tags List Before Creating a New One By user
        instance.tags.clear()

        tags_data = validated_data.pop('tags')
        instance = super(ProfileSerializer, self).update(instance, validated_data)

        for tag_data in tags_data:
            tag_qs = Tag.objects.filter(name__iexact=tag_data['name'])

            if tag_qs.exists():
                tag = tag_qs.first()
            else:
                tag = Tag.objects.create(**tag_data, creator=self.instance.profiler)

            instance.tags.add(tag)

        return instance
</code>```

It Worked Like a charm but the problem is:
when I want to partial update of fields and i did't submit tags field,
It raises error

```<code>{
    "tags": [
        "This field is required."
    ]
}
</code>```

Can some one help to keep my tags list as it is when the updated data missing tags field

Thanks in-advance

Body:
I have a question here

I have two models

Tag Model

class Tag(models.Model):
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author')
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

Profile Model

class Profile(models.Model):
    profiler = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='contour')
    bio = models.TextField(blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True, related_name='keywords')
    image = models.ImageField(default='avatar.jpg', upload_to='images', blank=True, null=True)

    def __str__(self):
        return f'{self.profiler}'

Tag Serializer

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = '__all__'

Profile Serializer

class ProfileSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, read_only=True)

    class Meta:
        model = Profile
        fields = ['id',  # List All fields Exclude profiler => OneToOne field name
                  'bio', 'description',
                  'tags',
                  'image',
                  'birthDate', 'created', 'updated',
                  ]
        depth = 1

Profile Viewset

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = [IsAuthenticated]

def partial_update(self, request, *args, **kwargs):
    data = request.data

    profile_obj = Profile.objects.update(
        profiler=self.request.user,
        bio=data['bio'],
        image=data['image'],
    )

    profile_obj.save()

    for tag in data['tags']:
        tag_obj = Tag.objects.update_or_create(
            creator=self.request.user,
            name=tag['name'],  # name => Field Name in Tag Model
        )

        print(tag_obj)
        profile_obj.tags.add(tag_obj)  # tags => ManyToMany Field Name in Profile Model

    serializer = ProfileSerializer(profile_obj)

    return Response(serializer.data)

my aim is to create a new tag if this name is not exist, and also update profile tags

but my code is not working, and I don't know why

Can Any body help please ?

Body:
Finally I found the solution, But it still missing some steps

Profile Serializer

class ProfileSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True)  # tags = ManyToMany Field Name

    class Meta:
        model = Profile

        fields = ['id',  # List All fields Exclude profiler => OneToOne field name
                  'bio', 'description',
                  'tags',
                  'image', 'get_image',
                  'birthDate', 'created', 'updated',
                  ]

    def update(self, instance, validated_data):
        # Clear Existing Tags List Before Creating a New One By user
        instance.tags.clear()

        tags_data = validated_data.pop('tags')
        instance = super(ProfileSerializer, self).update(instance, validated_data)

        for tag_data in tags_data:
            tag_qs = Tag.objects.filter(name__iexact=tag_data['name'])

            if tag_qs.exists():
                tag = tag_qs.first()
            else:
                tag = Tag.objects.create(**tag_data, creator=self.instance.profiler)

            instance.tags.add(tag)

        return instance

It Worked Like a charm but the problem is:
when I want to partial update of fields and i did't submit tags field,
It raises error

{
    "tags": [
        "This field is required."
    ]
}

Can some one help to keep my tags list as it is when the updated data missing tags field

Thanks in-advance


问:
Trying to move completed tasks from one list to another
Here we have a tab with incompled tasks and the list is supposed to be attached to the first tab(all-taks). After the task is finished it is supposed to get deleted from first list and move to second one with completed tasks. And after you switch to second tab, all the completed ones should be there. I can't figure out the way to do it.
I hope I could get some help or some detailed explanation, 'cause I have been stuck on this for some time.

Here is an image for more clarification:
[1]: https://i.stack.imgur.com/Dy0KL.png

HTML code:

```<code><body>
    <div class="container">
        <header>
            <h1>To-Do List</h1>
            <h4>Describe your list...</h4>
        </header>

        <form action="" class="todo-form">
            <div class="form-wrapper">
                <!-- action is where files will be sent after submitting -->
                <input class="todo-input" type="text" placeholder="Add a task...">
            </div>
            <div class="form-wrapper">
                <button class="todo-button" type="submit">Add</button>
            </div>
    </form>

    <div class="todo-tabs">
        <ul>
            <li class="all-tasks active">
                <span></span>All tasks (<span class="counter">0</span>)</span>
            </li>
            <li class="completed">
                <span>Completed (<span class="counter">0</span>)</span>
            </li>
        </ul>
    </div>

    <div class="todo-list">
        <div class="tabs-content" data-tab="1">
            <ol class="undone-tasks"></ol>
        </div>
        <div class="tabs-content" data-tab="2">
            <ol class="done-tasks"></ol>
        </div>
    </div>
</body>
</code>```

JS code:

```<code>//Selectors
const todoForm = document.querySelector('.todo-form');
const todoInput = document.querySelector('.todo-input');
const todoButton = document.querySelector('.todo-button');

const tabs = document.querySelectorAll('.todo-tabs ul li');
const tabWrap = document.querySelector('.todo-tabs ul');

const undone = document.querySelector('.undone-tasks');
const done = document.querySelectorAll('.done-tasks');

//Event Listeners
tabWrap.addEventListener('click', tabs)
todoButton.addEventListener('click', addToDo);

//Functions
tabs.forEach(function (tab, tab_index) {
    tab.addEventListener("click", function () {
        tabs.forEach(function (tab) {
            tab.classList.remove("active");
        })
        tabWrap.forEach(function (todoList, todoList_index) {
            if (todoList_index == tab_index) {
                todoList.style.display = "block";
            }
            else[
                todoList.style.display = "none"
            ]
        })
    })
})

function addToDo(event) {
    //Prevent form from submitting
    event.preventDefault();

    if (todoInput.value != "") {
        const todoDiv = document.createElement('div');
        todoDiv.classList.add('todo-div');

        const inputCheckbox = document.createElement('input');
        inputCheckbox.classList.add("checkbox-incompleted");
        inputCheckbox.setAttribute('type', 'checkbox');
        todoDiv.appendChild(inputCheckbox);

        //Create li
        const newToDo = document.createElement('li');
        newToDo.classList.add('todo-item');
        newToDo.insertAdjacentText("beforeend", todoInput.value);
        todoDiv.appendChild(newToDo);
        console.log(newToDo)

        //Append to list
        undone.appendChild(todoDiv);

        //Clear todo input value
        todoInput.value = "";

        //Focusing after 1st input
        todoInput.focus();
    }
}
</code>```

The commented area is what i tried to do for tabs and lists to switch, but it gives the following error:

```<code>Uncaught TypeError: tabWrap.forEach is not a function
    at HTMLLIElement.<anonymous> (script.js:32:17)
(anonymous) @ script.js:32
</code>```

The error starts at the beggining of the tabWrap.forEach function. But I guess there could be other way to solve this

答:
tabWrap is not useful for what you want: it is a single element. Instead, you'll want to iterate over the tab contents, which are identified by class tabs-content. It is those that you need to iterate and show or hide.

Then, to decide which contents to use, you may need to use that data-tab attribute you have in your HTML (not sure, since it is nowhere referenced).

Anyway, adapt as needed:

```<code>const tabContents = document.querySelectorAll('.tabs-content');
tabs.forEach(function (activeTab, activeIndex) {
    activeTab.addEventListener("click", function (e) {
        tabs.forEach(function (tab) {
            tab.classList.toggle("active", tab == activeTab);
        });
        tabContents.forEach(function (tabContent) {
            tabContent.style.display = tabContent.dataset.tab == activeIndex + 1 ? "" : "none";
        });
    })
})
</code>```

Body:
Here we have a tab with incompled tasks and the list is supposed to be attached to the first tab(all-taks). After the task is finished it is supposed to get deleted from first list and move to second one with completed tasks. And after you switch to second tab, all the completed ones should be there. I can't figure out the way to do it.
I hope I could get some help or some detailed explanation, 'cause I have been stuck on this for some time.

Here is an image for more clarification:
[1]: https://i.stack.imgur.com/Dy0KL.png

HTML code:

To-Do List

Describe your list...

        <form action="" class="todo-form">

                <input class="todo-input" type="text" placeholder="Add a task...">

                <button class="todo-button" type="submit">Add</button>

    </form>

                All tasks (0)

                Completed (0)

JS code:

//Selectors
const todoForm = document.querySelector('.todo-form');
const todoInput = document.querySelector('.todo-input');
const todoButton = document.querySelector('.todo-button');

const tabs = document.querySelectorAll('.todo-tabs ul li');
const tabWrap = document.querySelector('.todo-tabs ul');

const undone = document.querySelector('.undone-tasks');
const done = document.querySelectorAll('.done-tasks');

//Event Listeners
tabWrap.addEventListener('click', tabs)
todoButton.addEventListener('click', addToDo);

//Functions
tabs.forEach(function (tab, tab_index) {
    tab.addEventListener("click", function () {
        tabs.forEach(function (tab) {
            tab.classList.remove("active");
        })
        tabWrap.forEach(function (todoList, todoList_index) {
            if (todoList_index == tab_index) {
                todoList.style.display = "block";
            }
            else[
                todoList.style.display = "none"
            ]
        })
    })
})

function addToDo(event) {
    //Prevent form from submitting
    event.preventDefault();

    if (todoInput.value != "") {
        const todoDiv = document.createElement('div');
        todoDiv.classList.add('todo-div');

        const inputCheckbox = document.createElement('input');
        inputCheckbox.classList.add("checkbox-incompleted");
        inputCheckbox.setAttribute('type', 'checkbox');
        todoDiv.appendChild(inputCheckbox);

        //Create li
        const newToDo = document.createElement('li');
        newToDo.classList.add('todo-item');
        newToDo.insertAdjacentText("beforeend", todoInput.value);
        todoDiv.appendChild(newToDo);
        console.log(newToDo)

        //Append to list
        undone.appendChild(todoDiv);

        //Clear todo input value
        todoInput.value = "";

        //Focusing after 1st input
        todoInput.focus();
    }
}

The commented area is what i tried to do for tabs and lists to switch, but it gives the following error:

Uncaught TypeError: tabWrap.forEach is not a function
    at HTMLLIElement.<anonymous> (script.js:32:17)
(anonymous) @ script.js:32

The error starts at the beggining of the tabWrap.forEach function. But I guess there could be other way to solve this

Body:
tabWrap is not useful for what you want: it is a single element. Instead, you'll want to iterate over the tab contents, which are identified by class tabs-content. It is those that you need to iterate and show or hide.

Then, to decide which contents to use, you may need to use that data-tab attribute you have in your HTML (not sure, since it is nowhere referenced).

Anyway, adapt as needed:

const tabContents = document.querySelectorAll('.tabs-content');
tabs.forEach(function (activeTab, activeIndex) {
    activeTab.addEventListener("click", function (e) {
        tabs.forEach(function (tab) {
            tab.classList.toggle("active", tab == activeTab);
        });
        tabContents.forEach(function (tabContent) {
            tabContent.style.display = tabContent.dataset.tab == activeIndex + 1 ? "" : "none";
        });
    })
})


问:
Rate limit policy settings is not applied using AspNetCoreRateLimit
I am using AspNetCoreRateLimit version 4.0.1 and I have done all the setup in .net core 6 web api. I can see rate limit is working when I send a call via postman.

However, when I add IpRateLimitPolicies with specific IP address, the settings won't be applied.
I use postman and this time in the proxy I added the ip address to 127.0.0.1. I can see the ip hitting the api is set correctly when I use Request.HttpContext.Connection.RemoteIpAddress;

I registered them as follow in program.cs:

```<code>    _serviceCollection.AddOptions();
    _serviceCollection.AddMemoryCache();
    _serviceCollection.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
     _serviceCollection.Configure<IpRateLimitPolicies>(builder.Configuration.GetSection("IpRateLimitPolicies"));
     _serviceCollection.AddInMemoryRateLimiting();
     _serviceCollection.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
     _serviceCollection.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
     _serviceCollection.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
     _serviceCollection.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
</code>```

Also added:
app.UseIpRateLimiting();

My appsettings also looks like:

```<code> {
  "IpRateLimiting": {
    "EnableEndpointRateLimiting": false,
    "StackBlockedRequests": false,
    "RealIPHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "IpWhitelist": [ ],
    "EndpointWhitelist": [],
    "ClientWhitelist": [],
    "HttpStatusCode": 429,
    "GeneralRules": [
      {
        "Endpoint": "*",
        "Period": "10s",
        "Limit": 1
      }
    ]
  },
  "IpRateLimitPolicies": {
    "IpRules": [
      {
        "Ip": "127.0.0.1",
        "Rules": [
          {
            "Endpoint": "*",
            "Period": "20s",
            "Limit": 2
          }
        ]
      }
    ]
  }
</code>```

But apparently the settings under IpRateLimitPolicies won't be applied.

I wonder if I have missed anything here?

Thank you

答:
After testing, I think the AspNetCoreRateLimit package is not compatible in .net5 and .net6. Maybe the .net core3.1 version will be more stable.

You can submit issues on github.

Body:
I am using AspNetCoreRateLimit version 4.0.1 and I have done all the setup in .net core 6 web api. I can see rate limit is working when I send a call via postman.

However, when I add IpRateLimitPolicies with specific IP address, the settings won't be applied.
I use postman and this time in the proxy I added the ip address to 127.0.0.1. I can see the ip hitting the api is set correctly when I use Request.HttpContext.Connection.RemoteIpAddress;

I registered them as follow in program.cs:

    _serviceCollection.AddOptions();
    _serviceCollection.AddMemoryCache();
    _serviceCollection.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
     _serviceCollection.Configure<IpRateLimitPolicies>(builder.Configuration.GetSection("IpRateLimitPolicies"));
     _serviceCollection.AddInMemoryRateLimiting();
     _serviceCollection.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
     _serviceCollection.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
     _serviceCollection.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
     _serviceCollection.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

Also added:
app.UseIpRateLimiting();

My appsettings also looks like:

 {
  "IpRateLimiting": {
    "EnableEndpointRateLimiting": false,
    "StackBlockedRequests": false,
    "RealIPHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "IpWhitelist": [ ],
    "EndpointWhitelist": [],
    "ClientWhitelist": [],
    "HttpStatusCode": 429,
    "GeneralRules": [
      {
        "Endpoint": "*",
        "Period": "10s",
        "Limit": 1
      }
    ]
  },
  "IpRateLimitPolicies": {
    "IpRules": [
      {
        "Ip": "127.0.0.1",
        "Rules": [
          {
            "Endpoint": "*",
            "Period": "20s",
            "Limit": 2
          }
        ]
      }
    ]
  }

But apparently the settings under IpRateLimitPolicies won't be applied.

I wonder if I have missed anything here?

Thank you