问:
Flutter Webrtc Build error on M1 android and ios
I am trying to build a webrtc flutter app on my m1 macbook air. But I got different issues both on android and ios. Latest one ^0.8.2 has error on both then  ^0.7.0+hotfix.1 demo demo only works for android.

On iOS part 'Libyuv''s deployment target is set to 8.0 but min deployment target is 9.0 occurs. I set the deployment target above 10 then it still happens.

```<code>/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCMediaStream.m:3:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCFrameCapturer.m:8:
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCFrameCapturer.h:6:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCDataChannel.m:2:
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCDataChannel.h:1:
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete
    /Users/alperenbaskaya/AndroidStudioProjects/flutter-webrtc-demo/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 4.3, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Libyuv' from project 'Pods')
Could not build the application for the simulator.
Error launching application on iPhone 8 Plus.
</code>```

After a workaround I updated libyuv deployment target but now I got following ios Error;

```<code>        objc[66512]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libauthinstall.dylib (0x20d426c10) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x113d3c2b8). One of the two will be used. Which one is undefined.
    objc[66512]: Class AMSupportURLSession is implemented in both /usr/lib/libauthinstall.dylib (0x20d426c60) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x113d3c308). One of the two will be used. Which one is undefined.
    ** BUILD FAILED **
Xcode's output:
↳
    warning: [CP] Unable to find matching .xcframework slice in 'ios-arm64_x86_64-simulator ios-arm64_armv7' for the current build architectures (arm64 x86_64 i386).
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.8.2/ios/Classes/FlutterRTCPeerConnection.m:2:
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.8.2/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete
Could not build the application for the simulator.
Error launching application on iPhone 8 Plus.
</code>```

On android side I got following;

```<code>Execution failed for task ':flutter_webrtc:compileDebugJavaWithJavac'.
</code>```

答:
For version ^0.8.2 following solutions work for me.

iOS

in ios/Podfile add following to end of file.

```<code>    post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |build_configuration|
      build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386'
    end
  end
end
</code>```

Then clean your project and follow these steps as santoshakil mentioned santoshakilsanswer; (Those steps work for me if not follow all steps mentioned in link)

```<code>flutter clean && flutter pub get
cd ios
arch -x86_64 pod update
arch -x86_64 pod install
then at the top of your Pod file, paste this line platform :ios, '10.0'
right click on ios folder and open in xcode and then set all deployment target to 10
</code>```

Android
Your android/app/build.gradle look like below as webrtcflutterdemo

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.cloudwebrtc.flutterwebrtcdemo"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
            useProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/proguard/androidx-annotations.pro'
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

android/app/AndroidManifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cloudwebrtc.flutterwebrtcdemo">

    <!-- The INTERNET permission is required for development. Specifically,
         flutter needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:label="flutter_webrtc_demo"
        android:icon="@mipmap/ic_launcher">
        <meta-data
</code>```

EDIT
For Android side, i can not build for compilesdk and targetsdk 31. Temporary solution is downgrading compilesdk to 30. It is about jdk version on your mac device.

Body:
I am trying to build a webrtc flutter app on my m1 macbook air. But I got different issues both on android and ios. Latest one ^0.8.2 has error on both then  ^0.7.0+hotfix.1 demo demo only works for android.

On iOS part 'Libyuv''s deployment target is set to 8.0 but min deployment target is 9.0 occurs. I set the deployment target above 10 then it still happens.

/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCMediaStream.m:3:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCFrameCapturer.m:8:
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCFrameCapturer.h:6:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCDataChannel.m:2:
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCDataChannel.h:1:
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete
    /Users/alperenbaskaya/AndroidStudioProjects/flutter-webrtc-demo/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 4.3, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Libyuv' from project 'Pods')
Could not build the application for the simulator.
Error launching application on iPhone 8 Plus.

After a workaround I updated libyuv deployment target but now I got following ios Error;

        objc[66512]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libauthinstall.dylib (0x20d426c10) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x113d3c2b8). One of the two will be used. Which one is undefined.
    objc[66512]: Class AMSupportURLSession is implemented in both /usr/lib/libauthinstall.dylib (0x20d426c60) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x113d3c308). One of the two will be used. Which one is undefined.
    ** BUILD FAILED **
Xcode's output:
↳
    warning: [CP] Unable to find matching .xcframework slice in 'ios-arm64_x86_64-simulator ios-arm64_armv7' for the current build architectures (arm64 x86_64 i386).
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.8.2/ios/Classes/FlutterRTCPeerConnection.m:2:
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.8.2/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete
Could not build the application for the simulator.
Error launching application on iPhone 8 Plus.

On android side I got following;

Execution failed for task ':flutter_webrtc:compileDebugJavaWithJavac'.

Body:
For version ^0.8.2 following solutions work for me.

iOS

in ios/Podfile add following to end of file.

    post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |build_configuration|
      build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386'
    end
  end
end

Then clean your project and follow these steps as santoshakil mentioned santoshakilsanswer; (Those steps work for me if not follow all steps mentioned in link)

flutter clean && flutter pub get
cd ios
arch -x86_64 pod update
arch -x86_64 pod install
then at the top of your Pod file, paste this line platform :ios, '10.0'
right click on ios folder and open in xcode and then set all deployment target to 10

Android
Your android/app/build.gradle look like below as webrtcflutterdemo

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.cloudwebrtc.flutterwebrtcdemo"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
            useProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/proguard/androidx-annotations.pro'
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

android/app/AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cloudwebrtc.flutterwebrtcdemo">

    <!-- The INTERNET permission is required for development. Specifically,
         flutter needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:label="flutter_webrtc_demo"
        android:icon="@mipmap/ic_launcher">
        <meta-data

EDIT
For Android side, i can not build for compilesdk and targetsdk 31. Temporary solution is downgrading compilesdk to 30. It is about jdk version on your mac device.


来源: stackexchange

问:
Linq ToList() and Count() performance problem
I have 200k rows in my table and I need to filter the table and then show in datatable. When I try to do that, my sql run fast. But when I want to get row count or run the ToList(), it takes long time. Also when I try to convert it to list it has 15 rows after filter, it has not huge data.</p>
```<code>public static List<Books> GetBooks()
{
    List<Books> bookList = new List<Books>();

    var v = from a in ctx.Books select a);
    int allBooksCount = v.Count(); // I need all books count before filter. but it is so slow is my first problem
    if (isFilter)
        {
           v = v.Where(a => a.startdate <= DateTime.Now && a.enddate>= DateTime.Now);
        }
  .
  .
    bookList = v.ToList(); // also toList is so slow is my second problem
}
</code>```

答:
First, to get help you need to provide quantitative values for "fast" vs. "too long". Loading entities from EF will take longer than running a raw SQL statement in a client tool like TOAD etc. Are you seeing differences of 15ms vs. 15 seconds, or 15ms vs. 150ms?

To help identify and eliminate possible culprits:

Eliminate the possibility of a long-running DbContext instance tracking too many entities bogging down performance. The longer a DbContext is used and the more entities it tracks, the slower it gets. Temporarily change the code to:

```<code>List<Books> bookList = new List<Books>();

