问:
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.

答:
I faced the same issue with the latest alpha11 cameraX library, so downgraded to

```<code>// CameraX View class
    implementation "androidx.camera:camera-view:1.0.0-alpha10"
</code>```

Also added the camera info parameter

```<code>preview?.setSurfaceProvider(viewFinder.createSurfaceProvider(camera?.cameraInfo))
</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:
I faced the same issue with the latest alpha11 cameraX library, so downgraded to

// CameraX View class
    implementation "androidx.camera:camera-view:1.0.0-alpha10"

Also added the camera info parameter

preview?.setSurfaceProvider(viewFinder.createSurfaceProvider(camera?.cameraInfo))


来源: stackexchange

问:
Using AddEventListener to change variable to 'True' using a Switch statement
I'm building a calculator in HTML, CSS & Javascript. When a user clicks a number it is added to an Array. Which Array it is added to is determined by three variables which are initially set to false. If the variable is true then that Array has already been used.

The problem I am facing is that my event listener for the operands is failing to change the value of the three variables to true when required to do so.

Initial Variables

```<code>var numberArrayOne = [];
var numberArrayTwo = [];
var numberArrayThree = [];

var operandOne = false;
var operandTwo = false;
var operandThree = false;
</code>```

This is the code that listens for operand clicks.

```<code>const operandDivide = document.querySelector('.btnDivide');
operandDivide.addEventListener('click', () => {
    switch(false){
        case (operandOne):
            var operandOne = true;
            break;
        case (operandTwo):
            var operandTwo = true;
            break;
        case (operandThree):
            var operandThree = true;
            break;
        default:
            console.log("Error");

    }
});
</code>```

This code chooses which array to place a number into.

```<code>const displayFunction = (num) => {
    switch(true){
        case (!operandOne):
            numberArrayOne.push(num);
            console.log(numberArrayOne);
            break;
        case (!operandTwo):
            numberArrayTwo.push(num);
            console.log(numberArrayTwo);
            break;
        case (!operandThree):
            numberArrayThree.push(num);
            break;
        default:
    }
};
</code>```

Clicking divide button on my calc the value remains false, it should change to true, and I am getting the console.log(error) message I added as the default.

答:
I was declaring a variable in only the function scope. Removing VAR has resolved </p>

```<code>const operandDivide = document.querySelector('.btnDivide');
operandDivide.addEventListener('click', () => {
    switch(false){
        case (operandOne):
            operandOne = true;
            break;
        case (operandTwo):
            operandTwo = true;
            break;
        case (operandThree):
            operandThree = true;
            break;
        default:
            console.log("Error");

    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm building a calculator in HTML, CSS & Javascript. When a user clicks a number it is added to an Array. Which Array it is added to is determined by three variables which are initially set to false. If the variable is true then that Array has already been used.

The problem I am facing is that my event listener for the operands is failing to change the value of the three variables to true when required to do so.

Initial Variables

var numberArrayOne = [];
var numberArrayTwo = [];
var numberArrayThree = [];

var operandOne = false;
var operandTwo = false;
var operandThree = false;

This is the code that listens for operand clicks.

const operandDivide = document.querySelector('.btnDivide');
operandDivide.addEventListener('click', () => {
    switch(false){
        case (operandOne):
            var operandOne = true;
            break;
        case (operandTwo):
            var operandTwo = true;
            break;
        case (operandThree):
            var operandThree = true;
            break;
        default:
            console.log("Error");

    }
});

This code chooses which array to place a number into.

const displayFunction = (num) => {
    switch(true){
        case (!operandOne):
            numberArrayOne.push(num);
            console.log(numberArrayOne);
            break;
        case (!operandTwo):
            numberArrayTwo.push(num);
            console.log(numberArrayTwo);
            break;
        case (!operandThree):
            numberArrayThree.push(num);
            break;
        default:
    }
};

Clicking divide button on my calc the value remains false, it should change to true, and I am getting the console.log(error) message I added as the default.

Body:
I was declaring a variable in only the function scope. Removing VAR has resolved

const operandDivide = document.querySelector('.btnDivide');
operandDivide.addEventListener('click', () => {
    switch(false){
        case (operandOne):
            operandOne = true;
            break;
        case (operandTwo):
            operandTwo = true;
            break;
        case (operandThree):
            operandThree = true;
            break;
        default:
            console.log("Error");

    }
});


问:
Wordpress Woocommerce - REST API limitation to up to 100 objects
As the documentation of woocommerce REST API (v3) stated, by default the REST API is limited to up to 100 objects to be created, updated or deleted.
https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-products
I'm wondering if it is possible to remove this limitation totally or set the limit a bit higher (to 1000 or so).
Thanks!</p>

答:
Finally found the answer here:
https://wordpress.stackexchange.com/questions/304237/increase-product-variation-limit-in-woocommerce

just add the lines below to wp-includes/functions.php

```<code>function wpse_rest_batch_items_limit( $limit ) {
    $limit = 1000;

    return $limit;
}
add_filter( 'woocommerce_rest_batch_items_limit', 'wpse_rest_batch_items_limit' );
</code>```

Body:
Finally found the answer here:
https://wordpress.stackexchange.com/questions/304237/increase-product-variation-limit-in-woocommerce

just add the lines below to wp-includes/functions.php

function wpse_rest_batch_items_limit( $limit ) {
    $limit = 1000;

    return $limit;
}
add_filter( 'woocommerce_rest_batch_items_limit', 'wpse_rest_batch_items_limit' );


问:
What is the difference between app:contentPadding and android:Padding?
I have a CardView and inside that there is a TextView. I am trying to add padding in card view. But when i use android:Padding="16dp" nothing happens between the textview and Cardview while when i use app:contentPadding="16dp" the 16dp space is created between the CardView and TextView.

Why is this happening?

答:
ContentPadding is a typealias for EdgeInsets which is used to Describe set of offsets from each of the four sides of a box.

EdgeInsets (float top, float left, float bottom, float right)


问:
Windows Command for reading bytes sent/received since network interface is connected
I want to grab the bytes send/received of a network interface on the windows command line (Win 7/Win 2008 Server).
I already tried the commands netsh, netcfg, ipconfig and net statistics.
No one of them can give me the required information, that I can already see in the interface status GUI (Activities).

Is ist possible?

答:
I think that performance monitor provides those information. - http://technet.microsoft.com/en-us/library/cc768048.aspx#XSLTsection133121120120

The link is somewhat old but you should be able to use that to obtain what you need based on the article.

ContentLicense: CC BY-SA 3.0


问:
How to get a specific value inside a foreach loop and match it in another foreach loop in PHP (codeigniter)
I have two (2) foreach loops using PHP under codeigniter. They call the same function in a controller. I want to get the value "gross_1" on the first loop then deduct it to the "gross_2" on the second loop to have a "final_gross".

Here's the Controller that I use in calling the same function (I don't have problem using these):

```<code>CONTROLLER:
$data['for_first_cutoff'] = $this->MyModel->my_function( $date_start_1, $date_end_1);
$data['for_second_cutoff'] = $this->MyModel->my_function( $date_start_2, $date_end_2 );

MODEL:
public function my_function($getDate_start, $getDate_end){
    $this->db->select('usr.*, att.id, ss.*');
    $this->db->from('usr');
    $this->db->join('att', 'att.id = att.id');
    $this->db->join('ss', 'ss.id = att.comp');
    $this->db->group_by('att.id');
    $this->db->where('att_date >=',$getDate_start);
    $this->db->where('att_date <=',$getDate_end);
    $query  = $this->db->get();

    return $query->result_array();
}
</code>```

Here's the view (first loop).

```<code><!-- first loop -->
<?php foreach ($for_first_cutoff as $emp_1):?>

<?php

   $num_of_days_1 = '12'; //auto computed based on "start1" and "end" dates1.
   $salary_cutoff_1 = $emp_1['salary'];
   $gross_1 = $salary_cutoff_1 * $num_of_days_1;
?>

   <!-- table here-->
   | <?=$emp_1['usr_fname'];?> | <?=$gross_1;?> |

<?php endforeach;?>
</code>```

(second loop) Same content but I need to deduct the gross_1 to the gross_2 to have the final_gross:

```<code><!-- Second loop -->
<?php foreach ($for_second_cutoff as $emp_2):?>

<?php
   $num_of_days_2 = '10'; //auto computed based on "start2" and "end" dates2.
   $salary_cutoff_2 = $emp_2['salary'];
   $gross_2 = $salary_cutoff_2 * $num_of_days_2;

   $final_gross = $gross_1 - $gross_2;
?>

   <!-- table here-->
  | <?=$emp_2['usr_fname'];?> | <?=$gross_2;?> | <?=$final_gross;?> |

<?php endforeach;?>
</code>```

The HTML look like this:

```<code>Loop 1
| John Doe | $100 |
| Sarah Doe | $0 |

Loop 2
| John Doe | $50 | $150 |
| Sarah Doe | $2 | $150 | <---- this is wrong. It must be only $2.
</code>```

I tried using the approach found in this [post] (How can I get outside foreach loop value in this situation?) but I don't know how to implement it using my structure.

答:
alright - based on the comments you can try the following

create an array which saves your data from the first loop - i used as key att.id (should probably your user_id) - and access to this array from your first loop with your id from the second one

```<code><!-- first loop -->
<?php
    $arrGrossData = [];
    foreach ($for_first_cutoff as $emp_1):
?>

<?php

   $num_of_days_1 = '12'; //auto computed based on "start1" and "end" dates1.
   $salary_cutoff_1 = $emp_1['salary'];
   $gross_1 = $salary_cutoff_1 * $num_of_days_1;
   $arrGrossData[$emp_1['att.id']] = $gross_1;
?>

   <!-- table here-->
   | <?=$emp_1['usr_fname'];?> | <?=$gross_1;?> |

<?php endforeach;?>

<!-- Second loop -->
<?php foreach ($for_second_cutoff as $emp_2):?>

<?php
   $num_of_days_2 = '10'; //auto computed based on "start2" and "end" dates2.
   $salary_cutoff_2 = $emp_2['salary'];
   $gross_2 = $salary_cutoff_2 * $num_of_days_2;

   $final_gross = (isset($arrGrossData[$emp_2['att.id']])) ? $arrGrossData[$emp_2['att.id']] - $gross_2 : $gross_2;
?>

   <!-- table here-->
  | <?=$emp_2['usr_fname'];?> | <?=$gross_2;?> | <?=$final_gross;?> |

<?php endforeach;?>
</code>```

Body:
I have two (2) foreach loops using PHP under codeigniter. They call the same function in a controller. I want to get the value "gross_1" on the first loop then deduct it to the "gross_2" on the second loop to have a "final_gross".

Here's the Controller that I use in calling the same function (I don't have problem using these):

CONTROLLER:
$data['for_first_cutoff'] = $this->MyModel->my_function( $date_start_1, $date_end_1);
$data['for_second_cutoff'] = $this->MyModel->my_function( $date_start_2, $date_end_2 );

MODEL:
public function my_function($getDate_start, $getDate_end){
    $this->db->select('usr.*, att.id, ss.*');
    $this->db->from('usr');
    $this->db->join('att', 'att.id = att.id');
    $this->db->join('ss', 'ss.id = att.comp');
    $this->db->group_by('att.id');
    $this->db->where('att_date >=',$getDate_start);
    $this->db->where('att_date <=',$getDate_end);
    $query  = $this->db->get();

    return $query->result_array();
}

Here's the view (first loop).

<?php foreach ($for_first_cutoff as $emp_1):?>

<?php

   $num_of_days_1 = '12'; //auto computed based on "start1" and "end" dates1.
   $salary_cutoff_1 = $emp_1['salary'];
   $gross_1 = $salary_cutoff_1 * $num_of_days_1;
?>

   | <?=$emp_1['usr_fname'];?> | <?=$gross_1;?> |

<?php endforeach;?>

(second loop) Same content but I need to deduct the gross_1 to the gross_2 to have the final_gross:

<?php foreach ($for_second_cutoff as $emp_2):?>

<?php
   $num_of_days_2 = '10'; //auto computed based on "start2" and "end" dates2.
   $salary_cutoff_2 = $emp_2['salary'];
   $gross_2 = $salary_cutoff_2 * $num_of_days_2;

   $final_gross = $gross_1 - $gross_2;
?>

  | <?=$emp_2['usr_fname'];?> | <?=$gross_2;?> | <?=$final_gross;?> |

<?php endforeach;?>

The HTML look like this:

Loop 1
| John Doe | $100 |
| Sarah Doe | $0 |

Loop 2
| John Doe | $50 | $150 |
| Sarah Doe | $2 | $150 | <---- this is wrong. It must be only $2.

I tried using the approach found in this [post] (How can I get outside foreach loop value in this situation?) but I don't know how to implement it using my structure.

Body:
alright - based on the comments you can try the following

create an array which saves your data from the first loop - i used as key att.id (should probably your user_id) - and access to this array from your first loop with your id from the second one

<!-- first loop -->
<?php
    $arrGrossData = [];
    foreach ($for_first_cutoff as $emp_1):
?>

<?php

   $num_of_days_1 = '12'; //auto computed based on "start1" and "end" dates1.
   $salary_cutoff_1 = $emp_1['salary'];
   $gross_1 = $salary_cutoff_1 * $num_of_days_1;
   $arrGrossData[$emp_1['att.id']] = $gross_1;
?>

   <!-- table here-->
   | <?=$emp_1['usr_fname'];?> | <?=$gross_1;?> |

<?php endforeach;?>

<!-- Second loop -->
<?php foreach ($for_second_cutoff as $emp_2):?>

<?php
   $num_of_days_2 = '10'; //auto computed based on "start2" and "end" dates2.
   $salary_cutoff_2 = $emp_2['salary'];
   $gross_2 = $salary_cutoff_2 * $num_of_days_2;

   $final_gross = (isset($arrGrossData[$emp_2['att.id']])) ? $arrGrossData[$emp_2['att.id']] - $gross_2 : $gross_2;
?>

   <!-- table here-->
  | <?=$emp_2['usr_fname'];?> | <?=$gross_2;?> | <?=$final_gross;?> |

<?php endforeach;?>


问:
Mac freezes when running compiles c application
For a long time I have been trying to compile and run c programs on my MacBook Pro running macOS Catalina, I’ve tried compiling with cc, gcc and clang and the compilation seems to work just fine but every time I run the .out file my Mac freezes, I can’t control+c out of the application and even if I terminate the terminal the issue continues with the finder app (it completely stops responding), so in order to fix the problem I have to completely shut the computer off and then turn it on again via the power button.
This issue happens with every program that I have tried, including the “hello, world” program.

I have compiled a minimal test with gcc -v -o demo demo.c and the output is:

```<code>Apple clang version 11.0.3 (clang-1103.0.32.62)
Target: x86_64-apple-darwin19.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
 "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.15.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name demo.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=all -fno-strict-return -masm-verbose -munwind-tables -target-sdk-version=10.15.4 -target-cpu penryn -dwarf-column-info -debugger-tuning=lldb -target-linker-version 556.6 -v -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk -I/usr/local/include -internal-isystem /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/local/include -internal-isystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3/include -internal-externc-isystem /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include -internal-externc-isystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Wno-objc-signed-char-bool-implicit-int-conversion -Wno-extra-semi-stmt -Wno-quoted-include-in-framework-header -fdebug-compilation-dir /Users/user -ferror-limit 19 -fmessage-length 80 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fobjc-runtime=macosx-10.15.0 -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -o /var/folders/xj/rw_jny791d9c83w_rplgscnw0000gn/T/demo-635cdc.o -x c demo.c
clang -cc1 version 11.0.3 (clang-1103.0.32.62) default target x86_64-apple-darwin19.4.0
ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/local/include"
ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks"
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks (framework directory)
End of search list.
 "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -lto_library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/libLTO.dylib -no_deduplicate -dynamic -arch x86_64 -platform_version macos 10.15.0 10.15.4 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk -o demo /var/folders/xj/rw_jny791d9c83w_rplgscnw0000gn/T/demo-635cdc.o -L/usr/local/lib -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3/lib/darwin/libclang_rt.osx.a
</code>```

答:
The solution was to run this command:

```<code>export CPATH=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/
</code>```

For anyone else that experiences this issue, please see discussion at: Can't compile a C program on a Mac after upgrading to Catalina 10.15

Body:
For a long time I have been trying to compile and run c programs on my MacBook Pro running macOS Catalina, I’ve tried compiling with cc, gcc and clang and the compilation seems to work just fine but every time I run the .out file my Mac freezes, I can’t control+c out of the application and even if I terminate the terminal the issue continues with the finder app (it completely stops responding), so in order to fix the problem I have to completely shut the computer off and then turn it on again via the power button.
This issue happens with every program that I have tried, including the “hello, world” program.

I have compiled a minimal test with gcc -v -o demo demo.c and the output is:

Apple clang version 11.0.3 (clang-1103.0.32.62)
Target: x86_64-apple-darwin19.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
 "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.15.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name demo.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=all -fno-strict-return -masm-verbose -munwind-tables -target-sdk-version=10.15.4 -target-cpu penryn -dwarf-column-info -debugger-tuning=lldb -target-linker-version 556.6 -v -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk -I/usr/local/include -internal-isystem /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/local/include -internal-isystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3/include -internal-externc-isystem /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include -internal-externc-isystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Wno-objc-signed-char-bool-implicit-int-conversion -Wno-extra-semi-stmt -Wno-quoted-include-in-framework-header -fdebug-compilation-dir /Users/user -ferror-limit 19 -fmessage-length 80 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fobjc-runtime=macosx-10.15.0 -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -o /var/folders/xj/rw_jny791d9c83w_rplgscnw0000gn/T/demo-635cdc.o -x c demo.c
clang -cc1 version 11.0.3 (clang-1103.0.32.62) default target x86_64-apple-darwin19.4.0
ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/local/include"
ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks"
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks (framework directory)
End of search list.
 "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -lto_library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/libLTO.dylib -no_deduplicate -dynamic -arch x86_64 -platform_version macos 10.15.0 10.15.4 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk -o demo /var/folders/xj/rw_jny791d9c83w_rplgscnw0000gn/T/demo-635cdc.o -L/usr/local/lib -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3/lib/darwin/libclang_rt.osx.a

Body:
The solution was to run this command:

export CPATH=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/

For anyone else that experiences this issue, please see discussion at: Can't compile a C program on a Mac after upgrading to Catalina 10.15


问:
What is the best way to make clickable text in java?
This is for an application so I don't want a hyperlink. I first tried using a Jbutton without all of border/background stuff and then hooking up an actionListener to it but I couldn't get it to the point where I thought it looked nice.  I also tried using a JLabel and hooking up a mouse listener to that but I also couldn't get it to look right.

Basically I would like a way using swing to make a button exactly like a url link in an application.  What is the standard way of doing this?

答: that isn't answer to your question but are you tried to add ButtonModel to your JButton example here</p>


问:
MessageBox.Show not working with my visual studio
Hello I'm practicing on typing codes of inventory system of products for the pos software.
 I'm working on something like here:

Click here to see my products of inventory sketch.

And after a click on the save button for the results of the database then it should show up like the "record added...." window. And I don't see the result even I don't see any error on my visual studio pro software.

And please let me know which part is wrong and how to fix that.

Here is my code of salesn.cs file

```<code>using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace superpos3
{
    public partial class salesn : Form
    {
        public salesn()
        {
            InitializeComponent();
        }

        int totalPrice = 0;

        MySqlConnection con = new MySqlConnection("server= localhost; database =superpos;  username= root; password=; ");
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtno_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtqty.Enabled = true;
                txtqty.Focus();
            }
        }

        private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {

                try
                {

                    string txt = "select * from products where id='" + txtno.Text + "'";
                    MySqlCommand cmd = new MySqlCommand(txt, con);
                    con.Open();
                    MySqlDataReader r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        int price = int.Parse(txtqty.Text.ToString()) * int.Parse(r[4].ToString());
                        totalPrice = totalPrice + price;
                        //discount
                        // totalPrice = totalPrice - totalPrice* Payment.discount/100;

                        dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);

                    }
                    lbitems.Text = " " + (dataGridView1.RowCount - 1) + "";
                    lbtotal.Text = " " + totalPrice + " ";

                    con.Close();

                }

                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "Error From Database");
                }

                txtno.Focus();
                txtno.Clear();

                txtqty.Enabled = false;
                txtqty.Clear();

            }

        }

        private void txtqty_TextChanged(object sender, EventArgs e)
        {

        }

        private void salesn_Load(object sender, EventArgs e)
        {
            lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            lbltime.Text = DateTime.Now.ToShortTimeString();

            con.Open();
            string query = "select max(id) from salesmain ";
            MySqlCommand cmd2 = new MySqlCommand(query, con);
            MySqlDataReader dr;
            dr = cmd2.ExecuteReader();
            if (dr.Read())
            {
                string val = dr[0].ToString();
                if (val == "")
                {
                    lbinvoice.Text = "1";

                }
                else
                {
                    int a;

                    a = int.Parse(dr[0].ToString());
                    a = a + 1;
                    lbinvoice.Text = a.ToString();

                }
                con.Close();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,price,grosstotal)values(@salesid,@productname,@qty,@price,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@price", dataGridView1.Rows[i].Cells[4].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[5].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,qty,grosstotal)values(@id,@date,@time,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                    cmd.ExecuteNonQuery();
                    cmd1.ExecuteNonQuery();
                    MessageBox.Show("Record added ..........");
                    con.Close();

                }
               }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }

            finally
            {
                con.Close();
            }
           }
       }
}
</code>```

答:
I guess you should check if the dataGridView1.Rows.Count is not zero because if it is, the for loop won't even run which means that neither your code nor the message box show method is gonna run.

the other MessageBox.Show() methods are inside catch blocks which obviously means that they won't run if the catch block doesn't catch any errors.

Body:
Hello I'm practicing on typing codes of inventory system of products for the pos software.
 I'm working on something like here:

Click here to see my products of inventory sketch.

And after a click on the save button for the results of the database then it should show up like the "record added...." window. And I don't see the result even I don't see any error on my visual studio pro software.

And please let me know which part is wrong and how to fix that.

Here is my code of salesn.cs file

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace superpos3
{
    public partial class salesn : Form
    {
        public salesn()
        {
            InitializeComponent();
        }

        int totalPrice = 0;

        MySqlConnection con = new MySqlConnection("server= localhost; database =superpos;  username= root; password=; ");
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtno_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtqty.Enabled = true;
                txtqty.Focus();
            }
        }

        private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {

                try
                {

                    string txt = "select * from products where id='" + txtno.Text + "'";
                    MySqlCommand cmd = new MySqlCommand(txt, con);
                    con.Open();
                    MySqlDataReader r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        int price = int.Parse(txtqty.Text.ToString()) * int.Parse(r[4].ToString());
                        totalPrice = totalPrice + price;
                        //discount
                        // totalPrice = totalPrice - totalPrice* Payment.discount/100;

                        dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);

                    }
                    lbitems.Text = " " + (dataGridView1.RowCount - 1) + "";
                    lbtotal.Text = " " + totalPrice + " ";

                    con.Close();

                }

                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "Error From Database");
                }

                txtno.Focus();
                txtno.Clear();

                txtqty.Enabled = false;
                txtqty.Clear();

            }

        }

        private void txtqty_TextChanged(object sender, EventArgs e)
        {

        }

        private void salesn_Load(object sender, EventArgs e)
        {
            lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            lbltime.Text = DateTime.Now.ToShortTimeString();

            con.Open();
            string query = "select max(id) from salesmain ";
            MySqlCommand cmd2 = new MySqlCommand(query, con);
            MySqlDataReader dr;
            dr = cmd2.ExecuteReader();
            if (dr.Read())
            {
                string val = dr[0].ToString();
                if (val == "")
                {
                    lbinvoice.Text = "1";

                }
                else
                {
                    int a;

                    a = int.Parse(dr[0].ToString());
                    a = a + 1;
                    lbinvoice.Text = a.ToString();

                }
                con.Close();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,price,grosstotal)values(@salesid,@productname,@qty,@price,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@price", dataGridView1.Rows[i].Cells[4].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[5].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,qty,grosstotal)values(@id,@date,@time,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                    cmd.ExecuteNonQuery();
                    cmd1.ExecuteNonQuery();
                    MessageBox.Show("Record added ..........");
                    con.Close();

                }
               }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }

            finally
            {
                con.Close();
            }
           }
       }
}


问:
How will you convert method to single line in java8
I am having following method which converts single line to map

And want to convert it to single line statement using java8

input pipe separated string
e.g.:
status:MYSTATUS|data1:value1

```<code>public Map<String, String> getMap(String attributeUpdate){
    Map<String, String> attr = new HashMap<>();
    if(StringUtils.isNotEmpty(attributeUpdate)){
        List<String> a = Arrays.asList(attributeUpdate.split("\\|"));
        for (String s : a) {
            String[] key_val = s.split(":");
            if(key_val.length == 2) {
                attr.put(key_val[0], key_val[1]);
            }
        }
    }
    return attr;
}
</code>```

答:
Please try this following code. It works fine.

```<code>String s = new String("status:MYSTATUS|data1:value1");
Arrays.stream(s.split("\\|")).map(stringArray -> stringArray.split(":"))
        .filter(stringArray -> stringArray.length == 2)
        .collect(Collectors.toMap(stringArray ->stringArray[0], stringArray-> stringArray[1],(oldvalue,newvalue)->newvalue));
</code>```

Thanks

Body:
I am having following method which converts single line to map

And want to convert it to single line statement using java8

input pipe separated string
e.g.:
status:MYSTATUS|data1:value1

public Map<String, String> getMap(String attributeUpdate){
    Map<String, String> attr = new HashMap<>();
    if(StringUtils.isNotEmpty(attributeUpdate)){
        List<String> a = Arrays.asList(attributeUpdate.split("\\|"));
        for (String s : a) {
            String[] key_val = s.split(":");
            if(key_val.length == 2) {
                attr.put(key_val[0], key_val[1]);
            }
        }
    }
    return attr;
}