using (var context = new YourDbContext())
{
    var v = from a in context.Books select a);
    int allBooksCount = v.Count(); // I need all books count before filter. but it is so slow is my first problem
    if (isFilter)
    {
       v = v.Where(a => a.startdate <= DateTime.Now && a.enddate>= DateTime.Now);
    }
    .
    .
    bookList = v.ToList();
}
</code>```

Using a fresh DbContext ensures queries are not sifting through in-memory entities after running a query to find tracked instances to return. This also ensures we are running against IQueryable off the Books DbSet within the context. We can only guess what "ctx" in your code actually represents.

Next: Look at a profiler for MySQL, or have your database log out SQL statements to capture exactly what EF is requesting. Check that the Count and ToList each trigger just one query against the database, and then run these exact statements against the database. If there are more than these two queries being run then something odd is happening behind the scenes that you need to investigate, such as that your example doesn't really represent what your real code is doing. You could be tripping client side evaluation (if using EF Core 2) or lazy loading. The next thing I would look at is if possible to look at the execution plan for these queries for hints like missing indexes or such. (my DB experience is primarily SQL Server so I cannot provide advice on tools to use for MySQL)

ContentLicense: CC BY-SA 4.0

Body:
I have 200k rows in my table and I need to filter the table and then show in datatable. When I try to do that, my sql run fast. But when I want to get row count or run the ToList(), it takes long time. Also when I try to convert it to list it has 15 rows after filter, it has not huge data.

public static List<Books> GetBooks()
{
    List<Books> bookList = new List<Books>();

    var v = from a in ctx.Books select a);
    int allBooksCount = v.Count(); // I need all books count before filter. but it is so slow is my first problem
    if (isFilter)
        {
           v = v.Where(a => a.startdate <= DateTime.Now && a.enddate>= DateTime.Now);
        }
  .
  .
    bookList = v.ToList(); // also toList is so slow is my second problem
}

Body:
First, to get help you need to provide quantitative values for "fast" vs. "too long". Loading entities from EF will take longer than running a raw SQL statement in a client tool like TOAD etc. Are you seeing differences of 15ms vs. 15 seconds, or 15ms vs. 150ms?

To help identify and eliminate possible culprits:

Eliminate the possibility of a long-running DbContext instance tracking too many entities bogging down performance. The longer a DbContext is used and the more entities it tracks, the slower it gets. Temporarily change the code to:

List<Books> bookList = new List<Books>();

using (var context = new YourDbContext())
{
    var v = from a in context.Books select a);
    int allBooksCount = v.Count(); // I need all books count before filter. but it is so slow is my first problem
    if (isFilter)
    {
       v = v.Where(a => a.startdate <= DateTime.Now && a.enddate>= DateTime.Now);
    }
    .
    .
    bookList = v.ToList();
}

Using a fresh DbContext ensures queries are not sifting through in-memory entities after running a query to find tracked instances to return. This also ensures we are running against IQueryable off the Books DbSet within the context. We can only guess what "ctx" in your code actually represents.

Next: Look at a profiler for MySQL, or have your database log out SQL statements to capture exactly what EF is requesting. Check that the Count and ToList each trigger just one query against the database, and then run these exact statements against the database. If there are more than these two queries being run then something odd is happening behind the scenes that you need to investigate, such as that your example doesn't really represent what your real code is doing. You could be tripping client side evaluation (if using EF Core 2) or lazy loading. The next thing I would look at is if possible to look at the execution plan for these queries for hints like missing indexes or such. (my DB experience is primarily SQL Server so I cannot provide advice on tools to use for MySQL)


问:
HID USB ReadFile() missing packets during large downloads
I implemented a HID USB PC application which seems to work fine for connecting, readin and writing to an external USB device.
The problem is when attemping to read large data files, some packets get lost.

Here is the code im using:

```<code>DWORD   result;
uint8_t u8_dataBuffer[size] = { 0 };
DWORD   bytesRead;
ReadFile(Handle, u8_dataBuffer,
    size + 1,
    &bytesRead,
    (LPOVERLAPPED)&m_HidOverlapped))

result = WaitForSingleObject(Handle, 6000);
switch (result) {
    case WAIT_OBJECT_0: {
        break;
    }
    case WAIT_TIMEOUT: {
        result = CancelIo(Handle);
        CloseHandle(Handle);
        deviceFound = false;
        break;
    }
    default: {
        break;
    }
}
</code>```

答:
HID reports are saved in a ring buffer. So if you don't fast enough to read all pending input reports - they could  be lost.
Size of this buffer could be changed via HidD_SetNumInputBuffers call or IOCTL_SET_NUM_DEVICE_INPUT_BUFFERS IOCTL on HID device handle.

By default, the HID class driver maintains an input report ring buffer that holds 32 reports.

See Troubleshooting HID Reports#Dropped HID Reports for additional info.

Body:
I implemented a HID USB PC application which seems to work fine for connecting, readin and writing to an external USB device.
The problem is when attemping to read large data files, some packets get lost.

Here is the code im using:

DWORD   result;
uint8_t u8_dataBuffer[size] = { 0 };
DWORD   bytesRead;
ReadFile(Handle, u8_dataBuffer,
    size + 1,
    &bytesRead,
    (LPOVERLAPPED)&m_HidOverlapped))

result = WaitForSingleObject(Handle, 6000);
switch (result) {
    case WAIT_OBJECT_0: {
        break;
    }
    case WAIT_TIMEOUT: {
        result = CancelIo(Handle);
        CloseHandle(Handle);
        deviceFound = false;
        break;
    }
    default: {
        break;
    }
}


问:
How to Invert column values in pandas - pythonic way?
I have a dataframe like as shown below

```<code>cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,1,1,0,0]})
</code>```

My objective is to

a) replace 0s as 1s AND 1s as 0s in Label column

I was trying something like the below

```<code>cdf.assign(invert_label=cdf.Label.loc[::-1].reset_index(drop=True)) #not work
cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0')
</code>```

'
but this doesn't work. It reverses the order

I expect my output to be like as shown below

```<code>    Id  Label
0   1   0
1   2   0
2   3   0
3   4   1
4   5   1
</code>```

答:
Another way, and I am adding this as a separate answer as this is probably not "pythonic" enough (in the sense that it is not very explicit) is to use the bitwise xor

```<code>cdf['Label'] ^ 1
</code>```

Body:
I have a dataframe like as shown below

cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,1,1,0,0]})

My objective is to

a) replace 0s as 1s AND 1s as 0s in Label column

I was trying something like the below

cdf.assign(invert_label=cdf.Label.loc[::-1].reset_index(drop=True)) #not work
cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0')

'
but this doesn't work. It reverses the order

I expect my output to be like as shown below

    Id  Label
0   1   0
1   2   0
2   3   0
3   4   1
4   5   1

Body:
Another way, and I am adding this as a separate answer as this is probably not "pythonic" enough (in the sense that it is not very explicit) is to use the bitwise xor

cdf['Label'] ^ 1


问:
How to insert/remove hyphen to/from a plain string in c#?
I have a string like this;

```<code>   string text =  "6A7FEBFCCC51268FBFF";
</code>```

And I have one method for which I want to insert the logic for appending the hyphen after 4 characters to 'text' variable. So, the output should be like this;

```<code>6A7F-EBFC-CC51-268F-BFF
</code>```

Appending hyphen to above 'text' variable logic should be inside this method;

```<code>public void GetResultsWithHyphen
{
     // append hyphen after 4 characters logic goes here
}
</code>```

And I want also remove the hyphen from a given string such as 6A7F-EBFC-CC51-268F-BFF. So, removing hyphen from a string logic should be inside this method;

```<code>public void GetResultsWithOutHyphen
{
     // Removing hyphen after 4 characters logic goes here
}
</code>```

How can I do this in C# (for desktop app)?
What is the best way to do this?
Appreciate everyone's answer in advance.

答:
Callee

```<code>public static void Main()
{
    var text = new Text("THISisJUSTanEXAMPLEtext");
    var convertText = text.Convert();
    Console.WriteLine(convertText);
}
</code>```

Caller

```<code>public class Text
{
    private string _text;
    private int _jumpNo = 4;

    public Text(string text)
    {
        _text = text;
    }

    public Text(string text, int jumpNo)
    {
        _text = text;
        _jumpNo = jumpNo < 1 ? _jumpNo : jumpNo;
    }

    public string Convert()
    {
        if (string.IsNullOrEmpty(_text))
        {
            return string.Empty;
        }

        if (_text.Length < _jumpNo)
        {
            return _text;
        }

        var convertText = _text.Substring(0, _jumpNo);
        int start = _jumpNo;
        while (start < _text.Length)
        {
            convertText += "-" + _text.Substring(start, Math.Min(_jumpNo, _text.Length - start));
            start += _jumpNo;
        }

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

ContentLicense: CC BY-SA 3.0

Body:
I have a string like this;

   string text =  "6A7FEBFCCC51268FBFF";

And I have one method for which I want to insert the logic for appending the hyphen after 4 characters to 'text' variable. So, the output should be like this;

6A7F-EBFC-CC51-268F-BFF

Appending hyphen to above 'text' variable logic should be inside this method;

public void GetResultsWithHyphen
{
     // append hyphen after 4 characters logic goes here
}

And I want also remove the hyphen from a given string such as 6A7F-EBFC-CC51-268F-BFF. So, removing hyphen from a string logic should be inside this method;

public void GetResultsWithOutHyphen
{
     // Removing hyphen after 4 characters logic goes here
}

How can I do this in C# (for desktop app)?
What is the best way to do this?
Appreciate everyone's answer in advance.

Body:
Callee

public static void Main()
{
    var text = new Text("THISisJUSTanEXAMPLEtext");
    var convertText = text.Convert();
    Console.WriteLine(convertText);
}

Caller

public class Text
{
    private string _text;
    private int _jumpNo = 4;

    public Text(string text)
    {
        _text = text;
    }

    public Text(string text, int jumpNo)
    {
        _text = text;
        _jumpNo = jumpNo < 1 ? _jumpNo : jumpNo;
    }

    public string Convert()
    {
        if (string.IsNullOrEmpty(_text))
        {
            return string.Empty;
        }

        if (_text.Length < _jumpNo)
        {
            return _text;
        }

        var convertText = _text.Substring(0, _jumpNo);
        int start = _jumpNo;
        while (start < _text.Length)
        {
            convertText += "-" + _text.Substring(start, Math.Min(_jumpNo, _text.Length - start));
            start += _jumpNo;
        }

        return convertText;
    }
}


问:
Added Springfox Swagger-UI and it's not working, what am I missing?
Following the instructions here:

http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api

I added these dependencies to my project:

```<code>compile "io.springfox:springfox-swagger2:2.7.0"
compile "io.springfox:springfox-swagger-ui:2.7.0"
</code>```

and configured SpringFox Swagger like this:

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}
</code>```

but the Swagger UI seems not to get enabled. I tried:

http://localhost:8080/swagger-ui.html

http://localhost:8080/api/swagger-ui.html

http://localhost:8080/v2/api-docs/swagger-ui.html

and all I get is:

```<code>Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Sep 11 09:43:46 BST 2017
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
</code>```

and on the logs I see:

```<code>2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound             : Request method 'GET' not supported
2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
</code>```

http://localhost:8080/swagger-resources returns:

```<code>[{"name": "default",
  "location": "/v2/api-docs",
  "swaggerVersion": "2.0"}]
</code>```

What am I missing?

答:
I had similar problem recently

http://localhost:8080/swagger-ui/ - didn't work

http://localhost:8080/swagger-ui/index.html - worked fine

...at the end the issue was caused by some mess in my pom.xml

```<code><dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
</code>```

I deleted the first two dependencies, so only springfox-boot-starter left
and after couple of maven cleanups and restarting the app the first path started to work fine as well
http://localhost:8080/swagger-ui/

Body:
Following the instructions here:

http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api

I added these dependencies to my project:

compile "io.springfox:springfox-swagger2:2.7.0"
compile "io.springfox:springfox-swagger-ui:2.7.0"

and configured SpringFox Swagger like this:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

but the Swagger UI seems not to get enabled. I tried:

http://localhost:8080/swagger-ui.html

http://localhost:8080/api/swagger-ui.html

http://localhost:8080/v2/api-docs/swagger-ui.html

and all I get is:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Sep 11 09:43:46 BST 2017
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported

and on the logs I see:

2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound             : Request method 'GET' not supported
2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

http://localhost:8080/swagger-resources returns:

[{"name": "default",
  "location": "/v2/api-docs",
  "swaggerVersion": "2.0"}]

What am I missing?

Body:
I had similar problem recently

http://localhost:8080/swagger-ui/ - didn't work

http://localhost:8080/swagger-ui/index.html - worked fine

...at the end the issue was caused by some mess in my pom.xml

<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

I deleted the first two dependencies, so only springfox-boot-starter left
and after couple of maven cleanups and restarting the app the first path started to work fine as well
http://localhost:8080/swagger-ui/


问:
Room Database operations inside flow function
Here is my login function that return a flow

```<code>override  fun loginMeIn(loginDto: LoginDto): Flow<Resource<User?>> = flow {
    emit(Resource.Loading())

    try {
        Log.e(TAG, "loginMeIn : try");
        val result = api.loginMeIN(loginDto)
          dao.deleteAll()
          dao.upsertUser(result.toUserEntity())
         val user = dao.getUsers().first()
        emit(Resource.Success<User?>(user.toUser()))
        Log.e(TAG, "loginMeIn : job finished");

    }catch (e:HttpException ){
        emit(Resource.Error<User?>(message = e.response().toString(),data = null))
        Log.e(TAG, "loginMeIn :"+ e);

    }catch (e:IOException){

        emit(Resource.Error<User?>(message = "Couldn't reach server, check Your internet connection",data = null))
        Log.e(TAG, "Couldn't reach server");
    }

}
</code>```

with this implementation the app crash with error : Cannot access database on the main thread
and if i use coroutine scope for IO dispatchers i cant emit the Success result Please Help!

答:
You can switch coroutine context to Dispatchers.IO when making DB requests:

```<code>val user = withContext(Dispatchers.IO) {
    dao.deleteAll()
    dao.upsertUser(result.toUserEntity())
    dao.getUsers().first()
}
emit(Resource.Success<User?>(user.toUser()))
</code>```

If you use Room DB you can try to mark functions as suspend, for example:

```<code>// in Dao class
@Insert
suspend fun insertUser(user: User)
</code>```

If all function are marked as suspend then you won'y need to switch coroutine context to Dispatchers.IO in flow builder.

Body:
Here is my login function that return a flow

override  fun loginMeIn(loginDto: LoginDto): Flow<Resource<User?>> = flow {
    emit(Resource.Loading())

    try {
        Log.e(TAG, "loginMeIn : try");
        val result = api.loginMeIN(loginDto)
          dao.deleteAll()
          dao.upsertUser(result.toUserEntity())
         val user = dao.getUsers().first()
        emit(Resource.Success<User?>(user.toUser()))
        Log.e(TAG, "loginMeIn : job finished");

    }catch (e:HttpException ){
        emit(Resource.Error<User?>(message = e.response().toString(),data = null))
        Log.e(TAG, "loginMeIn :"+ e);

    }catch (e:IOException){

        emit(Resource.Error<User?>(message = "Couldn't reach server, check Your internet connection",data = null))
        Log.e(TAG, "Couldn't reach server");
    }

}

with this implementation the app crash with error : Cannot access database on the main thread
and if i use coroutine scope for IO dispatchers i cant emit the Success result Please Help!

Body:
You can switch coroutine context to Dispatchers.IO when making DB requests:

val user = withContext(Dispatchers.IO) {
    dao.deleteAll()
    dao.upsertUser(result.toUserEntity())
    dao.getUsers().first()
}
emit(Resource.Success<User?>(user.toUser()))

If you use Room DB you can try to mark functions as suspend, for example:

// in Dao class
@Insert
suspend fun insertUser(user: User)

If all function are marked as suspend then you won'y need to switch coroutine context to Dispatchers.IO in flow builder.


问:
check to see if a domain is available or not using PHP?
If I have a domain like www.example.com and I want to check if it is available using DNS records (not whois)...

Is it possible to do this using PHP?

答:
Here's a script to check domain availability for some domains using whois.
In this example we check all number domains between 10 and 999 for a given top level domain (spoiler alert: they're mostly taken).

Here are predefined examples for .com .pe .ee .cc and .gg. It runs a whois search for the domain and then looks for the words "no match for domain" in the output.

```<code>$tld = "com" ;

$lookFor = array();
$lookFor['com'] = "No match for domain" ; // .com
$lookFor['pe'] = "No Object Found" ; // .pe
$lookFor['ee'] = "Domain not found" ; // ee
$lookFor['cc'] = "No match for" ; // cc
$lookFor['gg'] = "NOT FOUND" ;

$i = 10 ;
while($i < 10000)
{
    $domain = "$i.$tld" ;
    $dig = `whois $domain` ;

    if(stripos($dig, $lookFor[$tld]) !== FALSE)
    {
        echo "$domain is available\n" ;
    } else {
        echo "$domain bad\n" ;
    }

     $i ++ ;

}
</code>```

Body:
Here's a script to check domain availability for some domains using whois.
In this example we check all number domains between 10 and 999 for a given top level domain (spoiler alert: they're mostly taken).

Here are predefined examples for .com .pe .ee .cc and .gg. It runs a whois search for the domain and then looks for the words "no match for domain" in the output.

$tld = "com" ;

$lookFor = array();
$lookFor['com'] = "No match for domain" ; // .com
$lookFor['pe'] = "No Object Found" ; // .pe
$lookFor['ee'] = "Domain not found" ; // ee
$lookFor['cc'] = "No match for" ; // cc
$lookFor['gg'] = "NOT FOUND" ;

$i = 10 ;
while($i < 10000)
{
    $domain = "$i.$tld" ;
    $dig = `whois $domain` ;

    if(stripos($dig, $lookFor[$tld]) !== FALSE)
    {
        echo "$domain is available\n" ;
    } else {
        echo "$domain bad\n" ;
    }

     $i ++ ;

}


问:
Cannot use IOptions in console app .NET Core
I have a console application where I am building up the configuration

```<code>IConfiguration config = new ConfigurationBuilder()
   .AddJsonFile("appsettings.json", true, true)
   .Build();

var services = new ServiceCollection();
services.AddOptions();
services.Configure<ResourceConfiguration>(config.GetSection("ResourceConfiguration"));
</code>```

This doesnt work

```<code>  Error CS1503: Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<ResourceConfiguration>' (29, 55)
</code>```

I have the following in my using (as well as my own namespaces)

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;

```<code>IConfiguration config = new ConfigurationBuilder()
   .AddJsonFile("appsettings.json", true, true)
   .Build();
</code>```

Returns IConfigurationRoot which may be the issue?

What am I doing wrong?

This is .NET Core 3.1

Paul

答:
I have created a console app using .NET 6 to help you out.

Check the code below and let us know if it worked. =)

AppSettings.json

```<code>{
    "SETUP_OPTIONS":
    {
        "MyProperty": 100,
        "MyProperty2": "Success!"
    }
}
</code>```

usings required

```<code>using Microsoft.Extensions.Options;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
</code>```

SetupOptions class

```<code>public class SetupOptions
{
    public const string ConfigKey = "SETUP_OPTIONS";

    public int MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}
</code>```

Program.cs

```<code>static async Task Main(string[] args)
{
    IConfiguration configuration = new ConfigurationBuilder()
        .SetBasePath(currentDirectory)
        .AddJsonFile("appsettings.json", optional: false)
        .Build();

    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection, configuration);

    var serviceProvider = serviceCollection.BuildServiceProvider();

    await serviceProvider.GetService<MyAppClass>().RunAsync(args);
}