Body:
Please try this following code. It works fine.

String s = new String("status:MYSTATUS|data1:value1");
Arrays.stream(s.split("\\|")).map(stringArray -> stringArray.split(":"))
        .filter(stringArray -> stringArray.length == 2)
        .collect(Collectors.toMap(stringArray ->stringArray[0], stringArray-> stringArray[1],(oldvalue,newvalue)->newvalue));

Thanks


问:
Receiving KeyError: "None of [Int64Index([ ... dtype='int64', length=1323)] are in the [columns]"

SUMMARY

When feeding test and train data into a ROC curve plot, I receive the following error:

KeyError: "None of [Int64Index([   0,    1,    2, ... dtype='int64', length=1323)] are in the [columns]"

The error seems to be saying that it doesn't like the format of my data, but it worked when run the first time and I haven't been able to get it to run again.

Am I incorrectly splitting my data or sending incorrectly formatted data into my function?

WHAT I'VE TRIED

Read through several StackOverflow posts with the same KeyError

Re-ead through scikit-learn example I followed

Reviewed previous versions of my code to troubleshoot

I am running this within a CoLab document and it can be viewed here

CODE

I am using standard dataframes to pull in my X and Y sets:

```<code>X = df_full.drop(['Attrition'], axis=1)
y = df_full['Attrition'].as_matrix()
</code>```