private static void ConfigureServices(ServiceCollection serviceCollection, IConfiguration configuration)
{
    // AppSettings IOptions configuration
    serviceCollection.AddOptions<SetupOptions>().Bind(configuration.GetSection(SetupOptions.ConfigKey));

    serviceCollection.AddTransient<MyAppClass>();
}
</code>```

MyAppClass.cs

```<code>public class MyAppClass
{
    private readonly SetupOptions _setupOptions;

    // Inject IOptions in your constructor
    public MyAppClass(IOptions<SetupOptions> setupOptions)
    {
        _setupOptions = setupOptions?.Value;
    }

    public async Task RunAsync(string[] args)
    {
        // Use your Setup Options value loaded from appsettings file.
        var myPropertyValue = _setupOptions.MyProperty;
    }
}
</code>```

Body:
I have a console application where I am building up the configuration

IConfiguration config = new ConfigurationBuilder()
   .AddJsonFile("appsettings.json", true, true)
   .Build();

var services = new ServiceCollection();
services.AddOptions();
services.Configure<ResourceConfiguration>(config.GetSection("ResourceConfiguration"));

This doesnt work

  Error CS1503: Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<ResourceConfiguration>' (29, 55)

I have the following in my using (as well as my own namespaces)

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;

IConfiguration config = new ConfigurationBuilder()
   .AddJsonFile("appsettings.json", true, true)
   .Build();

Returns IConfigurationRoot which may be the issue?

What am I doing wrong?

This is .NET Core 3.1

Paul

Body:
I have created a console app using .NET 6 to help you out.

Check the code below and let us know if it worked. =)

AppSettings.json

{
    "SETUP_OPTIONS":
    {
        "MyProperty": 100,
        "MyProperty2": "Success!"
    }
}

usings required

using Microsoft.Extensions.Options;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

SetupOptions class

public class SetupOptions
{
    public const string ConfigKey = "SETUP_OPTIONS";

    public int MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

Program.cs

static async Task Main(string[] args)
{
    IConfiguration configuration = new ConfigurationBuilder()
        .SetBasePath(currentDirectory)
        .AddJsonFile("appsettings.json", optional: false)
        .Build();

    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection, configuration);

    var serviceProvider = serviceCollection.BuildServiceProvider();

    await serviceProvider.GetService<MyAppClass>().RunAsync(args);
}

private static void ConfigureServices(ServiceCollection serviceCollection, IConfiguration configuration)
{
    // AppSettings IOptions configuration
    serviceCollection.AddOptions<SetupOptions>().Bind(configuration.GetSection(SetupOptions.ConfigKey));

    serviceCollection.AddTransient<MyAppClass>();
}

MyAppClass.cs

public class MyAppClass
{
    private readonly SetupOptions _setupOptions;

    // Inject IOptions in your constructor
    public MyAppClass(IOptions<SetupOptions> setupOptions)
    {
        _setupOptions = setupOptions?.Value;
    }

    public async Task RunAsync(string[] args)
    {
        // Use your Setup Options value loaded from appsettings file.
        var myPropertyValue = _setupOptions.MyProperty;
    }
}


问:
Different types of mobile Ads network
Can anyone tell me what are the different types of Ads Network available for mobile apps..
I know about AdMob and Adwhrill...But other than these two what are the other types of ads network present and which one is the best.for business prospective

with regards
Anshuman

答: You can use Google adsense also. There is one Airpush ads network getting famous lately for native applications.</p>

Title: Different types of mobile Ads network


问:
Return a value of first & last row matching criterion in Google Sheets
I have 2 columns of numbers, the idea is to find the first & last value in column L that respects a criterion and return the value from the same row in column K.
As the criterion is "higher than 99% of the max value in column L", I tried the MINIFS formula, but I cannot use this as a criterion.

I guess the solution will include the MATCH, INDEX formula but I cannot find the right combination

In this specific example,  we want to return the value of the first column that has in column L a number higher than 0,99*max(L3:L62)(=3.0879...) so it should return 19
This will be verified for a couple rows until the value goes below the 99% again. This last row is 58.

Link to sheet :
https://docs.google.com/spreadsheets/d/1MUkYDPoR1NxB8qWcYr_2Fp91FgUbnUOpfGd7EUuWCOg/edit?usp=sharing

答:
You can also try the following:

For first value

```<code>=Index(K3:K62;Min(IFERROR(1/(1/((Row(K3:K62)*(L3:L62>0,99*max(L3:L62)))))))-2)
</code>```

For last value

```<code>=Index(K3:K62;Max(IFERROR(1/(1/((Row(K3:K62)*(L3:L62>0,99*max(L3:L62)))))))-2)
</code>```

Body:
You can also try the following:

For first value

=Index(K3:K62;Min(IFERROR(1/(1/((Row(K3:K62)*(L3:L62>0,99*max(L3:L62)))))))-2)

For last value

=Index(K3:K62;Max(IFERROR(1/(1/((Row(K3:K62)*(L3:L62>0,99*max(L3:L62)))))))-2)


问:
Fullcalendar dayClick sends multiple ajax requests
I use Fullcalendar v3 with Django. and I have an issue with dayClick.
when I click a day, a modal opens that while submitting sends an ajax request to the backend.
the problem is that when I click and then click another day, it sends two ajax requests and so on.

I search for the issue, and i found that an event handler stores the requests when day clicks and then submit all. but i couldn't solve my issue.

here is the dayclick code:

```<code>       dayClick: function(date) {
            var cell = $(this);
            weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
            clicked_date = new Date(date);
            var clicked_day_name = weekday[clicked_date.getDay()];
            $('#schedule_modal').on('show.bs.modal', function (event) {
                modal = $(this)
                modal.find('#schedule_modal_title').text('Schedule your ' + clicked_day_name)
                modal.find('#only_this_day').text('Only this ' + clicked_day_name)
                modal.find('#include_other_days').text('With upcoming ' + clicked_day_name + 's to: ')
            });
            $('#schedule_modal').modal('show');
            $('.dropdown-menu').addClass('d-none');

            $('#submit_day_schedule').on('click', function () {
                if ($('#only_this').is(':checked')) {
                    schedule_option = $('#only_this').val();
                } else {
                    schedule_option = $('#schedule_option_date').val();
                }
                data = {
                    'day_schedule': $('#day_schedule_select option:selected').val(),
                    'day': moment(date).format('YYYY-MM-DD'),
                    'schedule_option': schedule_option,
                };
                $('#schedule_modal').modal('hide');
                $.ajax({
                    headers: {
                        'X-CSRFToken': $('[name="csrfmiddlewaretoken"]').val()
                    },
                    type: 'POST',
                    url: "{% url 'test_url' option=option %}",
                    data: data,
                    success: function (response) {
                        cell.css('background-color', 'red');
                        $('#day_schedule_form').trigger('reset');
                        showNotification('bg-success', response.message);
                    },
                    error: function (response) {
                        showNotification('bg-warning', response.message);
                    }
                });
            });
        },
</code>```

答:
This:

```<code>$('#schedule_modal').on('show.bs.modal', function (event) {
</code>```

...creates a new event handler for the "shown" event every time you click on a day. And since you never remove any of the previous event handlers, it means that they all run every time the modal is shown. So if you click on a day 3 times, you get 3 copies of the "shown" event handler registered, and thus that function will run 3 times whenever the modal is shown.

It's the same with

```<code>$('#submit_day_schedule').on('click', function () {
</code>```

too. Either remove any previous handlers using .off(), or register the handlers once outside fullcalendar.

Body:
I use Fullcalendar v3 with Django. and I have an issue with dayClick.
when I click a day, a modal opens that while submitting sends an ajax request to the backend.
the problem is that when I click and then click another day, it sends two ajax requests and so on.

I search for the issue, and i found that an event handler stores the requests when day clicks and then submit all. but i couldn't solve my issue.

here is the dayclick code:

       dayClick: function(date) {
            var cell = $(this);
            weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
            clicked_date = new Date(date);
            var clicked_day_name = weekday[clicked_date.getDay()];
            $('#schedule_modal').on('show.bs.modal', function (event) {
                modal = $(this)
                modal.find('#schedule_modal_title').text('Schedule your ' + clicked_day_name)
                modal.find('#only_this_day').text('Only this ' + clicked_day_name)
                modal.find('#include_other_days').text('With upcoming ' + clicked_day_name + 's to: ')
            });
            $('#schedule_modal').modal('show');
            $('.dropdown-menu').addClass('d-none');

            $('#submit_day_schedule').on('click', function () {
                if ($('#only_this').is(':checked')) {
                    schedule_option = $('#only_this').val();
                } else {
                    schedule_option = $('#schedule_option_date').val();
                }
                data = {
                    'day_schedule': $('#day_schedule_select option:selected').val(),
                    'day': moment(date).format('YYYY-MM-DD'),
                    'schedule_option': schedule_option,
                };
                $('#schedule_modal').modal('hide');
                $.ajax({
                    headers: {
                        'X-CSRFToken': $('[name="csrfmiddlewaretoken"]').val()
                    },
                    type: 'POST',
                    url: "{% url 'test_url' option=option %}",
                    data: data,
                    success: function (response) {
                        cell.css('background-color', 'red');
                        $('#day_schedule_form').trigger('reset');
                        showNotification('bg-success', response.message);
                    },
                    error: function (response) {
                        showNotification('bg-warning', response.message);
                    }
                });
            });
        },

Body:
This:

$('#schedule_modal').on('show.bs.modal', function (event) {

...creates a new event handler for the "shown" event every time you click on a day. And since you never remove any of the previous event handlers, it means that they all run every time the modal is shown. So if you click on a day 3 times, you get 3 copies of the "shown" event handler registered, and thus that function will run 3 times whenever the modal is shown.

It's the same with

$('#submit_day_schedule').on('click', function () {

too. Either remove any previous handlers using .off(), or register the handlers once outside fullcalendar.


问:
R - Issues with group order/ ggplot dodge barchart
I looked through other questions but I didn't find this exact problem

```<code>company<-c("c1","c1","c2","c2","c2","c3","c3","c3","c4","c4", "c4")
subsegment<- c("Sub2","Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3")
values<-c(120,300,30,300,1800,10,96,277, 10, 400, 1100)
df<- data.frame(company,subsegment, values)
</code>```

That's my code for the data frame and I try to make a grouped barchart:

```<code>plot.1<- ggplot(df, aes(fill=company, y=values, x=subsegment)) +
  geom_bar(position="dodge", stat="identity", alpha=0.5)
</code>```

The plot I get is exactly what I want, values for each company grouped by SubSegment... except the subsegments are ordered from left to right in default in alphabetical order "Sub1","Sub2","Sub3" and same for the companies...

I would like the same graphic to appear, but showing first "Sub3" then "Sub1" and last "Sub2"
I would also like for the bars inside each group (inside each subsegment) to be ordered by value from bigger to smaller, instead of just alphabetically.

I attach picture of the graph I get:

Hope the question is clear enough, I want to get the same graph but change order of things in the x axis

答:
To reorder the subsegment, assign factor to it and specify the orders in levels.

To reorder the bars within dodged bar chart, use reorder to order the dodged bars with descending size of values.

```<code>library(tidyverse)

ggplot(df, aes(factor(subsegment, levels = c("Sub3", "Sub1", "Sub2")),
               values,
               fill = reorder(company, desc(values)))) +
  geom_bar(position="dodge", stat="identity", alpha=0.5) +
  labs(x = "subsegment", fill = "company")
</code>```

Body:
I looked through other questions but I didn't find this exact problem

company<-c("c1","c1","c2","c2","c2","c3","c3","c3","c4","c4", "c4")
subsegment<- c("Sub2","Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3")
values<-c(120,300,30,300,1800,10,96,277, 10, 400, 1100)
df<- data.frame(company,subsegment, values)

That's my code for the data frame and I try to make a grouped barchart:

plot.1<- ggplot(df, aes(fill=company, y=values, x=subsegment)) +
  geom_bar(position="dodge", stat="identity", alpha=0.5)

The plot I get is exactly what I want, values for each company grouped by SubSegment... except the subsegments are ordered from left to right in default in alphabetical order "Sub1","Sub2","Sub3" and same for the companies...

I would like the same graphic to appear, but showing first "Sub3" then "Sub1" and last "Sub2"
I would also like for the bars inside each group (inside each subsegment) to be ordered by value from bigger to smaller, instead of just alphabetically.

I attach picture of the graph I get:

Hope the question is clear enough, I want to get the same graph but change order of things in the x axis

Body:
To reorder the subsegment, assign factor to it and specify the orders in levels.

To reorder the bars within dodged bar chart, use reorder to order the dodged bars with descending size of values.

library(tidyverse)

ggplot(df, aes(factor(subsegment, levels = c("Sub3", "Sub1", "Sub2")),
               values,
               fill = reorder(company, desc(values)))) +
  geom_bar(position="dodge", stat="identity", alpha=0.5) +
  labs(x = "subsegment", fill = "company")


问:
How can I create an array of React.RefObjects
I have a custom pin input of 5 input fields. My goal is to have control of the next input via reference. so I can perform an action like reference.focus() or reference.unfocus().

Presently my code looks like this:

```<code>const PinInput = ({ ...props }: Props): JSX.Element => {
  const [value, setValue] = useState<Array<string>>(Array.from({ length: 6 }, () => ''));
  const inputRef = React.useRef<HTMLInputElement>(null);

  return (
    <Box sx={{ display: 'flex', justifyContent: 'space-between', flexDirection: 'row' }}>
      {_.times(6, (i) => (
        <TextField
          key={i.toString()}
          id={i.toString()}
          className="pinError"
          placeholder={props.placeholder}
          sx={{
            borderRadius: '4px',
          }}
          inputRef={inputRef}
          inputProps={{
            inputMode: 'numeric',
            size: 3,
            maxLength: 1,
            style: {
              color: colors.errorDefault,
              textAlign: 'center',
              backgroundColor: colors.error80,
              caretColor: colors.transparent,
            },
          }}
          required
          value={value[i]}
          onKeyDown={(event) => {
            if (event.key === 'Backspace') { console.log(event.key); }
          }}
          onChange={(event) => {
            value[i] = event.target.value;
            setValue([...value]);
            inputRef?.current?.focus();
            if (props.onChange) props.onChange(event);
          }}
        />
      ))}
    </Box>
  );
};
</code>```

But the issue is now, I have only one inputRef for all the input pins. how can I make this dynamic. I tried this:

```<code>const refs = Array.from({ length: 6 }, () => React.useRef<HTMLInputElement>(null));
</code>```

but was met with the error:
React Hook "React.useRef" cannot be called inside a callback.

答:
You need to create an array of Refs to manage all your inuts separately. Here is a repro on Stackblitz (Based on MUI's provided stackblitz of TextField) and here is the code :

import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import * as _ from 'lodash';

export default function BasicTextFields() {
  const inputRefs = React.useRef([]);

  React.useEffect(() => {
    console.log(inputRefs.current);
  });

  return (
    <Box
      component="form"
      sx={{
        '& > :not(style)': { m: 1, width: '25ch' },
      }}
      noValidate
      autoComplete="off"
    >
      {_.times(6, (i) => (
        <TextField
          key={Math.random()}
          inputRef={(el) => (inputRefs.current[i] = el)}
          defaultValue={`input number ${i}`}
          id="outlined-basic"
          label="Outlined"
          variant="outlined"
        />
      ))}
    </Box>
  );
}
```

You can see in the console that an array of refs is displayed.

Body:
I have a custom pin input of 5 input fields. My goal is to have control of the next input via reference. so I can perform an action like reference.focus() or reference.unfocus().

Presently my code looks like this:

const PinInput = ({ ...props }: Props): JSX.Element => {
  const [value, setValue] = useState<Array<string>>(Array.from({ length: 6 }, () => ''));
  const inputRef = React.useRef<HTMLInputElement>(null);

  return (
    <Box sx={{ display: 'flex', justifyContent: 'space-between', flexDirection: 'row' }}>
      {_.times(6, (i) => (
        <TextField
          key={i.toString()}
          id={i.toString()}
          className="pinError"
          placeholder={props.placeholder}
          sx={{
            borderRadius: '4px',
          }}
          inputRef={inputRef}
          inputProps={{
            inputMode: 'numeric',
            size: 3,
            maxLength: 1,
            style: {
              color: colors.errorDefault,
              textAlign: 'center',
              backgroundColor: colors.error80,
              caretColor: colors.transparent,
            },
          }}
          required
          value={value[i]}
          onKeyDown={(event) => {
            if (event.key === 'Backspace') { console.log(event.key); }
          }}
          onChange={(event) => {
            value[i] = event.target.value;
            setValue([...value]);
            inputRef?.current?.focus();
            if (props.onChange) props.onChange(event);
          }}
        />
      ))}
    </Box>
  );
};

But the issue is now, I have only one inputRef for all the input pins. how can I make this dynamic. I tried this:

const refs = Array.from({ length: 6 }, () => React.useRef<HTMLInputElement>(null));

but was met with the error:
React Hook "React.useRef" cannot be called inside a callback.

Body:
You need to create an array of Refs to manage all your inuts separately. Here is a repro on Stackblitz (Based on MUI's provided stackblitz of TextField) and here is the code :

import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import * as _ from 'lodash';

export default function BasicTextFields() {
  const inputRefs = React.useRef([]);

  React.useEffect(() => {
    console.log(inputRefs.current);
  });

  return (
    <Box
      component="form"
      sx={{
        '& > :not(style)': { m: 1, width: '25ch' },
      }}
      noValidate
      autoComplete="off"
    >
      {_.times(6, (i) => (
        <TextField
          key={Math.random()}
          inputRef={(el) => (inputRefs.current[i] = el)}
          defaultValue={`input number ${i}`}
          id="outlined-basic"
          label="Outlined"
          variant="outlined"
        />
      ))}
    </Box>
  );
}

You can see in the console that an array of refs is displayed.


问:
The best practice in using the base interface
Our purpose of using Interface was to have the same method for each class, we realized that the method we previously determined was not sufficient for the task of each class.

I decided to solve this problem by creating an overload method

Is the usage in the example below a correct method? What do you recommend

Base Interface

```<code>public interface IBankMapper<T1,T2,T3>
    {
        public  T1 Test(T2 t2,T3 t3);

    }
</code>```

Interface that inherits from the base interface for X bank

```<code> public interface IXBank : IBankMapper<string, string, string>
    {
        public int Test(string t2, string t3, string t4,int t5);
    }
</code>```

use of the interface

```<code>   public class XBank : IXBank
    {
        public string Test(string t2, string t3)
        {
            throw new NotImplementedException();
        }

        public int Test(string t2, string t3, string t4, int t5)
        {

            return t2.Length + t3.Length + t4.Length + t5;
        }

    }
</code>```

we used it like in this example before we needed new parameters.(Y Bank)

```<code>  public interface IYBank : IBankMapper<string, string, string>
    {

    }

   public class YBank : IYBank
    {
        public string Test(string t2, string t3)
        {
            return (t2.Length + t3.Length).ToString();
        }
    }
</code>```

As seen here, the method named Test from the base interface throw new NotImplementedException();
to be left with the body is this wrong? What's the solution?

FLOW

答:
Tested this, runs with no problem, however as pointed by Jonas, it's not the best solution:</p>
```<code>using System;

namespace ConsoleApp2
{
class Program
{
    static void Main(string[] args)
    {
        var xB = new XBank();
        var yB = new YBank();

        Console.WriteLine(xB.Test("a", "b"));
        Console.WriteLine(yB.Test("a", "b"));
    }
}

public interface IBankMapper<T1, T2, T3>
{
    public T1 Test(T2 t2, T3 t3);

}

public interface IXBank : IBankMapper<string, string, string>
{
    public int Test(string t2, string t3, string t4, int t5);
}

public class XBank : IXBank
{
    public string Test(string t2, string t3)
    {
        return (t2.Length + t3.Length).ToString();
    }

    public int Test(string t2, string t3, string t4, int t5)
    {

        return t2.Length + t3.Length + t4.Length + t5;
    }

}

public interface IYBank : IBankMapper<string, string, string>
{

}

public class YBank : IYBank
{
    public string Test(string t2, string t3)
    {
        return (t2.Length + t3.Length).ToString();
        }
    }
}
</code>```

Body:
Our purpose of using Interface was to have the same method for each class, we realized that the method we previously determined was not sufficient for the task of each class.

I decided to solve this problem by creating an overload method

Is the usage in the example below a correct method? What do you recommend

Base Interface

public interface IBankMapper<T1,T2,T3>
    {
        public  T1 Test(T2 t2,T3 t3);

    }

Interface that inherits from the base interface for X bank

 public interface IXBank : IBankMapper<string, string, string>
    {
        public int Test(string t2, string t3, string t4,int t5);
    }

use of the interface

   public class XBank : IXBank
    {
        public string Test(string t2, string t3)
        {
            throw new NotImplementedException();
        }

        public int Test(string t2, string t3, string t4, int t5)
        {

            return t2.Length + t3.Length + t4.Length + t5;
        }

    }

we used it like in this example before we needed new parameters.(Y Bank)

  public interface IYBank : IBankMapper<string, string, string>
    {

    }

   public class YBank : IYBank
    {
        public string Test(string t2, string t3)
        {
            return (t2.Length + t3.Length).ToString();
        }
    }

As seen here, the method named Test from the base interface throw new NotImplementedException();
to be left with the body is this wrong? What's the solution?

FLOW

Body:
Tested this, runs with no problem, however as pointed by Jonas, it's not the best solution:

using System;

namespace ConsoleApp2
{
class Program
{
    static void Main(string[] args)
    {
        var xB = new XBank();
        var yB = new YBank();

        Console.WriteLine(xB.Test("a", "b"));
        Console.WriteLine(yB.Test("a", "b"));
    }
}

public interface IBankMapper<T1, T2, T3>
{
    public T1 Test(T2 t2, T3 t3);

}

public interface IXBank : IBankMapper<string, string, string>
{
    public int Test(string t2, string t3, string t4, int t5);
}

public class XBank : IXBank
{
    public string Test(string t2, string t3)
    {
        return (t2.Length + t3.Length).ToString();
    }

    public int Test(string t2, string t3, string t4, int t5)
    {

        return t2.Length + t3.Length + t4.Length + t5;
    }

}

public interface IYBank : IBankMapper<string, string, string>
{

}

public class YBank : IYBank
{
    public string Test(string t2, string t3)
    {
        return (t2.Length + t3.Length).ToString();
        }
    }
}


问:
Change Email Notification Settings on a Google Sheet using Google Sheets API
Can someone point me at the API method for changing the "Email Notification Settings" on a Google Sheet?

Thanks.

答:
Programmaticaly, you cannot change Google Sheets UI settings like notification rules

The closest you can do is to create a webhook that will watch for changes and implement the request of your choice (e.g. sending an email) when a certain change of a Drive File (inlcluding Google Sheets) occurs.

You can implement this by watching for file changes with the Google Drive API
and receiving push notifications.


问:
How to make IntelliJ IDEA load org.slf4j.impl.StaticLoggerBinder in order to run Kafka?
I want to run Kafka from IDEA and I am getting the following error:

```<code>> Task :core:Kafka.main()
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
SLF4J: Failed to load class "org.slf4j.impl.StaticMDCBinder".
SLF4J: Defaulting to no-operation MDCAdapter implementation.
SLF4J: See http://www.slf4j.org/codes.html#no_static_mdc_binder for further details.

> Task :core:Kafka.main() FAILED

Execution failed for task ':core:Kafka.main()'.
> Process 'command '/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
</code>```

I am able to run Kafka from the terminal.
I run Zookeeper from terminal and then Run Kafka from IDEA.

Steps that I follow to run Kafka

As usual, I run the command ./gradlew jar to build Kafka from the source, using the terminal.
I open the project in IDEA using idea . from the root directory of the cloned repository.

I opened the file: core/src/main/scala/kafka/Kafka.scala

I then navigate to main() function and click on the green triangle.

This helps me get the Run configurations and it fails. I then add the config/server.properties in the Program Arguments to make the Run config look like this:

Upon running with the above configurations, I get the aforementioned error.

I searched a bit and found that the same issue was resolved by adding dependencies, like mentioned here and here but I could not understand how I can add dependency as I do not use Maven and I cannot find the file pom.xml file as described here.

Update 1

I tried to add the exact dependency as stated from the terminal to the Run configurations, I am unsure whether that is added or not because the result is still the same:

This is what I find when I run Kafka from the terminal:

```<code>SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/core/build/dependant-libs-2.13.5/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/tools/build/dependant-libs-2.13.5/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/api/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/transforms/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/runtime/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/file/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/mirror/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/mirror-client/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/json/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/basic-auth-extension/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
[2021-03-23 10:54:59,524] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$)
</code>```

From the second last line, I deduced the dependency name and added it as shown in the last image.

答:
I was also facing the same issue while trying to set up the Apache Kafka source code in Intellij IDEA and here's what I have tried to solve the SL4J issue.

Set the JVM arguments as highlighted in the picture below:

Also, in the build.gradle file, add the following dependency under section project(':core') after the line implementation libs.commonsCli

```<code>implementation libs.slf4jlog4j
</code>```

Tested on Java 17, Apache Kafka 3.1.0 and Intellij IDEA 2021.3.1

Body:
I want to run Kafka from IDEA and I am getting the following error:

> Task :core:Kafka.main()
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
SLF4J: Failed to load class "org.slf4j.impl.StaticMDCBinder".
SLF4J: Defaulting to no-operation MDCAdapter implementation.
SLF4J: See http://www.slf4j.org/codes.html#no_static_mdc_binder for further details.

> Task :core:Kafka.main() FAILED

Execution failed for task ':core:Kafka.main()'.
> Process 'command '/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

I am able to run Kafka from the terminal.
I run Zookeeper from terminal and then Run Kafka from IDEA.

Steps that I follow to run Kafka

As usual, I run the command ./gradlew jar to build Kafka from the source, using the terminal.
I open the project in IDEA using idea . from the root directory of the cloned repository.

I opened the file: core/src/main/scala/kafka/Kafka.scala

I then navigate to main() function and click on the green triangle.

This helps me get the Run configurations and it fails. I then add the config/server.properties in the Program Arguments to make the Run config look like this:

Upon running with the above configurations, I get the aforementioned error.

I searched a bit and found that the same issue was resolved by adding dependencies, like mentioned here and here but I could not understand how I can add dependency as I do not use Maven and I cannot find the file pom.xml file as described here.

Update 1

I tried to add the exact dependency as stated from the terminal to the Run configurations, I am unsure whether that is added or not because the result is still the same:

This is what I find when I run Kafka from the terminal:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/core/build/dependant-libs-2.13.5/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/tools/build/dependant-libs-2.13.5/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/api/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/transforms/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/runtime/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/file/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/mirror/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/mirror-client/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/json/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/aviralsrivastava/dev/kafka/connect/basic-auth-extension/build/dependant-libs/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
[2021-03-23 10:54:59,524] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$)

From the second last line, I deduced the dependency name and added it as shown in the last image.

Body:
I was also facing the same issue while trying to set up the Apache Kafka source code in Intellij IDEA and here's what I have tried to solve the SL4J issue.

Set the JVM arguments as highlighted in the picture below:

Also, in the build.gradle file, add the following dependency under section project(':core') after the line implementation libs.commonsCli

implementation libs.slf4jlog4j

Tested on Java 17, Apache Kafka 3.1.0 and Intellij IDEA 2021.3.1


问:
React Native: AWS Amplify Auth.signOut() not working
React Native noob here, trying to implement AWS Amplify authentication flow into my project. But the Auth.signOut() function is not working at all. Nothing happens when I press the logout button.

```<code>const onLogOutPressed = async () => {
        //Auth.signOut();
        try {
            await Auth.signOut({ global: true });
        } catch (error) {
            console.log('Error Logging Out', error);
        }
    }
</code>```

My first version was purely Auth.signOut() as that was what the tutorial I was following did. Another guide suggested using the try method so I commented the first Auth function and added the rest.

Some help would be greatly appreciated. Do let me know if more info is required, thanks in advance.

答:
If you're using React Native UI from Amplify and wrapped your component with withAuthenticator, below code should work.

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
  };

  ...

    Auth.signOut().then(() => {
      this.props.onStateChange(("signedOut");
    });
}

</code>```
```<code>// Functional component
const App = (props) => {

  ...

    Auth.signOut().then(() => {
      this.props.onStateChange("signedOut", null);
    })
}

</code>```

If you're not using React Native UI, then you need to handle redirection yourself. Auth.signOut() will only clear session.

Body:
React Native noob here, trying to implement AWS Amplify authentication flow into my project. But the Auth.signOut() function is not working at all. Nothing happens when I press the logout button.

const onLogOutPressed = async () => {
        //Auth.signOut();
        try {
            await Auth.signOut({ global: true });
        } catch (error) {
            console.log('Error Logging Out', error);
        }
    }

My first version was purely Auth.signOut() as that was what the tutorial I was following did. Another guide suggested using the try method so I commented the first Auth function and added the rest.

Some help would be greatly appreciated. Do let me know if more info is required, thanks in advance.

Body:
If you're using React Native UI from Amplify and wrapped your component with withAuthenticator, below code should work.

class App extends React.Component {
  constructor(props) {
    super(props);
  };

  ...

    Auth.signOut().then(() => {
      this.props.onStateChange(("signedOut");
    });
}

// Functional component
const App = (props) => {

  ...

    Auth.signOut().then(() => {
      this.props.onStateChange("signedOut", null);
    })
}

If you're not using React Native UI, then you need to handle redirection yourself. Auth.signOut() will only clear session.


答:
is this wrong?

This would be a rather clear violation of liskovs substitution principle, i.e. all objects implementing a interface should interchangeable. Implementing an interface is a promise of providing some functionality, throwing NotImplementedException violates that promise.

What's the solution?

This depend on the specific situation.

In some cases it is possible to provide a default value for added parameters. If so, you can make the parameter optional, make the old method a default interface method or an extension method to avoid changing all the call sites.

It might even be possible to remove the old method completely, and change all the callers, but this assumes the callers can provide meaning full values for all parameters.

In other cases it might be a sign that the interfaces should be separate, so that each can be used where appropriate. c# allow multiple interface implementations, so a class can still implement both interfaces.

It is difficult to provide concrete recommendations since I assume the example is fictional.

Title: The best practice in using the base interface


问:
I am having Issues counting values in a row with separators using SQL
I am new to snowflake and trying the count the number of values in a row with separators using SQL. I am not sure how to go about it. I've googled solutions for this but have not been able to find one.

table name: Lee_tab

user
names

id01
Jon;karl;lee;

id02
Abi;jackson;

id03
don;

id04

what I want to achieve

user
names
name_count

id01
Jon;karl;lee;
3

id02
Abi;jackson;
2

id03
don;
1

id04

0

答:
Here is a different answer, using the Snowflake SPLIT_TO_TABLE function. This function splits the string on the delimiter, creating a row for each value, which we lateral join back to the CTE table, finally we COUNT and GROUP BY using standard SQL syntax:</p>
```<code>with cte as (
    select 'id01' as user, 'Jon;karl;lee' as names union all
    select 'id02' as user, 'Abi;jackson' as names union all
    select 'id03' as user, 'don' as names
)
select user, names, count(value) as count_names
    from cte, lateral split_to_table(cte.names, ';')
group by user, names;
</code>```

Body:
Here is a different answer, using the Snowflake SPLIT_TO_TABLE function. This function splits the string on the delimiter, creating a row for each value, which we lateral join back to the CTE table, finally we COUNT and GROUP BY using standard SQL syntax:

with cte as (
    select 'id01' as user, 'Jon;karl;lee' as names union all
    select 'id02' as user, 'Abi;jackson' as names union all
    select 'id03' as user, 'don' as names
)
select user, names, count(value) as count_names
    from cte, lateral split_to_table(cte.names, ';')
group by user, names;


问:
Kafka Rejoining Group Quite Frequently
I have a Spring Boot application which consists of 10 different consumers , trying to consume messages from 10 different topics. The application uses same consumer group as all the 10 different topics are listed under the same consumer group. Now after a while of running the application (After 5 hours) , I am seeing the consumers going are trying to rebalance , and at times the rebalances never finishes hence unable to receive the messages after a while.

Here is my consumer configuration.

```<code>public Map<String, Object> consumerConfigs(String clientID) {
    Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);

    props.put("key.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
    props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, consumerGroup);
    props.put(SECURITY_PROTOCOL, securityProtocol);
    props.put(SASL_MECHANISM, saslMechanism);
    props.put(SASL_JAAS_CONFIG,
            String.format("%s required username=\"%s\" password=\"%s\" ;", loginModule, username, kafkaSecretPass));

    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
    props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 5);
    props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 10000);
    props.put(ConsumerConfig.CLIENT_ID_CONFIG, clientID);
    props.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,
            "org.apache.kafka.clients.consumer.RoundRobinAssignor");
   //props.put(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, 120000);
  //props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 60000);
  //props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 600000);
 //props.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, 2097164);
 //props.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 30000);
     return props;
}
</code>```

Here is the error I see after running the consumer for a while.

```<code>[Consumer clientId=consumer-one, groupId=group-1] (Re-)joining group
</code>```

This attempt to rejoin the group goes on a for a long time , eventually it is never able to join the group.

Here is how one of the consumer is consuming the topic and sending it for processing.

```<code>  @EventListener(ApplicationStartedEvent.class)
public Disposable consume() {
    return reactiveKafkaConsumerTemplate
            .receive()
            .concatMap(consumerRecord -> {
                log.info("Received event:customer offset {} and value {}",
                        consumerRecord.offset(),new String(consumerRecord.value(), StandardCharsets.UTF_8));
                return updateCustomer(consumerRecord).flatMap(success -> {
                    consumerRecord.receiverOffset().acknowledge();
                    return Mono.just("Received");
                });
            })
            .retryWhen(Retry.backoff(3, Duration.ofSeconds(2)).transientErrors(true))
            .onErrorResume(e -> {
                log.info("Customer - Receiver On Error Resume");
                return Mono.empty();
            })
            .repeat()
            .subscribe(suc -> log.info("Subscribe successfully in Customer"), err -> log.error("Error occurred during subscribe Customer, " + err));
}
</code>```

答:
Frequent rebalances are usually caused because it is taking too long for the consumer to process batches. This happens because the consumer is processing the batch for a long time (and heartbeats are not being sent) and therefore the brokers think that consumer was lost and they start re-balancing.

I would either suggest to create smaller batches by reducing the value of max.partition.fetch.bytes or extend/increase heartbeat intervals by increasing the value of heartbeat.interval.ms.

For more info : More info

Title: Kafka Rejoining Group Quite Frequently

Body:
I have a Spring Boot application which consists of 10 different consumers , trying to consume messages from 10 different topics. The application uses same consumer group as all the 10 different topics are listed under the same consumer group. Now after a while of running the application (After 5 hours) , I am seeing the consumers going are trying to rebalance , and at times the rebalances never finishes hence unable to receive the messages after a while.

Here is my consumer configuration.

public Map<String, Object> consumerConfigs(String clientID) {
    Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);

    props.put("key.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
    props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, consumerGroup);
    props.put(SECURITY_PROTOCOL, securityProtocol);
    props.put(SASL_MECHANISM, saslMechanism);
    props.put(SASL_JAAS_CONFIG,
            String.format("%s required username=\"%s\" password=\"%s\" ;", loginModule, username, kafkaSecretPass));

    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
    props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 5);
    props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 10000);
    props.put(ConsumerConfig.CLIENT_ID_CONFIG, clientID);
    props.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,
            "org.apache.kafka.clients.consumer.RoundRobinAssignor");
   //props.put(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, 120000);
  //props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 60000);
  //props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 600000);
 //props.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, 2097164);
 //props.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 30000);
     return props;
}

Here is the error I see after running the consumer for a while.

[Consumer clientId=consumer-one, groupId=group-1] (Re-)joining group

This attempt to rejoin the group goes on a for a long time , eventually it is never able to join the group.

Here is how one of the consumer is consuming the topic and sending it for processing.

  @EventListener(ApplicationStartedEvent.class)
public Disposable consume() {
    return reactiveKafkaConsumerTemplate
            .receive()
            .concatMap(consumerRecord -> {
                log.info("Received event:customer offset {} and value {}",
                        consumerRecord.offset(),new String(consumerRecord.value(), StandardCharsets.UTF_8));
                return updateCustomer(consumerRecord).flatMap(success -> {
                    consumerRecord.receiverOffset().acknowledge();
                    return Mono.just("Received");
                });
            })
            .retryWhen(Retry.backoff(3, Duration.ofSeconds(2)).transientErrors(true))
            .onErrorResume(e -> {
                log.info("Customer - Receiver On Error Resume");
                return Mono.empty();
            })
            .repeat()
            .subscribe(suc -> log.info("Subscribe successfully in Customer"), err -> log.error("Error occurred during subscribe Customer, " + err));
}


问:
Redirect at first login in Wordpress/Woocommerce
```<code>Good morning,
</code>```

I can't do a redirect on the first wordpress login for clients,
I created a "has_not_logged_in_yet" field on the database,
but when I go to do an update, the update_user_meta function with this "woocommerce_login_redirect" hook doesn't work.
If I use "init" as a hook, update_user_meta works but the redirect doesn't work.
I am attaching the code,
you can help me? Thank you!

```<code>function after_user_register( $user_id ){
    add_user_meta($user_id, "has_not_logged_in_yet", "true", true);
    }