The KeyError traces back to the 8th line here:

```<code>def roc_plot(X, Y, Model):
    tprs = []
    aucs = []
    mean_fpr = np.linspace(0, 1, 100)
    plt.figure(figsize=(12,8))
    i = 0
    for train, test in kf.split(X, Y):
        probas_ = model.fit(X[train], Y[train]).predict_proba(X[test])
        # Compute ROC curve and area the curve
        fpr, tpr, thresholds = roc_curve(Y[test], probas_[:, 1])
        tprs.append(np.interp(mean_fpr, fpr, tpr))
        tprs[-1][0] = 0.0
        roc_auc = auc(fpr, tpr)
        aucs.append(roc_auc)
        plt.plot(fpr, tpr, lw=1, alpha=0.3,
                 label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc))

        i += 1
    plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',
             label='Chance', alpha=.8)

    mean_tpr = np.mean(tprs, axis=0)
    mean_tpr[-1] = 1.0
    mean_auc = auc(mean_fpr, mean_tpr)
    std_auc = np.std(aucs)
    plt.plot(mean_fpr, mean_tpr, color='b',
             label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (mean_auc, std_auc),
             lw=2, alpha=.8)

    std_tpr = np.std(tprs, axis=0)
    tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
    tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
    plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,
                     label=r'$\pm$ 1 std. dev.')

    plt.xlim([-0.05, 1.05])
    plt.ylim([-0.05, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic example')
    plt.legend(loc="lower right")
    plt.show()
</code>```

It happens when I run the following with the function:

```<code>model = XGBClassifier() # Create the Model
roc_plot(X, Y, Model)
</code>```

EXPECTED RESULT

I should be able to feed the data, X and Y, into my function.

答:
in this piece of code train, test are arrays of indices, while you using it as a columns when selection from DataFrame:

```<code>for train, test in kf.split(X, Y):
    probas_ = model.fit(X[train], Y[train]).predict_proba(X[test])
</code>```

you should use iloc instead:

```<code>    probas_ = model.fit(X.iloc[train], Y.iloc[train]).predict_proba(X.iloc[test])
</code>```

Body:
SUMMARY

When feeding test and train data into a ROC curve plot, I receive the following error:

KeyError: "None of [Int64Index([   0,    1,    2, ... dtype='int64', length=1323)] are in the [columns]"

The error seems to be saying that it doesn't like the format of my data, but it worked when run the first time and I haven't been able to get it to run again.

Am I incorrectly splitting my data or sending incorrectly formatted data into my function?

WHAT I'VE TRIED

Read through several StackOverflow posts with the same KeyError

Re-ead through scikit-learn example I followed

Reviewed previous versions of my code to troubleshoot

I am running this within a CoLab document and it can be viewed here

CODE

I am using standard dataframes to pull in my X and Y sets:

X = df_full.drop(['Attrition'], axis=1)
y = df_full['Attrition'].as_matrix()

The KeyError traces back to the 8th line here:

def roc_plot(X, Y, Model):
    tprs = []
    aucs = []
    mean_fpr = np.linspace(0, 1, 100)
    plt.figure(figsize=(12,8))
    i = 0
    for train, test in kf.split(X, Y):
        probas_ = model.fit(X[train], Y[train]).predict_proba(X[test])
        # Compute ROC curve and area the curve
        fpr, tpr, thresholds = roc_curve(Y[test], probas_[:, 1])
        tprs.append(np.interp(mean_fpr, fpr, tpr))
        tprs[-1][0] = 0.0
        roc_auc = auc(fpr, tpr)
        aucs.append(roc_auc)
        plt.plot(fpr, tpr, lw=1, alpha=0.3,
                 label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc))

        i += 1
    plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',
             label='Chance', alpha=.8)

    mean_tpr = np.mean(tprs, axis=0)
    mean_tpr[-1] = 1.0
    mean_auc = auc(mean_fpr, mean_tpr)
    std_auc = np.std(aucs)
    plt.plot(mean_fpr, mean_tpr, color='b',
             label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (mean_auc, std_auc),
             lw=2, alpha=.8)

    std_tpr = np.std(tprs, axis=0)
    tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
    tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
    plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,
                     label=r'$\pm$ 1 std. dev.')

    plt.xlim([-0.05, 1.05])
    plt.ylim([-0.05, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic example')
    plt.legend(loc="lower right")
    plt.show()

It happens when I run the following with the function:

model = XGBClassifier() # Create the Model
roc_plot(X, Y, Model)

EXPECTED RESULT

I should be able to feed the data, X and Y, into my function.

Body:
in this piece of code train, test are arrays of indices, while you using it as a columns when selection from DataFrame:

for train, test in kf.split(X, Y):
    probas_ = model.fit(X[train], Y[train]).predict_proba(X[test])

you should use iloc instead:

    probas_ = model.fit(X.iloc[train], Y.iloc[train]).predict_proba(X.iloc[test])


问:
Why kakfa topic partition is not receiving messages?
I have a kafka cluster with 3 brokers and a topic with 8 partitions.
A producer written in java using spring boot and without custom rule for load balancing. It means it should do round robin.

The issue is that there are some partitions there are not receiving messages into it. I figured it out checking what the 4 consumers are receiving and even they are processing all messages there is a consumer idle all the time because it has received just one message.

What could be the issue?
Kafka version I'm using is 0.10.1.1
Additional note in this case I'm not using replicas for the partitions

答:
It means it should do round robin.

It will only do round robin, if you have no keys in your Kafka messages. Otherwise, the messages are partitioned based on a hash value of the key:

```<code>hash(key) % number_of_partitions
</code>```

It is not unusal, that this will cause some partitions to not receive any messages at all. Imagine a case, where you are using a key that can only have two different values. In that case, all your data will flow into only two partitions, independent of the number of partitions in your topic.

Body:
It means it should do round robin.

It will only do round robin, if you have no keys in your Kafka messages. Otherwise, the messages are partitioned based on a hash value of the key:

hash(key) % number_of_partitions

It is not unusal, that this will cause some partitions to not receive any messages at all. Imagine a case, where you are using a key that can only have two different values. In that case, all your data will flow into only two partitions, independent of the number of partitions in your topic.


问:
Angular 8 Typescript How to set value of export const from another component?
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

```<code>var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];
</code>```

答:
You can not change the value of the variable from any other component as this variable is not accessible from that component.

You dont have to do anything big. You just have to export this variable and import this variable in the other component.

```<code>Export bdg_m_1:string = '10'
</code>```

And import the variable using.

```<code>import bdg_m_1 from nav.ts
</code>```

And change the value from the other component using.

```<code>bdg_m_1 = 'abc'
</code>```

You can also change the name while importing the variable by using:

```<code>import bdg_m_1 as myConst from nav.ts
myConst = 'abc'
</code>```

Body:
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];

Body:
You can not change the value of the variable from any other component as this variable is not accessible from that component.

You dont have to do anything big. You just have to export this variable and import this variable in the other component.

Export bdg_m_1:string = '10'

And import the variable using.

import bdg_m_1 from nav.ts

And change the value from the other component using.

bdg_m_1 = 'abc'

You can also change the name while importing the variable by using:

import bdg_m_1 as myConst from nav.ts
myConst = 'abc'


问:
TSQL to get missing records inside IN operator
I have a table like below in SQL Server:

```<code>create table address (id int, city varchar(10));

insert into address values (1, 'Rome');
insert into address values (2, 'Dallas');
insert into address values (3, 'Cracow');
insert into address values (4, 'Moscow');
insert into address values (5, 'Liverpool');
insert into address values (6, 'Cracow');
insert into address values (7, 'Seoul');
</code>```

I'm writing a query with the IN operator as

```<code>SELECT City
FROM address
WHERE city IN ('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow')
</code>```

I can get the result, but I want to get the list of missing or not available records in the table like

```<code>|  City  |  Status   |
+--------+-----------+
| Rome   | Available |
| Dallas | Available |
| Moscow | Available |
| Mumbai | Missing   |
| Delhi  | Missing   |
+--------+-----------+
</code>```

答:
You can use IIF

```<code>SELECT [City],
   IIF([City] IN('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow'), 'Available', 'Missing') STATUS
FROM [Address];
</code>```

Result

Body:
I have a table like below in SQL Server:

create table address (id int, city varchar(10));

insert into address values (1, 'Rome');
insert into address values (2, 'Dallas');
insert into address values (3, 'Cracow');
insert into address values (4, 'Moscow');
insert into address values (5, 'Liverpool');
insert into address values (6, 'Cracow');
insert into address values (7, 'Seoul');

I'm writing a query with the IN operator as

SELECT City
FROM address
WHERE city IN ('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow')

I can get the result, but I want to get the list of missing or not available records in the table like

|  City  |  Status   |
+--------+-----------+
| Rome   | Available |
| Dallas | Available |
| Moscow | Available |
| Mumbai | Missing   |
| Delhi  | Missing   |
+--------+-----------+

Body:
You can use IIF

SELECT [City],
   IIF([City] IN('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow'), 'Available', 'Missing') STATUS
FROM [Address];

Result


问:
.Net Core 3.1 - Mutiple hosted services with independent configurations
As far I know, it's possible to add multiple hosted services to run under the same 'host', like this example took from Microsoft page:

```<code>public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //Other DI registrations;

    // Register Hosted Services
    services.AddHostedService<GracePeriodManagerService>();
    services.AddHostedService<MyHostedServiceB>();
    services.AddHostedService<MyHostedServiceC>();
    //...
}

</code>```

If instead of that I create three different projects, It would be possible to inject three different configurations for each one of them.

Is there any way to do that in same project? Maybe loading different configuration files(appsettings.json)?

Like:

For hosted service GracePeriodManagerService appsettings.graceperiod.json

For hosted service MyHostedServiceB appsettings.myHostedServiceB.json

Or separating it by folders:

For hosted service GracePeriodManagerService GracePeriodManagerService\appsettings.json

For hosted service MyHostedServiceB MyHostedServiceB\appsettings.json

答: When configuring your application, you can define where to get configuration from (see this blogpost for instance). Each file could have a section with the settings you want and the individual hosted services could get their relevant configuration by using configuration.GetSection().

Body:
As far I know, it's possible to add multiple hosted services to run under the same 'host', like this example took from Microsoft page:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //Other DI registrations;

    // Register Hosted Services
    services.AddHostedService<GracePeriodManagerService>();
    services.AddHostedService<MyHostedServiceB>();
    services.AddHostedService<MyHostedServiceC>();
    //...
}

If instead of that I create three different projects, It would be possible to inject three different configurations for each one of them.

Is there any way to do that in same project? Maybe loading different configuration files(appsettings.json)?

Like:

For hosted service GracePeriodManagerService appsettings.graceperiod.json

For hosted service MyHostedServiceB appsettings.myHostedServiceB.json

Or separating it by folders:

For hosted service GracePeriodManagerService GracePeriodManagerService\appsettings.json

For hosted service MyHostedServiceB MyHostedServiceB\appsettings.json


问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答: C# is the very much so a high level language and is more developed than most scripting languages.  As far as I've ever learned, there is no such thing as a medium level language and the ones considered low level these days is pretty much any form of assembly or binary code.</p>

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?


问:
database timeout error resolution problem
Hi I am having some problems in my app for the database timeout. Due to some network glitches the query takes more than 45 sec to return the resultset which has about 10,000 rows. Most of the time its fast upto 11-12 secs. My app is runs as a scheduled job in the background.

The problem is I need to try three times if i get the timeout exception before writing the error to the error log or exiting. I know i can set the command timeout property to 60 seconds but still i want to try three times before exiting. I have written a method for that but I think there is some flaw in my method.

For now i specifically set the timeout to be 5 seconds as i know well that it takes more than 25 seconds for this stored proc to run. I just want to get that timeout expired exception and write ways to handle it.

My problem is if after 2 times I set the connection timeout to 50 so my method goes and get the correct list but it again goes inside the methodname which i have called inside the catch statement and finally returns nothing. It looks like its getting into recursion or something but i am confused as to where i am wrong.

Any hints or pointers will be helpful in clarifying my concept.

```<code>Private Shared timeoutcounter As Integer = 0
Private Shared dbConnectionString As String = ConfigurationManager.AppSettings("DBConn")

Public Shared Function GetPurgeList() As DestList

    Dim AcInfo As DestInfo = Nothing
    Dim tempList As DestList= Nothing
    Dim ConnectionString As String = dbConnectionString
    Dim cn As New SqlConnection(ConnectionString)
    Dim cmd As SqlCommand = Nothing
    Dim dr As SqlDataReader = Nothing

    Try
        cn.Open()
        cmd = New SqlCommand
        With cmd
            .Connection = cn
            .CommandType = CommandType.StoredProcedure
            .CommandText = "usp_abcd"
            .CommandTimeout = 5
            dr = .ExecuteReader
            If dr.HasRows Then
                tempList = New DestList()
                While dr.Read()
                    If dr.GetName(0).ToString() = "errnum" Then
                        ErrorLogger.WriteToErrorLog("Error from stored proc usp_abcd" + CStr(dr("errnum")), dr("errmsg"))
                    Else
                        AcInfo = New DestInfo
...
//fill object
...
                           tempList.Add(AccountInfo)
                    End If
                End While
            End If
        End With

    Catch ex As Exception
       If ex.Message.ToUpper.Contains("Timeout Expired".ToUpper) Then
            timeoutcounter = timeoutcounter + 1
            If timeoutcounter > 2 Then
                timeoutcounter = 0
                ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList timeoutCounter > 3 : " + ex.Message, ex.StackTrace)
            Else
------------>  GetPurgeList() 'it gets here after getting the correct list and I am confused why does it come back here again and then finally return nothing
            End If
        Else
            ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList : " + ex.Message, ex.StackTrace)

        End If

    Finally
        If dr IsNot Nothing Then
            dr.Close()
            dr = Nothing
        End If
        If cmd IsNot Nothing Then
            cmd.Dispose()
            cmd = Nothing
        End If
        If cn IsNot Nothing Then
            cn.Close()
            cn.Dispose()
            cn = Nothing
        End If
    End Try
    Return tempList
End Function
</code>```

答:
Change...

```<code>GetPurgeList() 'it gets here after getting the correct list and I am confused why does it come back here again and then finally return nothing
</code>```

Into..

```<code>tempList = New DestList()

tempList = GetPurgeList()
</code>```

Body:
Hi I am having some problems in my app for the database timeout. Due to some network glitches the query takes more than 45 sec to return the resultset which has about 10,000 rows. Most of the time its fast upto 11-12 secs. My app is runs as a scheduled job in the background.

The problem is I need to try three times if i get the timeout exception before writing the error to the error log or exiting. I know i can set the command timeout property to 60 seconds but still i want to try three times before exiting. I have written a method for that but I think there is some flaw in my method.

For now i specifically set the timeout to be 5 seconds as i know well that it takes more than 25 seconds for this stored proc to run. I just want to get that timeout expired exception and write ways to handle it.