add_action( 'user_register', 'after_user_register', 10, 1 );

function wc_custom_user_redirect( $redirect, $user ) {
    $role = $user->roles[0];
    $id= $user->ID;
    $dashboard = admin_url();
    $catalogo = get_permalink( wc_get_page_id( 'shop' ) );
    $changePWeAddress = get_permalink( get_page_by_title( 'Conferma Indirizzo' ) );
    if ( $role == 'customer' ) {
      $user_meta=get_user_meta($id);
      if($user_meta['has_not_logged_in_yet'][0] == "true"){
          update_user_meta($user_id, "has_not_logged_in_yet","false");
          $redirect = $changePWeAddress;
          }
          else
          $redirect =   $catalogo;
          }
          return $redirect
          }

add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );
</code>```

答:
There are several syntax errors. I have revised your code. Also, you are passing $user_id variable to update_user_meta

Replace

```<code>update_user_meta( $user_id, "has_not_logged_in_yet","false" );
</code>```

With this

```<code>update_user_meta( $id, "has_not_logged_in_yet","false" );
</code>```

Complete Code

```<code>function after_user_register( $user_id ){
    add_user_meta( $user_id, "has_not_logged_in_yet", "true", true );
}
add_action( 'user_register', 'after_user_register', 10, 1 );