My problem is if after 2 times I set the connection timeout to 50 so my method goes and get the correct list but it again goes inside the methodname which i have called inside the catch statement and finally returns nothing. It looks like its getting into recursion or something but i am confused as to where i am wrong.

Any hints or pointers will be helpful in clarifying my concept.

Private Shared timeoutcounter As Integer = 0
Private Shared dbConnectionString As String = ConfigurationManager.AppSettings("DBConn")

Public Shared Function GetPurgeList() As DestList

    Dim AcInfo As DestInfo = Nothing
    Dim tempList As DestList= Nothing
    Dim ConnectionString As String = dbConnectionString
    Dim cn As New SqlConnection(ConnectionString)
    Dim cmd As SqlCommand = Nothing
    Dim dr As SqlDataReader = Nothing

    Try
        cn.Open()
        cmd = New SqlCommand
        With cmd
            .Connection = cn
            .CommandType = CommandType.StoredProcedure
            .CommandText = "usp_abcd"
            .CommandTimeout = 5
            dr = .ExecuteReader
            If dr.HasRows Then
                tempList = New DestList()
                While dr.Read()
                    If dr.GetName(0).ToString() = "errnum" Then
                        ErrorLogger.WriteToErrorLog("Error from stored proc usp_abcd" + CStr(dr("errnum")), dr("errmsg"))
                    Else
                        AcInfo = New DestInfo
...
//fill object
...
                           tempList.Add(AccountInfo)
                    End If
                End While
            End If
        End With

    Catch ex As Exception
       If ex.Message.ToUpper.Contains("Timeout Expired".ToUpper) Then
            timeoutcounter = timeoutcounter + 1
            If timeoutcounter > 2 Then
                timeoutcounter = 0
                ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList timeoutCounter > 3 : " + ex.Message, ex.StackTrace)
            Else
------------>  GetPurgeList() 'it gets here after getting the correct list and I am confused why does it come back here again and then finally return nothing
            End If
        Else
            ErrorLogger.WriteToErrorLog("Exception from method GetPurgeList : " + ex.Message, ex.StackTrace)

        End If

    Finally
        If dr IsNot Nothing Then
            dr.Close()
            dr = Nothing
        End If
        If cmd IsNot Nothing Then
            cmd.Dispose()
            cmd = Nothing
        End If
        If cn IsNot Nothing Then
            cn.Close()
            cn.Dispose()
            cn = Nothing
        End If
    End Try
    Return tempList
End Function

Body:
Change...

GetPurgeList() 'it gets here after getting the correct list and I am confused why does it come back here again and then finally return nothing

Into..

tempList = New DestList()

tempList = GetPurgeList()


问:
JS: Object restructuring (using map) - add regex to some value
I can execute this code only that it works on the array:

```<code>bills.map((bill) => ({
        ...bill,
        amountMoney: bill.amountMoney.replace(/\B(?=(\d{3})+(?!\d))/g, ' '),
        accountBillNumber: bill.accountBillNumber
          .replace(/(^\d{2}|\d{4})+?/g, '$1 ')
          .trim(),
      }));
</code>```

Unfortunately, but this time, my bills is an object with the same structure.

```<code>const bills = { amountMoney: 0.22, accountBillNumber: 1234567890 }
</code>```

I would like to restructure it and add regex formatting to the value, just like I do for bills array.

答:
Your question is just about how to handle a single object instead of an array? If so, you can just extract out your formatting function:</p>

```<code>const formatSingleBill = (bill) => ({
  ...bill,
  amountMoney: bill.amountMoney.replace(/\B(?=(\d{3})+(?!\d))/g, ' '),
  accountBillNumber: bill.accountBillNumber
    .replace(/(^\d{2}|\d{4})+?/g, '$1 ')
    .trim(),
});

// If you have an array
bills.map(formatSingleBill);

// If you have a single object
const bills = { amountMoney: '0.22', accountBillNumber: '1234567890' }
const reformatted = formatSingleBill(bills);
</code>```

Body:
I can execute this code only that it works on the array:

bills.map((bill) => ({
        ...bill,
        amountMoney: bill.amountMoney.replace(/\B(?=(\d{3})+(?!\d))/g, ' '),
        accountBillNumber: bill.accountBillNumber
          .replace(/(^\d{2}|\d{4})+?/g, '$1 ')
          .trim(),
      }));

Unfortunately, but this time, my bills is an object with the same structure.

const bills = { amountMoney: 0.22, accountBillNumber: 1234567890 }

I would like to restructure it and add regex formatting to the value, just like I do for bills array.

Body:
Your question is just about how to handle a single object instead of an array? If so, you can just extract out your formatting function:

const formatSingleBill = (bill) => ({
  ...bill,
  amountMoney: bill.amountMoney.replace(/\B(?=(\d{3})+(?!\d))/g, ' '),
  accountBillNumber: bill.accountBillNumber
    .replace(/(^\d{2}|\d{4})+?/g, '$1 ')
    .trim(),
});

// If you have an array
bills.map(formatSingleBill);

// If you have a single object
const bills = { amountMoney: '0.22', accountBillNumber: '1234567890' }
const reformatted = formatSingleBill(bills);


问:
C++: Access private member vector of structs from other class
from a similiar question here
I tried the solution

```<code>class A {
 ...
  public:

    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
};
</code>```

but always get error: 'DataStruct' was not declared in this scope.
DataStruct and vec_A are defined in private section , below public section, in same class.

Please, could someone help me.

Regards,
Thomas

答:
Firstly, the the return type declarator part std::vector<DataStruct> requires a complete type in this context. That's what that error signifies. Class definition block can look forward for identifiers and signatures of members , but it cannot look for type definition.

Class A is not complete until its closing brace. Consecutively, nested classes defined aren't complete until theirs closing braces. Following declaration is correct one:

```<code>class A
{
private:
    struct DataStruct {
    }; // a complete type
public:
    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
private:
   std::vector<DataStruct> vec_A;
};
</code>```

In any other case you could forward declare it as struct A::DataStruct.

Body:
from a similiar question here
I tried the solution

class A {
 ...
  public:

    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
};

but always get error: 'DataStruct' was not declared in this scope.
DataStruct and vec_A are defined in private section , below public section, in same class.

Please, could someone help me.

Regards,
Thomas

Body:
Firstly, the the return type declarator part std::vector<DataStruct> requires a complete type in this context. That's what that error signifies. Class definition block can look forward for identifiers and signatures of members , but it cannot look for type definition.

Class A is not complete until its closing brace. Consecutively, nested classes defined aren't complete until theirs closing braces. Following declaration is correct one:

class A
{
private:
    struct DataStruct {
    }; // a complete type
public:
    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
private:
   std::vector<DataStruct> vec_A;
};

In any other case you could forward declare it as struct A::DataStruct.


问:
Ways to speedup solution time for a large LP (>10 million decision variables)
I have a large LP with more than 10 million decision variables and nearly the same number of constraints. I use CPLEX to solve the LP but it takes ~20 hours to solve, and that's on the best server of our institution.

Are there ways to significantly speedup the solution time (without adding more servers)?

I've read about Quantum Computing and its application in optimization problems speedup. Does anybody have a similar experience in that, or more generally any other ways of reducing the solution time?

答:
if your model is a LP then I suggest CPLEX Performance Tuning for Linear Programs

You could also try data check 2 to see whether you have some numerical issues in your model.

If still no improvement you could try to improve your model.

NB:

If it s a MIP then you could read this


答:
Here is a simple solution :</p>

```<code>import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.assertThat;

public class Test {

    @org.junit.jupiter.api.Test
    public void shouldParseAttributes() throws Exception {
        String attributeUpdate = "status:MYSTATUS|data1:value1";

        Map<String, String> attributes = Stream.of(attributeUpdate.split("\\|"))
            .map(attribute -> attribute.split(":"))
            .collect(Collectors.toMap(
                    attribute -> attribute[0],
                    attribute -> attribute[1]));

        assertThat(attributes).containsEntry("status", "MYSTATUS");
        assertThat(attributes).containsEntry("data1", "value1");
    }
}
</code>```

Title: How will you convert method to single line in java8

Body:
Here is a simple solution :

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.assertThat;

public class Test {

    @org.junit.jupiter.api.Test
    public void shouldParseAttributes() throws Exception {
        String attributeUpdate = "status:MYSTATUS|data1:value1";

        Map<String, String> attributes = Stream.of(attributeUpdate.split("\\|"))
            .map(attribute -> attribute.split(":"))
            .collect(Collectors.toMap(
                    attribute -> attribute[0],
                    attribute -> attribute[1]));

        assertThat(attributes).containsEntry("status", "MYSTATUS");
        assertThat(attributes).containsEntry("data1", "value1");
    }
}


问:
Pause and resume caret training in R
Let's assume I will do a caret training in R, but I want to split this training in two run sessions.

```<code>library(mlbench)
data(Sonar)
library(caret)
set.seed(998)
inTraining <- createDataPartition(Sonar$Class, p = .75, list = FALSE)
training <- Sonar[ inTraining,]
testing  <- Sonar[-inTraining,]

# First run session
nn.partial <- train(Class ~ ., data = training,
                method = "nnet",
                 max.turns.of.iteration=5) # Non-existent parameter. But represents my goal
</code>```

Let´s assume that instead the nn full object I have only a partial object that has training information until the turn 5 (i.e. nn.partial). Thus, in future I could run the below code to finish the training job:

```<code>library(mlbench)
data(Sonar)
library(caret)
set.seed(998)
inTraining <- createDataPartition(Sonar$Class, p = .75, list = FALSE)
training <- Sonar[ inTraining,]
testing  <- Sonar[-inTraining,]

nn <- train(Class ~ ., data = training,
                 method = "nnet",
                 previous.training=nn.partial) # Non-existent parameter. But represents my goal
</code>```

I am aware that the both max.turns.of.iteration and previous.training do not exist in the train function. I am just trying my best to represent in code what would be the ideal world to accomplish my goal if it was already implemented in train function. However, as the parameters are not there, is there a way to achieve this goal (i.e. do the caret training in more than one run) by tricking the function in some way?

I have tried to play with the trainControl function without success.

```<code>t.control <- trainControl(repeats=5)
nn <- train(Class ~ ., data = training,
                 method = "nnet",
trControl = t.control)
</code>```

By doing that, the number of iteration turns is still much higher than 5, as I would like to obtain in my example.

答:
I am almost certain that this is very complicated to implement in carets current infrastructure. However I will show you how to achieve this sort of thing out of the box with mlr3.

required packages for the example

```<code>library(mlr3)
library(mlr3tuning)
library(paradox)
</code>```

get an example task and define a learner to be tuned:

```<code>task_sonar <- tsk('sonar')
learner <- lrn('classif.rpart', predict_type = 'prob')
</code>```

define the hyper parameters to be tuned:

```<code>ps <- ParamSet$new(list(
  ParamDbl$new("cp", lower = 0.001, upper = 0.1),
  ParamInt$new("minsplit", lower = 1, upper = 10)
))
</code>```

define the tuner and resampling strategy

```<code>tuner <- tnr("random_search")
cv3 <- rsmp("cv", folds = 3)
</code>```

define the tuning instance

```<code>instance <- TuningInstance$new(
  task = task_sonar,
  learner = learner,
  resampling = cv3,
  measures = msr("classif.auc"),
  param_set = ps,
  terminator = term("evals", n_evals = 100) #one can combine multiple terminators such as clock time, number of evaluations, early stopping (stagnation), performance reached - ?Terminator
)
</code>```

tune:

```<code>tuner$tune(instance)
</code>```

now press stop after a second to stop the task in Rstudio

```<code>instance$archive()

    nr batch_nr  resample_result task_id    learner_id resampling_id iters params tune_x warnings errors classif.auc
 1:  1        1 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7105586
 2:  2        2 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7372720
 3:  3        3 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7335368
 4:  4        4 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7335368
 5:  5        5 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7276246
 6:  6        6 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7111217
 7:  7        7 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.6915560
 8:  8        8 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7452875
 9:  9        9 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7372720
10: 10       10 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7172328
</code>```

in my case it finished 10 iterations of random search.
You can now for instance call

```<code>save.image()
</code>```

close RStudio and reopen the same project

or  use  saveRDS/readRDS on the objects you wish to keep

```<code>saveRDS(instance, "i.rds")
instance <- readRDS("i.rds")
</code>```

after loading the required packages resume training with

```<code>tuner$tune(instance)
</code>```

stop it again after few seconds:

in my case it finished an additional 12 iterations:

```<code>task_sonar <- tsk('sonar')
learner <- lrn('classif.rpart', predict_type = 'prob')
</code>```0

Run it again without pressing stop

```<code>task_sonar <- tsk('sonar')
learner <- lrn('classif.rpart', predict_type = 'prob')
</code>```1

and it will finish the 100 evals

Limitation: The above example splits the tuning (evaluation of hyper-parameters) to multiple sessions). However it does not split one training instance into multiple sessions - very few packages support this kind of thing in R - keras/tensorflow are the only one I know of.

However regardless of the length of one training instance for an algorithm, the tuning (evaluation of hyper parameters) of such an algorithm takes much more time so it is more advantageous to be able to pause/resume the tuning as in the above example.

If you find this interesting here are some resources to learn mlr3

https://mlr3book.mlr-org.com/

https://mlr3gallery.mlr-org.com/

Take a look also at mlr3pipelines - https://mlr3pipelines.mlr-org.com/articles/introduction.html

Title: Pause and resume caret training in R

Body:
Let's assume I will do a caret training in R, but I want to split this training in two run sessions.

library(mlbench)
data(Sonar)
library(caret)
set.seed(998)
inTraining <- createDataPartition(Sonar$Class, p = .75, list = FALSE)
training <- Sonar[ inTraining,]
testing  <- Sonar[-inTraining,]

# First run session
nn.partial <- train(Class ~ ., data = training,
                method = "nnet",
                 max.turns.of.iteration=5) # Non-existent parameter. But represents my goal

Let´s assume that instead the nn full object I have only a partial object that has training information until the turn 5 (i.e. nn.partial). Thus, in future I could run the below code to finish the training job:

library(mlbench)
data(Sonar)
library(caret)
set.seed(998)
inTraining <- createDataPartition(Sonar$Class, p = .75, list = FALSE)
training <- Sonar[ inTraining,]
testing  <- Sonar[-inTraining,]

nn <- train(Class ~ ., data = training,
                 method = "nnet",
                 previous.training=nn.partial) # Non-existent parameter. But represents my goal

I am aware that the both max.turns.of.iteration and previous.training do not exist in the train function. I am just trying my best to represent in code what would be the ideal world to accomplish my goal if it was already implemented in train function. However, as the parameters are not there, is there a way to achieve this goal (i.e. do the caret training in more than one run) by tricking the function in some way?

I have tried to play with the trainControl function without success.

t.control <- trainControl(repeats=5)
nn <- train(Class ~ ., data = training,
                 method = "nnet",
trControl = t.control)

By doing that, the number of iteration turns is still much higher than 5, as I would like to obtain in my example.

Body:
I am almost certain that this is very complicated to implement in carets current infrastructure. However I will show you how to achieve this sort of thing out of the box with mlr3.

required packages for the example

library(mlr3)
library(mlr3tuning)
library(paradox)

get an example task and define a learner to be tuned:

task_sonar <- tsk('sonar')
learner <- lrn('classif.rpart', predict_type = 'prob')

define the hyper parameters to be tuned:

ps <- ParamSet$new(list(
  ParamDbl$new("cp", lower = 0.001, upper = 0.1),
  ParamInt$new("minsplit", lower = 1, upper = 10)
))

define the tuner and resampling strategy

tuner <- tnr("random_search")
cv3 <- rsmp("cv", folds = 3)

define the tuning instance

instance <- TuningInstance$new(
  task = task_sonar,
  learner = learner,
  resampling = cv3,
  measures = msr("classif.auc"),
  param_set = ps,
  terminator = term("evals", n_evals = 100) #one can combine multiple terminators such as clock time, number of evaluations, early stopping (stagnation), performance reached - ?Terminator
)

tune:

tuner$tune(instance)

now press stop after a second to stop the task in Rstudio

instance$archive()

    nr batch_nr  resample_result task_id    learner_id resampling_id iters params tune_x warnings errors classif.auc
 1:  1        1 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7105586
 2:  2        2 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7372720
 3:  3        3 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7335368
 4:  4        4 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7335368
 5:  5        5 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7276246
 6:  6        6 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7111217
 7:  7        7 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.6915560
 8:  8        8 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7452875
 9:  9        9 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7372720
10: 10       10 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7172328

in my case it finished 10 iterations of random search.
You can now for instance call

save.image()

close RStudio and reopen the same project

or  use  saveRDS/readRDS on the objects you wish to keep

saveRDS(instance, "i.rds")
instance <- readRDS("i.rds")

after loading the required packages resume training with

tuner$tune(instance)

stop it again after few seconds:

in my case it finished an additional 12 iterations:

instance$archive()

    nr batch_nr  resample_result task_id    learner_id resampling_id iters params tune_x warnings errors classif.auc
 1:  1        1 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7105586
 2:  2        2 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7372720
 3:  3        3 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7335368
 4:  4        4 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7335368
 5:  5        5 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7276246
 6:  6        6 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7111217
 7:  7        7 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.6915560
 8:  8        8 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7452875
 9:  9        9 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7372720
10: 10       10 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7172328
11: 11       11 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7325289
12: 12       12 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7105586
13: 13       13 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7215133
14: 14       14 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.6915560
15: 15       15 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.6915560
16: 16       16 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7335368
17: 17       17 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7276246
18: 18       18 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7111217
19: 19       19 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7172328
20: 20       20 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7276246
21: 21       21 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7105586
22: 22       22 <ResampleResult>   sonar classif.rpart            cv     3 <list> <list>        0      0   0.7276246

Run it again without pressing stop

tuner$tune(instance)

and it will finish the 100 evals

Limitation: The above example splits the tuning (evaluation of hyper-parameters) to multiple sessions). However it does not split one training instance into multiple sessions - very few packages support this kind of thing in R - keras/tensorflow are the only one I know of.

However regardless of the length of one training instance for an algorithm, the tuning (evaluation of hyper parameters) of such an algorithm takes much more time so it is more advantageous to be able to pause/resume the tuning as in the above example.

If you find this interesting here are some resources to learn mlr3

https://mlr3book.mlr-org.com/

https://mlr3gallery.mlr-org.com/

Take a look also at mlr3pipelines - https://mlr3pipelines.mlr-org.com/articles/introduction.html


问:
Adapting Shake Code from 'Beginning Iphone 4 Development' Causing Crash
The code below is a near replica of the Shake and Bake example from Beginning Iphone 4 Development.  It is lacking a BOOL if statement before CMAcceleration acceleration = accelerometerData.acceleration; because I want the person to shake and refresh the results as many times as they want. I  have a button that executes the same code flawlessly. When I run the code and shake the iphone, it crashes. What am I missing that will make this work?  Can you not run the same code with a button as with the shake method?

Example.h

```<code>#import <CoreMotion/CoreMotion.h>
#define kAccelerationThreshold 1.7
#define kUpdateInterval (1.0f/10.0f)

@interface exampleViewController : UIViewController  {
CMMotionManager *motionManager;
}
@property (retain,nonatomic) CMMotionManager *motionManager;
@end
</code>```

Example.m

```<code>@synthesize motionManager;

-(void)viewDidLoad {

self.motionManager = [[[CMMotionManager alloc] init] autorelease];
motionManager.accelerometerUpdateInterval = kUpdateInterval;
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[motionManager startAccelerometerUpdatesToQueue:queue
                                    withHandler:
 ^(CMAccelerometerData *accelerometerData, NSError *error){
     if (error) {
         [motionManager stopAccelerometerUpdates];
     } else {
         CMAcceleration acceleration = accelerometerData.acceleration;
         if (acceleration.x > kAccelerationThreshold
            || acceleration.y > kAccelerationThreshold
            || acceleration.z > kAccelerationThreshold){

// There is a bunch of other stuff here, but it all works using a button called shake....
            example4.hidden = NO;
            select1.text = first;
            display.text = [[NSString alloc] initWithFormat: @"%@", first];

         }
     }
 }];
}

- (void)dealloc
{
[super dealloc];
[motionManager release];
}

- (void)viewDidUnload {
[super viewDidUnload];
self.motionManager = nil;
}

@end
</code>```

答:
The part that looks fishy to me is NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];.

Nowhere are you hanging on to the queue for the duration of the time that motionManager is dispatching to it. I checked the documentation for startAccelerometerUpdatesToQueue but it doesn't say that the receiver retains the queue, so that's probably not something you can safely assume. My suggestion is to not autorelease the queue. Instead, release it in viewDidUnload after calling stopAccelerometerUpdates on motionManager.

Body:
The code below is a near replica of the Shake and Bake example from Beginning Iphone 4 Development.  It is lacking a BOOL if statement before CMAcceleration acceleration = accelerometerData.acceleration; because I want the person to shake and refresh the results as many times as they want. I  have a button that executes the same code flawlessly. When I run the code and shake the iphone, it crashes. What am I missing that will make this work?  Can you not run the same code with a button as with the shake method?

Example.h

#import <CoreMotion/CoreMotion.h>
#define kAccelerationThreshold 1.7
#define kUpdateInterval (1.0f/10.0f)

@interface exampleViewController : UIViewController  {
CMMotionManager *motionManager;
}
@property (retain,nonatomic) CMMotionManager *motionManager;
@end

Example.m

@synthesize motionManager;

-(void)viewDidLoad {

self.motionManager = [[[CMMotionManager alloc] init] autorelease];
motionManager.accelerometerUpdateInterval = kUpdateInterval;
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[motionManager startAccelerometerUpdatesToQueue:queue
                                    withHandler:
 ^(CMAccelerometerData *accelerometerData, NSError *error){
     if (error) {
         [motionManager stopAccelerometerUpdates];
     } else {
         CMAcceleration acceleration = accelerometerData.acceleration;
         if (acceleration.x > kAccelerationThreshold
            || acceleration.y > kAccelerationThreshold
            || acceleration.z > kAccelerationThreshold){

// There is a bunch of other stuff here, but it all works using a button called shake....
            example4.hidden = NO;
            select1.text = first;
            display.text = [[NSString alloc] initWithFormat: @"%@", first];

         }
     }
 }];
}

- (void)dealloc
{
[super dealloc];
[motionManager release];
}

- (void)viewDidUnload {
[super viewDidUnload];
self.motionManager = nil;
}

@end


问:
WebRTC + Android + Remote Video Not showing
Please review following code and let me know what I need to change for showing remote video. Audio is playing fine. Working Latest library of Webrtc.In onAddStream method I have get Videotrack size of 1 but is not render in remoteVideoTrack addSink method.</p>

```<code> private PeerConnection createPeerConnection(PeerConnectionFactory peerConnectionFactory, boolean isLocal) {
    //
    PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(getServerList());
    //
    PeerConnection.Observer pcObserver = new CustomPeerConnectionObserver("localPeerCreation") {
        @Override
        public void onIceCandidate(IceCandidate iceCandidate) {
            super.onIceCandidate(iceCandidate);
            //SignallingClient.getInstance().sendICECandidate(iceCandidate);
            if (iceCandidate.serverUrl.length() > 1)
                SignallingClient.getInstance().sendICECandidate(iceCandidate);
        }

        @Override
        public void onAddStream(MediaStream mediaStream) {
            super.onAddStream(mediaStream);
            Log.e("mytagVFrame", "Video Frame is OUt == " + mediaStream.videoTracks.size());
            VideoTrack remoteVideoTrack = mediaStream.videoTracks.get(0);
            remoteVideoTrack.setEnabled(true);
            ProxyVideoSink videoSink = new ProxyVideoSink();
            videoSink.setTarget(mRemoteSurfaceViewRenderer);
            remoteVideoTrack.addSink(videoSink);
        }
    };
    return peerConnectionFactory.createPeerConnection(rtcConfig, pcObserver);
    //
}
</code>```

答: I had the same problem. I discovered I was calling EglBase.create(); in two different places

Body:
Please review following code and let me know what I need to change for showing remote video. Audio is playing fine. Working Latest library of Webrtc.In onAddStream method I have get Videotrack size of 1 but is not render in remoteVideoTrack addSink method.

 private PeerConnection createPeerConnection(PeerConnectionFactory peerConnectionFactory, boolean isLocal) {
    //
    PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(getServerList());
    //
    PeerConnection.Observer pcObserver = new CustomPeerConnectionObserver("localPeerCreation") {
        @Override
        public void onIceCandidate(IceCandidate iceCandidate) {
            super.onIceCandidate(iceCandidate);
            //SignallingClient.getInstance().sendICECandidate(iceCandidate);
            if (iceCandidate.serverUrl.length() > 1)
                SignallingClient.getInstance().sendICECandidate(iceCandidate);
        }

        @Override
        public void onAddStream(MediaStream mediaStream) {
            super.onAddStream(mediaStream);
            Log.e("mytagVFrame", "Video Frame is OUt == " + mediaStream.videoTracks.size());
            VideoTrack remoteVideoTrack = mediaStream.videoTracks.get(0);
            remoteVideoTrack.setEnabled(true);
            ProxyVideoSink videoSink = new ProxyVideoSink();
            videoSink.setTarget(mRemoteSurfaceViewRenderer);
            remoteVideoTrack.addSink(videoSink);
        }
    };
    return peerConnectionFactory.createPeerConnection(rtcConfig, pcObserver);
    //
}