function wc_custom_user_redirect( $redirect, $user ) {

    $role             = $user->roles[0];
    $id               = $user->ID;
    $dashboard        = admin_url();
    $catalogo         = get_permalink( wc_get_page_id( 'shop' ) );
    $changePWeAddress = get_permalink( get_page_by_title( 'Conferma Indirizzo' ) );

    if ( $role == 'customer' ) {
        $user_meta = get_user_meta($id);
        if( $user_meta['has_not_logged_in_yet'][0] == "true" ){
            update_user_meta( $id, "has_not_logged_in_yet","false" );
            $redirect = $changePWeAddress;
        } else{
            $redirect = $catalogo;
        }
        return $redirect;
    }
}
add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );
</code>```

Body:
Good morning,

I can't do a redirect on the first wordpress login for clients,
I created a "has_not_logged_in_yet" field on the database,
but when I go to do an update, the update_user_meta function with this "woocommerce_login_redirect" hook doesn't work.
If I use "init" as a hook, update_user_meta works but the redirect doesn't work.
I am attaching the code,
you can help me? Thank you!

function after_user_register( $user_id ){
    add_user_meta($user_id, "has_not_logged_in_yet", "true", true);
    }
add_action( 'user_register', 'after_user_register', 10, 1 );

function wc_custom_user_redirect( $redirect, $user ) {
    $role = $user->roles[0];
    $id= $user->ID;
    $dashboard = admin_url();
    $catalogo = get_permalink( wc_get_page_id( 'shop' ) );
    $changePWeAddress = get_permalink( get_page_by_title( 'Conferma Indirizzo' ) );
    if ( $role == 'customer' ) {
      $user_meta=get_user_meta($id);
      if($user_meta['has_not_logged_in_yet'][0] == "true"){
          update_user_meta($user_id, "has_not_logged_in_yet","false");
          $redirect = $changePWeAddress;
          }
          else
          $redirect =   $catalogo;
          }
          return $redirect
          }

add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );

Body:
There are several syntax errors. I have revised your code. Also, you are passing $user_id variable to update_user_meta

Replace

update_user_meta( $user_id, "has_not_logged_in_yet","false" );

With this

update_user_meta( $id, "has_not_logged_in_yet","false" );

Complete Code

function after_user_register( $user_id ){
    add_user_meta( $user_id, "has_not_logged_in_yet", "true", true );
}
add_action( 'user_register', 'after_user_register', 10, 1 );

function wc_custom_user_redirect( $redirect, $user ) {

    $role             = $user->roles[0];
    $id               = $user->ID;
    $dashboard        = admin_url();
    $catalogo         = get_permalink( wc_get_page_id( 'shop' ) );
    $changePWeAddress = get_permalink( get_page_by_title( 'Conferma Indirizzo' ) );

    if ( $role == 'customer' ) {
        $user_meta = get_user_meta($id);
        if( $user_meta['has_not_logged_in_yet'][0] == "true" ){
            update_user_meta( $id, "has_not_logged_in_yet","false" );
            $redirect = $changePWeAddress;
        } else{
            $redirect = $catalogo;
        }
        return $redirect;
    }
}
add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );