问:
cucumber (with pico-container): IllegalStateException: Cannot stop. Current container state was: CONSTRUCTED
Below error is being encountered with selenium/testng/cucumber(with pico-container) project.

```<code>java.lang.IllegalStateException: Cannot stop.  Current container state was: CONSTRUCTED
    at org.picocontainer.lifecycle.DefaultLifecycleState.stopping(DefaultLifecycleState.java:72)
    at org.picocontainer.DefaultPicoContainer.stop(DefaultPicoContainer.java:794)
    at io.cucumber.picocontainer.PicoFactory.stop(PicoFactory.java:37)
    at io.cucumber.core.runner.Runner.disposeBackendWorlds(Runner.java:156)
    at io.cucumber.core.runner.Runner.runPickle(Runner.java:78)
    at io.cucumber.testng.TestNGCucumberRunner.lambda$runScenario$1(TestNGCucumberRunner.java:132)
    at io.cucumber.core.runtime.CucumberExecutionContext.lambda$runTestCase$3(CucumberExecutionContext.java:110)
    at io.cucumber.core.runtime.RethrowingThrowableCollector.executeAndThrow(RethrowingThrowableCollector.java:23)
    at io.cucumber.core.runtime.CucumberExecutionContext.runTestCase(CucumberExecutionContext.java:110)
    at io.cucumber.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:129)
    at io.cucumber.testng.AbstractTestNGCucumberTests.runScenario(AbstractTestNGCucumberTests.java:35)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
    at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
    at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
    at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)
    at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.testng.TestRunner.privateRun(TestRunner.java:794)
    at org.testng.TestRunner.run(TestRunner.java:596)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)
    at org.testng.SuiteRunner.run(SuiteRunner.java:276)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
    at org.testng.TestNG.runSuites(TestNG.java:1063)
    at org.testng.TestNG.run(TestNG.java:1031)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:284)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:119)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:428)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:162)
    at org.apache.maven.surefire.booter.ForkedBooter.run(ForkedBooter.java:562)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:548)

</code>```

With below execution methods, test is running with no issues:

Run feature file

Run testng.xml

Run Runner.java file

However if I run from command prompt:

mvn test or mvn verify, I am getting the error.

Body:
Below error is being encountered with selenium/testng/cucumber(with pico-container) project.

java.lang.IllegalStateException: Cannot stop.  Current container state was: CONSTRUCTED
    at org.picocontainer.lifecycle.DefaultLifecycleState.stopping(DefaultLifecycleState.java:72)
    at org.picocontainer.DefaultPicoContainer.stop(DefaultPicoContainer.java:794)
    at io.cucumber.picocontainer.PicoFactory.stop(PicoFactory.java:37)
    at io.cucumber.core.runner.Runner.disposeBackendWorlds(Runner.java:156)
    at io.cucumber.core.runner.Runner.runPickle(Runner.java:78)
    at io.cucumber.testng.TestNGCucumberRunner.lambda$runScenario$1(TestNGCucumberRunner.java:132)
    at io.cucumber.core.runtime.CucumberExecutionContext.lambda$runTestCase$3(CucumberExecutionContext.java:110)
    at io.cucumber.core.runtime.RethrowingThrowableCollector.executeAndThrow(RethrowingThrowableCollector.java:23)
    at io.cucumber.core.runtime.CucumberExecutionContext.runTestCase(CucumberExecutionContext.java:110)
    at io.cucumber.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:129)
    at io.cucumber.testng.AbstractTestNGCucumberTests.runScenario(AbstractTestNGCucumberTests.java:35)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
    at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
    at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
    at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)
    at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.testng.TestRunner.privateRun(TestRunner.java:794)
    at org.testng.TestRunner.run(TestRunner.java:596)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)
    at org.testng.SuiteRunner.run(SuiteRunner.java:276)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
    at org.testng.TestNG.runSuites(TestNG.java:1063)
    at org.testng.TestNG.run(TestNG.java:1031)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:284)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:119)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:428)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:162)
    at org.apache.maven.surefire.booter.ForkedBooter.run(ForkedBooter.java:562)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:548)

With below execution methods, test is running with no issues:

Run feature file

Run testng.xml

Run Runner.java file

However if I run from command prompt:

mvn test or mvn verify, I am getting the error.


来源: stackexchange

问:
(Roblox) how can I cut a portion of a part(s)?
I am making a road merge in roblox but I would have to cut the road to fit the merge but I dont know how how can I cut it (I need something like (bool tool/brush/difference) in blender)

How do I fix this

I tried layering the straight road under the merge but it didnt work

ContentLicense: CC BY-SA 4.0


问:
In screen lock background play music and controls
I am using React native video npm - In screnio In play audio in after screen lock .

Im using this type of code

```<code><Video
    source={{
        uri: this.props.data.Link,
    }}
    controls
    playInBackground={true}
    playWhenInactive={true}
    disableFocus={false}
    audioOnly={true}
    preventsDisplaySleepDuringVideoPlayback={false}
    pictureInPicture={true}
    ignoreSilentSwitch={'inherit'}
    lockControl={true}
    allowsExternalPlayback={true}
    automaticallyWaitsToMinimizeStalling={false}
/>
</code>```

Its working in lock screen play audio but controls are disabled please anyone help me

videos are playing at a time in the background without viewing the videos and another problem is all videos controls={true}  in lock screen
Any configure in ios upto 14 version Its fine working in ios 12 please any configuration in xcode or swift language to react native code

Body:
I am using React native video npm - In screnio In play audio in after screen lock .

Im using this type of code

<Video
    source={{
        uri: this.props.data.Link,
    }}
    controls
    playInBackground={true}
    playWhenInactive={true}
    disableFocus={false}
    audioOnly={true}
    preventsDisplaySleepDuringVideoPlayback={false}
    pictureInPicture={true}
    ignoreSilentSwitch={'inherit'}
    lockControl={true}
    allowsExternalPlayback={true}
    automaticallyWaitsToMinimizeStalling={false}
/>

Its working in lock screen play audio but controls are disabled please anyone help me

videos are playing at a time in the background without viewing the videos and another problem is all videos controls={true}  in lock screen
Any configure in ios upto 14 version Its fine working in ios 12 please any configuration in xcode or swift language to react native code


问:
How to connect from MongoDB Atlas version 4.4 to Mongo DB Shell?
I copied the Mongo DB Shell connection string from Mongo DB Atlas and pasted to Mongo DB Shell. I got the following error.
Please enter a MongoDB connection string (Default: mongodb://localhost/): mongo "mongodb+srv://cluster0.h75mayj.mongodb.net/myFirstDatabase" --username Kirushiraam
Please enter a MongoDB connection string (Default: mongodb://localhost/): mongo "mongodb+srv://cluster0.h75mayj.mongodb.net/myFirstDatabase" --username Kirushiraam
MongoshInvalidInputError: [COMMON-10001] Invalid URI: mongo "mongodb+srv://cluster0.h75mayj.mongodb.net/myFirstDatabase" --username Kirushiraam
Press any key to exit:

I'm expecting Mongo DB shell connect the Mongo DB Shell connection string to load the queries


问:
fetch all the saved binary data core data object names
In my swift code below the goal is fetch all of the object names of the 3 images saved and print them in the debug section of Xcode. I have a fetch method but I don't know how to get the specific object names printed in the debug section. There are 2 classes a base class and helper class. The helper class has the fetch method.</p>
```<code>import UIKit; import CoreData

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .orange
        let gwen = UIImage(named: "blank")
        let katy = UIImage(named: "g.jpg")
        let sarah = UIImage(named: "drg")

        if let imageData = gwen.self?.pngData() {
            CoredataHandler.shareInstance.saveImage(data: imageData)
        }

        if let imageData2 = katy.self?.pngData() {
            CoredataHandler.shareInstance.saveImage(data: imageData2)
        }

        if let imageData3 = gwen.self?.pngData() {
            CoredataHandler.shareInstance.saveImage(data: imageData3)
        }

        CoredataHandler.shareInstance.fetchImage()

    }

}

class CoredataHandler : NSManagedObject {
    static let shareInstance = CoredataHandler()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

private class func getContext() -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    return appDelegate.persistentContainer.viewContext
}
    func saveImage(data: Data) {
        let imageInstance = Information(context: context)

        imageInstance.pic = data

        do {
            try context.save()

        } catch {
            print(error.localizedDescription)
        }
    }

    func fetchImage() -> [Information] {

        var fetchingImage = [Information]()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Information")

        do {

            fetchingImage = try context.fetch(fetchRequest) as! [Information]
        } catch {
            print("Error while fetching the image")
        }

        return fetchingImage
    }
}
</code>```

Body:
In my swift code below the goal is fetch all of the object names of the 3 images saved and print them in the debug section of Xcode. I have a fetch method but I don't know how to get the specific object names printed in the debug section. There are 2 classes a base class and helper class. The helper class has the fetch method.

import UIKit; import CoreData

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .orange
        let gwen = UIImage(named: "blank")
        let katy = UIImage(named: "g.jpg")
        let sarah = UIImage(named: "drg")

        if let imageData = gwen.self?.pngData() {
            CoredataHandler.shareInstance.saveImage(data: imageData)
        }

        if let imageData2 = katy.self?.pngData() {
            CoredataHandler.shareInstance.saveImage(data: imageData2)
        }

        if let imageData3 = gwen.self?.pngData() {
            CoredataHandler.shareInstance.saveImage(data: imageData3)
        }

        CoredataHandler.shareInstance.fetchImage()

    }

}

class CoredataHandler : NSManagedObject {
    static let shareInstance = CoredataHandler()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

private class func getContext() -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    return appDelegate.persistentContainer.viewContext
}
    func saveImage(data: Data) {
        let imageInstance = Information(context: context)

        imageInstance.pic = data

        do {
            try context.save()

        } catch {
            print(error.localizedDescription)
        }
    }

    func fetchImage() -> [Information] {

        var fetchingImage = [Information]()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Information")

        do {

            fetchingImage = try context.fetch(fetchRequest) as! [Information]
        } catch {
            print("Error while fetching the image")
        }

        return fetchingImage
    }
}


问:
how can i use online subsystem facebook plugin of unreal 4?
I attempted to use Playfab for Facebook login authentication, but it worked just as well if I manually entered the test user's access token from the Facebook developer.
Is it possible to integrate the OnlineSubsystem Facebook plugin?</p>


问:
Disable autoComplete in angular - solution
The use of the autocomplete attribute to turn off autocomplete still case some issues across browser such as Chrome & Firefox.

There is a solution to deal with that:

```<code><input #input type="text" name="name" (focus)="onFocusChange()">
</code>```

Handle autocomple using reaonly attirbute on focus state

```<code>export class CustomInput {

@Input() isAutocomplete = true; <--- default autocomplete
@ViewChild('input', { static: true }) input: ElementRef<HTMLInputElement>;

  ngOnInit() {
    // make it as reaonly if isAutocomplete = false so it won't auto fill the input
    if (!this.isAutocomplete) this.input.nativeElement.readOnly = true;
  }

  onFocusChange() {
    // turn off readonly on user focus
    if (!this.isAutocomplete) this.input.nativeElement.readOnly = false;
   }

}
</code>```

Body:
The use of the autocomplete attribute to turn off autocomplete still case some issues across browser such as Chrome & Firefox.

There is a solution to deal with that:

<input #input type="text" name="name" (focus)="onFocusChange()">

Handle autocomple using reaonly attirbute on focus state

export class CustomInput {

@Input() isAutocomplete = true; <--- default autocomplete
@ViewChild('input', { static: true }) input: ElementRef<HTMLInputElement>;

  ngOnInit() {
    // make it as reaonly if isAutocomplete = false so it won't auto fill the input
    if (!this.isAutocomplete) this.input.nativeElement.readOnly = true;
  }

  onFocusChange() {
    // turn off readonly on user focus
    if (!this.isAutocomplete) this.input.nativeElement.readOnly = false;
   }

}


问:
My webview application is not showing notification popup
```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="io.gonative.android"
    android:versionName="1.0.0" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"/>
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

    <!-- WebRTC Audio and Video -->
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <!--<uses-permission android:name="android.permission.BLUETOOTH" />-->
    <!--<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />-->

    <!-- permissions for push messages -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="${applicationId}.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />

    <!-- permissions to block phone calls -->
    <!--<uses-permission android:name="android.permission.READ_CONTACTS" />-->
    <!--<uses-permission android:name="android.permission.READ_CALL_LOG" />-->
    <!--<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />-->

    <application
        android:name=".GoNativeApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:logo="@drawable/ic_actionbar"
        android:theme="@style/GoNativeTheme.NoActionBar"
        android:supportsRtl="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:requestLegacyExternalStorage="true">

        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="${admob_app_id}"/>

        <activity
            android:name="io.gonative.android.MainActivity"
            android:label="@string/app_name"
            android:exported="true"
            android:configChanges="orientation|screenSize"
            tools:node="merge">
        </activity>

        <activity
            android:name=".AppLinksActivity"
            android:launchMode="singleTask"
            android:exported="true">
            <!--additional intent filters-->

            <!--example: -->
            <!--<intent-filter>-->
            <!--<action android:name="android.intent.action.VIEW"></action>-->
            <!--<category android:name="android.intent.category.DEFAULT"></category>-->
            <!--<category android:name="android.intent.category.BROWSABLE"></category>-->
            <!--<data android:scheme="http"></data>-->
            <!--<data android:scheme="https"></data>-->
            <!--<data android:host="gonative.io"></data>-->
            <!--<data android:pathPrefix="/"></data>-->
            <!--</intent-filter>-->
        </activity>

        <!-- For file sharing without having to use external permissions. -->
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>

        <activity
            android:name=".SplashActivity"
            android:exported="true"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_notification" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />
        <meta-data
            android:name="com.google.firebase.Refex channel"
            android:value="Refex channel" />

    </application>

</manifest>

</code>```

Hello all , I have developed an android webview application for my website , everything works fine and i have published my application in playstore but the issue is my application is still not receiving any notification , it does not show message notification when it is received , I want my application to show up the notification over the top of the display.

And also i have created a notification and have given all the the permission, Further I have integrated firebase to the application so that it can receive notification .

But the thing is , the notification popup is till not showing . What can I do for this ? what should I do more to receive and display notification over the top of the display ?

Can anyone please help me to resolve this issue

My Android application should have the notification popup over the display when the message is received

Even after giving "post notification" permission and integrating firebase messaging service , the application is not showing the notification popup.

Body:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="io.gonative.android"
    android:versionName="1.0.0" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"/>
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

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

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="${applicationId}.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />

    <application
        android:name=".GoNativeApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:logo="@drawable/ic_actionbar"
        android:theme="@style/GoNativeTheme.NoActionBar"
        android:supportsRtl="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:requestLegacyExternalStorage="true">

        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="${admob_app_id}"/>

        <activity
            android:name="io.gonative.android.MainActivity"
            android:label="@string/app_name"
            android:exported="true"
            android:configChanges="orientation|screenSize"
            tools:node="merge">
        </activity>

        <activity
            android:name=".AppLinksActivity"
            android:launchMode="singleTask"
            android:exported="true">

        </activity>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>

        <activity
            android:name=".SplashActivity"
            android:exported="true"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_notification" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />
        <meta-data
            android:name="com.google.firebase.Refex channel"
            android:value="Refex channel" />

    </application>

</manifest>

Hello all , I have developed an android webview application for my website , everything works fine and i have published my application in playstore but the issue is my application is still not receiving any notification , it does not show message notification when it is received , I want my application to show up the notification over the top of the display.

And also i have created a notification and have given all the the permission, Further I have integrated firebase to the application so that it can receive notification .

But the thing is , the notification popup is till not showing . What can I do for this ? what should I do more to receive and display notification over the top of the display ?

Can anyone please help me to resolve this issue

My Android application should have the notification popup over the display when the message is received

Even after giving "post notification" permission and integrating firebase messaging service , the application is not showing the notification popup.


问:
k8s setup on windows with minikube
PS C:\Users\docker> minikube start

minikube v1.28.0 on Microsoft Windows 10 Pro 10.0.19044 Build 19044

Using the hyperv driver based on existing profile

Starting control plane node minikube in cluster minikube
! StartHost failed, but will try again: error loading existing host. Please try running [minikube delete], then run [minikube start] again: filestore "minikube": open C:\Users\docker.minikube\machines\minikube\config.json: The system cannot find the file specified.

Failed to start hyperv VM. Running "minikube delete" may fix it: error loading existing host. Please try running [minikube delete], then run [minikube start] again: filestore "minikube": open C:\Users\docker.minikube\machines\minikube\config.json: The system cannot find the file specified.

X Exiting due to GUEST_NOT_FOUND: Failed to start host: error loading existing host. Please try running [minikube delete], then run [minikube start] again: filestore "minikube": open C:\Users\docker.minikube\machines\minikube\config.json: The system cannot find the file specified.

Suggestion: minikube is missing files relating to your guest environment. This can be fixed by running 'minikube delete'

Related issue: https://github.com/kubernetes/minikube/issues/9130

PS C:\Users\docker> minikube start

minikube v1.28.0 on Microsoft Windows 10 Pro 10.0.19044 Build 19044

Using the hyperv driver based on existing profile

Starting control plane node minikube in cluster minikube
! StartHost failed, but will try again: error loading existing host. Please try running [minikube delete], then run [minikube start] again: filestore "minikube": open C:\Users\docker.minikube\machines\minikube\config.json: The system cannot find the file specified.

Failed to start hyperv VM. Running "minikube delete" may fix it: error loading existing host. Please try running [minikube delete], then run [minikube start] again: filestore "minikube": open C:\Users\docker.minikube\machines\minikube\config.json: The system cannot find the file specified.

X Exiting due to GUEST_NOT_FOUND: Failed to start host: error loading existing host. Please try running [minikube delete], then run [minikube start] again: filestore "minikube": open C:\Users\docker.minikube\machines\minikube\config.json: The system cannot find the file specified.

Suggestion: minikube is missing files relating to your guest environment. This can be fixed by running 'minikube delete'

Related issue: https://github.com/kubernetes/minikube/issues/9130

PS C:\Users\docker> minikube start --driver=hyperv

minikube v1.28.0 on Microsoft Windows 10 Pro 10.0.19044 Build 19044

Using the hyperv driver based on existing profile

Starting control plane node minikube in cluster minikube
! StartHost failed, but will try again: error loading existing host. Please try running [minikube delete], then run [minikube start] again: filestore "minikube": open C:\Users\docker.minikube\machines\minikube\config.json: The system cannot find the file specified.

Failed to start hyperv VM. Running "minikube delete" may fix it: error loading existing host. Please try running [minikube delete], then run [minikube start] again: filestore "minikube": open C:\Users\docker.minikube\machines\minikube\config.json: The system cannot find the file specified.

X Exiting due to GUEST_NOT_FOUND: Failed to start host: error loading existing host. Please try running [minikube delete], then run [minikube start] again: filestore "minikube": open C:\Users\docker.minikube\machines\minikube\config.json: The system cannot find the file specified.

Suggestion: minikube is missing files relating to your guest environment. This can be fixed by running 'minikube delete'

Related issue: https://github.com/kubernetes/minikube/issues/9130

tried  [minikube delete], then run [minikube start] but still the same issue

Title: k8s setup on windows with minikube


问:
compress multiple images before upload javascript and php
```<code><input id="upload" type="file" accept=".jpg, .jpeg, .png, .webp" />

<script>
    var fileInput = document.querySelector("#upload");
var originalImage = document.querySelector("#originalImage");

var compressedImage = document.querySelector("#compressedImage");
var resizingElement = document.querySelector("#resizingRange");

var qualityElement = document.querySelector("#qualityRange");
var uploadButton = document.querySelector("#uploadButton");

var compressedImageBlob;

var resizingFactor = 0.8;
var quality = 0.5;

// initializing the compressed image
compressImage(originalImage, resizingFactor, quality);

fileInput.addEventListener("change", async (e) => {

  var [file] = fileInput.files;

  // storing the original image
  originalImage.src = await fileToDataUri(file);

  // compressing the uplodaded image
  originalImage.addEventListener("load", () => {
    compressImage(originalImage, resizingFactor, quality);
  });

  return false;
});

resizingElement.oninput = (e) => {
  resizingFactor = parseInt(e.target.value) / 100;
  compressImage(originalImage, resizingFactor, quality);
};

qualityElement.oninput = (e) => {
  quality = parseInt(e.target.value) / 100;
  compressImage(originalImage, resizingFactor, quality);
};

function compressImage(imgToCompress, resizingFactor, quality) {
  // showing the compressed image
  var canvas = document.createElement("canvas");
  var context = canvas.getContext("2d");

  var originalWidth = imgToCompress.width;
  var originalHeight = imgToCompress.height;
  var obtainedHeight = (originalHeight / originalWidth) * 420;

  var canvasWidth = originalWidth * (420/originalWidth);
  var canvasHeight = originalHeight * (obtainedHeight/originalHeight);

  canvas.width = canvasWidth;
  canvas.height = canvasHeight;

  context.drawImage(
    imgToCompress,
    0,
    0,
    originalWidth  * (420/originalWidth),
    originalHeight  * (obtainedHeight/originalHeight)
  );

  // reducing the quality of the image
  canvas.toBlob(
    (blob) => {
      if (blob) {
        compressedImageBlob = blob;
        compressedImage.src = URL.createObjectURL(compressedImageBlob);
        document.querySelector("#size").innerHTML = bytesToSize(blob.size);
        var reader = new FileReader();
        reader.readAsDataURL(compressedImageBlob);
        reader.onloadend = function() {
        var base64data = reader.result;
        document.querySelector("#image").value = base64data;
        }

      }
    },
    "image/jpeg",
    quality
  );
}

function fileToDataUri(field) {
  return new Promise((resolve) => {
    var reader = new FileReader();
    reader.addEventListener("load", () => {
      resolve(reader.result);
    });
    reader.readAsDataURL(field);
  });
}

// source: https://stackoverflow.com/a/18650828
function bytesToSize(bytes) {
  var sizes = ["Bytes", "KB", "MB", "GB", "TB"];

  if (bytes === 0) {
    return "0 Byte";
  }

  var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));

  return Math.round(bytes / Math.pow(1024, i), 2) + " " + sizes[i];
}

    </script>

</code>```

With the javascript functions above I am able to select a big image, compress the size on client-side and upload to the server. This works perfectly for a single image upload. I was wondering if it is possible to modify this code to convert all selected images in a multiple file upload scenario.

so instead of doing it for

<input id="upload" type="file" accept=".jpg, .jpeg, .png, .webp" />

it will be for

<input id="uploads" type="file" accept=".jpg, .jpeg, .png, .webp" multiple>

Body:
<input id="upload" type="file" accept=".jpg, .jpeg, .png, .webp" />

With the javascript functions above I am able to select a big image, compress the size on client-side and upload to the server. This works perfectly for a single image upload. I was wondering if it is possible to modify this code to convert all selected images in a multiple file upload scenario.

so instead of doing it for

<input id="upload" type="file" accept=".jpg, .jpeg, .png, .webp" />

it will be for

<input id="uploads" type="file" accept=".jpg, .jpeg, .png, .webp" multiple>


问:
How to build an api that triggers automatically like firebase?
I want to build an API [or a system] that fires automatically when there is some change in backend so that I dont need to call that API from front end, continuously , Instead I could just listen to the stream.
Something like firebase realtime db , when there is a change in some value it automatically triggers and I just have to listen to the stream.
When I wanted same functionality for one my API  I had to call it periodically , say every second or 5 seconds to build any new changes [A very bad approach I think].
Some usecases are : Chats .

One approache I thought is , implementing triggers in database .
But I am not sure if thats the correct approach.


问:
Chrome extension v3 Service Worker; Uncaught TypeError: Cannot read properties of undefined (reading 'register')
I am writing a chrome extension v3. In my background.js, I keep getting the Uncaught TypeError: Cannot read properties of undefined (reading 'register')

Here is the code

```<code>// background.js
// Check if the service worker API is supported
if ("serviceWorker" in navigator) {
  // Register the service worker
  navigator.serviceWorker.register("background.js")
    .then(function(registration) {
      console.log("Service worker registered:", registration);
    })
    .catch(function(error) {
      console.error("Error registering service worker:", error);
    });
}

// Handle the message event
self.addEventListener("message", (event) => {
  var request = event.data;
  if (request.type === "search") {
    // Perform the searches and send the results back to the content script
    var title = request.title;
    var title2 = title.replace(/ /g, "+"); // Replace spaces with +
    var results = [];
    var queries = [
      `https://www.ncbi.nlm.nih.gov/pmc/?term=${title}`,
      `https://www.biorxiv.org/search/${title}`,
      `https://www.medrxiv.org/search/${title}`,
      `https://www.google.com/search?q=${title2}+filetype:pdf`
    ];
    queries.forEach(function (query) {
      fetch(query)
        .then(function (response) {
          return response.text();
        })
        .then(function (html) {
          // Extract the relevant information from the HTML using cheerio or regular expressions
          var $ = cheerio.load(html);
          // ...
          results.push( /* Extract the relevant information */);
        });
    });

    // Send the results back to the content script
    event.ports[0].postMessage({ results: results });
  }
});
</code>```

The error persists even when I delete the check section, i.e., the section that says // Check if the service worker API is supported
Any clues?

Body:
I am writing a chrome extension v3. In my background.js, I keep getting the Uncaught TypeError: Cannot read properties of undefined (reading 'register')

Here is the code

// background.js
// Check if the service worker API is supported
if ("serviceWorker" in navigator) {
  // Register the service worker
  navigator.serviceWorker.register("background.js")
    .then(function(registration) {
      console.log("Service worker registered:", registration);
    })
    .catch(function(error) {
      console.error("Error registering service worker:", error);
    });
}

// Handle the message event
self.addEventListener("message", (event) => {
  var request = event.data;
  if (request.type === "search") {
    // Perform the searches and send the results back to the content script
    var title = request.title;
    var title2 = title.replace(/ /g, "+"); // Replace spaces with +
    var results = [];
    var queries = [
      `https://www.ncbi.nlm.nih.gov/pmc/?term=${title}`,
      `https://www.biorxiv.org/search/${title}`,
      `https://www.medrxiv.org/search/${title}`,
      `https://www.google.com/search?q=${title2}+filetype:pdf`
    ];
    queries.forEach(function (query) {
      fetch(query)
        .then(function (response) {
          return response.text();
        })
        .then(function (html) {
          // Extract the relevant information from the HTML using cheerio or regular expressions
          var $ = cheerio.load(html);
          // ...
          results.push( /* Extract the relevant information */);
        });
    });

    // Send the results back to the content script
    event.ports[0].postMessage({ results: results });
  }
});

The error persists even when I delete the check section, i.e., the section that says // Check if the service worker API is supported
Any clues?


问:
How to optimise code to read a large CSV file in C++?
I am trying to read entries of my csv file into an entries vector whose data type is object OrderBookEntry, this is an object that stores the tokenized variables from the csv line which itself is converted through the function tokenise. My problem is that my csv file has around a million lines and it takes over 30 seconds to load, how can I reduce this?

This is my code that actually reads lines from the file and converts them into entries.

```<code>
    std::vector<OrderBookEntry> CSVReader::readCSV(std::string csvFilename)
    {
        std::vector<OrderBookEntry> entries;

        std::ifstream csvFile{csvFilename};

        std::string line;
        if (csvFile.is_open())
        {
            while(std::getline(csvFile, line))
            {
                try {
                    OrderBookEntry obe = stringsToOBE(tokenise(line, ','));
                    entries.push_back(obe);
                    //std::cout << "pushing entry" << std::endl;
                }catch(const std::exception& e)
                {
                    //std::cout << "CSVReader::readCSV bad data"  << std::endl;
                }
            }// end of while
        }

        std::cout << "CSVReader::readCSV read " << entries.size() << " entries"  <<
        std::endl;
        return entries;
    }
</code>```

This is the part of my code that tokenises the read line

```<code>
    std::vector<std::string> CSVReader::tokenise(std::string csvLine, char separator)
    {
       std::vector<std::string> tokens;
       signed int start, end;
       std::string token;
        start = csvLine.find_first_not_of(separator, 0);
        do{
            end = csvLine.find_first_of(separator, start);
            if (start == csvLine.length() || start == end) break;
            if (end >= 0) token = csvLine.substr(start, end - start);
            else token = csvLine.substr(start, csvLine.length() - start);
            tokens.push_back(token);
        start = end + 1;
        }while(end > 0);

       return tokens;
    }

</code>```

This is the part of my code that converts the tokens into a suitable object to work with

```<code>
    OrderBookEntry CSVReader::stringsToOBE(std::vector<std::string> tokens)
    {
        double price, amount;

        if (tokens.size() != 5) // bad
        {
            //std::cout << "Bad line " << std::endl;
            throw std::exception{};
        }
        // we have 5 tokens
        try {
             price = std::stod(tokens[3]);
             amount = std::stod(tokens[4]);
        }catch(const std::exception& e){
            std::cout << "Bad float! " << tokens[3]<< std::endl;
            std::cout << "Bad float! " << tokens[4]<< std::endl;
            throw;
        }

        OrderBookEntry obe{price,
                            amount,
                            tokens[0],
                            tokens[1],
                            OrderBookEntry::stringToOrderBookType(tokens[2])};

        return obe;
    }
</code>```

Body:
I am trying to read entries of my csv file into an entries vector whose data type is object OrderBookEntry, this is an object that stores the tokenized variables from the csv line which itself is converted through the function tokenise. My problem is that my csv file has around a million lines and it takes over 30 seconds to load, how can I reduce this?

This is my code that actually reads lines from the file and converts them into entries.

    std::vector<OrderBookEntry> CSVReader::readCSV(std::string csvFilename)
    {
        std::vector<OrderBookEntry> entries;

        std::ifstream csvFile{csvFilename};

        std::string line;
        if (csvFile.is_open())
        {
            while(std::getline(csvFile, line))
            {
                try {
                    OrderBookEntry obe = stringsToOBE(tokenise(line, ','));
                    entries.push_back(obe);
                    //std::cout << "pushing entry" << std::endl;
                }catch(const std::exception& e)
                {
                    //std::cout << "CSVReader::readCSV bad data"  << std::endl;
                }
            }// end of while
        }

        std::cout << "CSVReader::readCSV read " << entries.size() << " entries"  <<
        std::endl;
        return entries;
    }

This is the part of my code that tokenises the read line

    std::vector<std::string> CSVReader::tokenise(std::string csvLine, char separator)
    {
       std::vector<std::string> tokens;
       signed int start, end;
       std::string token;
        start = csvLine.find_first_not_of(separator, 0);
        do{
            end = csvLine.find_first_of(separator, start);
            if (start == csvLine.length() || start == end) break;
            if (end >= 0) token = csvLine.substr(start, end - start);
            else token = csvLine.substr(start, csvLine.length() - start);
            tokens.push_back(token);
        start = end + 1;
        }while(end > 0);

       return tokens;
    }

This is the part of my code that converts the tokens into a suitable object to work with

    OrderBookEntry CSVReader::stringsToOBE(std::vector<std::string> tokens)
    {
        double price, amount;

        if (tokens.size() != 5) // bad
        {
            //std::cout << "Bad line " << std::endl;
            throw std::exception{};
        }
        // we have 5 tokens
        try {
             price = std::stod(tokens[3]);
             amount = std::stod(tokens[4]);
        }catch(const std::exception& e){
            std::cout << "Bad float! " << tokens[3]<< std::endl;
            std::cout << "Bad float! " << tokens[4]<< std::endl;
            throw;
        }

        OrderBookEntry obe{price,
                            amount,
                            tokens[0],
                            tokens[1],
                            OrderBookEntry::stringToOrderBookType(tokens[2])};

        return obe;
    }


问:
React yup typecript Argument of type 'DefaultTFuncReturn' is not assignable to parameter of type 'Message<{}>
I have this code snippet which worked correctly without any issue

```<code>const validationSchema = Yup.object().shape({
    name: Yup.string()
      .required(translate('validations.organization.name', 'Organization name is required.'))
      .max(
        30,
        translate('validations.organization.max', 'Maximum length for the organization name is 30.')
      )
      .min(
        2,
        translate('validations.organization.min', 'Minimum length for the organization name is 2.')
      ),
  });
</code>```

Then I upgrade my project's all packages to the latest npm package. Including react,react-dom, react-scripts linting, and typescript

After that, I get this error in a lot of places

Functions like max, min we can pass a string as a second argument. But error saying here is

Argument of type 'DefaultTFuncReturn' is not assignable to parameter
of type 'Message<{}> | undefined'.

That also makes sense, DefaultTFuncReturn is not equal to Message<{}>

I want to fix this error quickly since my goal is to check whether the package upgrade was successful or not. So how can I quickly fix this error globally without ts-ignore ignore every file?

Body:
I have this code snippet which worked correctly without any issue

const validationSchema = Yup.object().shape({
    name: Yup.string()
      .required(translate('validations.organization.name', 'Organization name is required.'))
      .max(
        30,
        translate('validations.organization.max', 'Maximum length for the organization name is 30.')
      )
      .min(
        2,
        translate('validations.organization.min', 'Minimum length for the organization name is 2.')
      ),
  });

Then I upgrade my project's all packages to the latest npm package. Including react,react-dom, react-scripts linting, and typescript

After that, I get this error in a lot of places

Functions like max, min we can pass a string as a second argument. But error saying here is

Argument of type 'DefaultTFuncReturn' is not assignable to parameter
of type 'Message<{}> | undefined'.

That also makes sense, DefaultTFuncReturn is not equal to Message<{}>

I want to fix this error quickly since my goal is to check whether the package upgrade was successful or not. So how can I quickly fix this error globally without ts-ignore ignore every file?


问:
@-moz-document url-prefix matches incorrect URLs in usercontent.css on Firefox Developer edition
I have the following rule in my usercontent.css, which is in the correct location.

@-moz-document url-prefix(https://discord.com/channels/357922255553953794/437055638376284161){
    .scrollerInner-2PPAp2{
        background-color: red!important;
    }
}
```

However, this seems to match all discord channels, not just the one in the URL.

So far, I've tried

using url instead of url-prefix, with the same result

adding " around the URL

How can I make Firefox only apply the rule within to the listed url-prefix? (or if that is not possible, the listed URL?)

Thanks in advance.

Body:
I have the following rule in my usercontent.css, which is in the correct location.

@-moz-document url-prefix(https://discord.com/channels/357922255553953794/437055638376284161){
    .scrollerInner-2PPAp2{
        background-color: red!important;
    }
}

However, this seems to match all discord channels, not just the one in the URL.

So far, I've tried

using url instead of url-prefix, with the same result

adding " around the URL

How can I make Firefox only apply the rule within to the listed url-prefix? (or if that is not possible, the listed URL?)

Thanks in advance.


问:
Is it possible that we can add dynamic borders to X axis labels and sub labels in chart.js?
I need to create dynamic borders to labels and sub labels of chart.js graph. Is there any way of achieving this scenario?.

Below is the output I am expecting.
Labels and sub labels are having borders

Has anyone been able to achieve this with the library?

Thanks in advance.

I have tried this code but unable to get borders to labels.

```<code>
var data = [{"omlPartgroupid":"191  ","xmonth":"10","xyear":"2015","QTY":"52"},{"omlPartgroupid":"191  ","xmonth":"11","xyear":"2015","QTY":"145"},{"omlPartgroupid":"191  ","xmonth":"12","xyear":"2015","QTY":"122"},{"omlPartgroupid":"191  ","xmonth":"1","xyear":"2016","QTY":"348"},{"omlPartgroupid":"191  ","xmonth":"2","xyear":"2016","QTY":"460"},{"omlPartgroupid":"191  ","xmonth":"3","xyear":"2016","QTY":"187"},{"omlPartgroupid":"191  ","xmonth":"4","xyear":"2016","QTY":"109"},{"omlPartgroupid":"191  ","xmonth":"5","xyear":"2016","QTY":"234"},{"omlPartgroupid":"191  ","xmonth":"6","xyear":"2016","QTY":"166"},{"omlPartgroupid":"191  ","xmonth":"7","xyear":"2016","QTY":"186"},{"omlPartgroupid":"191  ","xmonth":"8","xyear":"2016","QTY":"250"},{"omlPartgroupid":"191  ","xmonth":"9","xyear":"2016","QTY":"1077"},{"omlPartgroupid":"191  ","xmonth":"10","xyear":"2016","QTY":"594"},{"omlPartgroupid":"193  ","xmonth":"10","xyear":"2015","QTY":"39"},{"omlPartgroupid":"193  ","xmonth":"11","xyear":"2015","QTY":"183"},{"omlPartgroupid":"193  ","xmonth":"12","xyear":"2015","QTY":"136"},{"omlPartgroupid":"193  ","xmonth":"1","xyear":"2016","QTY":"212"},{"omlPartgroupid":"193  ","xmonth":"2","xyear":"2016","QTY":"460"},{"omlPartgroupid":"193  ","xmonth":"3","xyear":"2016","QTY":"176"},{"omlPartgroupid":"193  ","xmonth":"4","xyear":"2016","QTY":"187"},{"omlPartgroupid":"193  ","xmonth":"5","xyear":"2016","QTY":"174"},{"omlPartgroupid":"193  ","xmonth":"6","xyear":"2016","QTY":"151"},{"omlPartgroupid":"193  ","xmonth":"7","xyear":"2016","QTY":"164"},{"omlPartgroupid":"193  ","xmonth":"8","xyear":"2016","QTY":"237"},{"omlPartgroupid":"193  ","xmonth":"9","xyear":"2016","QTY":"798"},{"omlPartgroupid":"193  ","xmonth":"10","xyear":"2016","QTY":"662"},{"omlPartgroupid":"195  ","xmonth":"10","xyear":"2015","QTY":"9"},{"omlPartgroupid":"195  ","xmonth":"11","xyear":"2015","QTY":"38"},{"omlPartgroupid":"195  ","xmonth":"12","xyear":"2015","QTY":"35"},{"omlPartgroupid":"195  ","xmonth":"1","xyear":"2016","QTY":"68"},{"omlPartgroupid":"195  ","xmonth":"2","xyear":"2016","QTY":"161"},{"omlPartgroupid":"195  ","xmonth":"3","xyear":"2016","QTY":"73"},{"omlPartgroupid":"195  ","xmonth":"4","xyear":"2016","QTY":"69"},{"omlPartgroupid":"195  ","xmonth":"5","xyear":"2016","QTY":"56"},{"omlPartgroupid":"195  ","xmonth":"6","xyear":"2016","QTY":"55"},{"omlPartgroupid":"195  ","xmonth":"7","xyear":"2016","QTY":"50"},{"omlPartgroupid":"195  ","xmonth":"8","xyear":"2016","QTY":"114"},{"omlPartgroupid":"195  ","xmonth":"9","xyear":"2016","QTY":"1046"},{"omlPartgroupid":"195  ","xmonth":"10","xyear":"2016","QTY":"883"},{"omlPartgroupid":"197  ","xmonth":"10","xyear":"2015","QTY":"34"},{"omlPartgroupid":"197  ","xmonth":"11","xyear":"2015","QTY":"76"},{"omlPartgroupid":"197  ","xmonth":"12","xyear":"2015","QTY":"114"},{"omlPartgroupid":"197  ","xmonth":"1","xyear":"2016","QTY":"173"},{"omlPartgroupid":"197  ","xmonth":"2","xyear":"2016","QTY":"327"},{"omlPartgroupid":"197  ","xmonth":"3","xyear":"2016","QTY":"134"},{"omlPartgroupid":"197  ","xmonth":"4","xyear":"2016","QTY":"125"},{"omlPartgroupid":"197  ","xmonth":"5","xyear":"2016","QTY":"200"},{"omlPartgroupid":"197  ","xmonth":"6","xyear":"2016","QTY":"104"},{"omlPartgroupid":"197  ","xmonth":"7","xyear":"2016","QTY":"99"},{"omlPartgroupid":"197  ","xmonth":"8","xyear":"2016","QTY":"191"},{"omlPartgroupid":"197  ","xmonth":"9","xyear":"2016","QTY":"845"},{"omlPartgroupid":"197  ","xmonth":"10","xyear":"2016","QTY":"578"},{"omlPartgroupid":"199  ","xmonth":"10","xyear":"2015","QTY":"35"},{"omlPartgroupid":"199  ","xmonth":"11","xyear":"2015","QTY":"75"},{"omlPartgroupid":"199  ","xmonth":"12","xyear":"2015","QTY":"76"},{"omlPartgroupid":"199  ","xmonth":"1","xyear":"2016","QTY":"105"},{"omlPartgroupid":"199  ","xmonth":"2","xyear":"2016","QTY":"229"},{"omlPartgroupid":"199  ","xmonth":"3","xyear":"2016","QTY":"147"},{"omlPartgroupid":"199  ","xmonth":"4","xyear":"2016","QTY":"73"},{"omlPartgroupid":"199  ","xmonth":"5","xyear":"2016","QTY":"50"},{"omlPartgroupid":"199  ","xmonth":"6","xyear":"2016","QTY":"58"},{"omlPartgroupid":"199  ","xmonth":"7","xyear":"2016","QTY":"103"},{"omlPartgroupid":"199  ","xmonth":"8","xyear":"2016","QTY":"4230"},{"omlPartgroupid":"199  ","xmonth":"9","xyear":"2016","QTY":"2570"},{"omlPartgroupid":"199  ","xmonth":"10","xyear":"2016","QTY":"730"}];

        var omlPartgroupid =[];
        var xyear =[];
        var xmonth =[];
        var QTY=[];
        var labelData = [];

        for(var i in data){
            omlPartgroupid.push("PartGroup"+ data[i].omlPartgroupid);
            xyear.push(data[i].xyear);
            xmonth.push(data[i].xmonth);
            QTY.push(data[i].QTY);
            labelData.push(data[i].xmonth + "|" + data[i].xyear + "|" + data[i].omlPartgroupid);

        }

       var chartdata ={
           labels:labelData,
           datasets :[
            {
           backgroundColor: 'rgba(200,200,200,0.75)',
           borderColor: 'rgba(200,200,200,0.75)',

           hoverBackground: 'rgba(200,200,200,1)',
           hoverBorderColor:  'rgba(200,200,200,1)',
           xAxisID:'time',
           data:QTY
            }
               ]
       };

        var ctx=$("#mycanvas");
        var barGraph =new Chart(ctx,{
            type: 'bar',
            data: chartdata,
            options: {
                scales: {
                    xAxes:[ {
                        id: 'time',
                        type: 'category',
                        ticks: {
                            callback: function(label) {
                                var labelArray = label.split("|");
                                return  labelArray[0] + "/" + labelArray[1];
                            }
                        }
                    },
                    {
                        id: 'partGroup',
                        type: 'category',
                        gridLines: {
                            drawOnChartArea: false, // only want the grid lines for one axis to show up
                        },
                        ticks: {
            display:true,
                            callback: function(label) {
                                var labelArray = label.split("|");
                                return labelArray[0] === "10" && labelArray[1] == "2015" ?      labelArray[2] : "";
                            }
                        }

                    }

                     ]
                }
            }

       });

</code>```
```<code><canvas id="mycanvas">
</code>```

Body:
I need to create dynamic borders to labels and sub labels of chart.js graph. Is there any way of achieving this scenario?.

Below is the output I am expecting.
Labels and sub labels are having borders

Has anyone been able to achieve this with the library?

Thanks in advance.

I have tried this code but unable to get borders to labels.

var data = [{"omlPartgroupid":"191  ","xmonth":"10","xyear":"2015","QTY":"52"},{"omlPartgroupid":"191  ","xmonth":"11","xyear":"2015","QTY":"145"},{"omlPartgroupid":"191  ","xmonth":"12","xyear":"2015","QTY":"122"},{"omlPartgroupid":"191  ","xmonth":"1","xyear":"2016","QTY":"348"},{"omlPartgroupid":"191  ","xmonth":"2","xyear":"2016","QTY":"460"},{"omlPartgroupid":"191  ","xmonth":"3","xyear":"2016","QTY":"187"},{"omlPartgroupid":"191  ","xmonth":"4","xyear":"2016","QTY":"109"},{"omlPartgroupid":"191  ","xmonth":"5","xyear":"2016","QTY":"234"},{"omlPartgroupid":"191  ","xmonth":"6","xyear":"2016","QTY":"166"},{"omlPartgroupid":"191  ","xmonth":"7","xyear":"2016","QTY":"186"},{"omlPartgroupid":"191  ","xmonth":"8","xyear":"2016","QTY":"250"},{"omlPartgroupid":"191  ","xmonth":"9","xyear":"2016","QTY":"1077"},{"omlPartgroupid":"191  ","xmonth":"10","xyear":"2016","QTY":"594"},{"omlPartgroupid":"193  ","xmonth":"10","xyear":"2015","QTY":"39"},{"omlPartgroupid":"193  ","xmonth":"11","xyear":"2015","QTY":"183"},{"omlPartgroupid":"193  ","xmonth":"12","xyear":"2015","QTY":"136"},{"omlPartgroupid":"193  ","xmonth":"1","xyear":"2016","QTY":"212"},{"omlPartgroupid":"193  ","xmonth":"2","xyear":"2016","QTY":"460"},{"omlPartgroupid":"193  ","xmonth":"3","xyear":"2016","QTY":"176"},{"omlPartgroupid":"193  ","xmonth":"4","xyear":"2016","QTY":"187"},{"omlPartgroupid":"193  ","xmonth":"5","xyear":"2016","QTY":"174"},{"omlPartgroupid":"193  ","xmonth":"6","xyear":"2016","QTY":"151"},{"omlPartgroupid":"193  ","xmonth":"7","xyear":"2016","QTY":"164"},{"omlPartgroupid":"193  ","xmonth":"8","xyear":"2016","QTY":"237"},{"omlPartgroupid":"193  ","xmonth":"9","xyear":"2016","QTY":"798"},{"omlPartgroupid":"193  ","xmonth":"10","xyear":"2016","QTY":"662"},{"omlPartgroupid":"195  ","xmonth":"10","xyear":"2015","QTY":"9"},{"omlPartgroupid":"195  ","xmonth":"11","xyear":"2015","QTY":"38"},{"omlPartgroupid":"195  ","xmonth":"12","xyear":"2015","QTY":"35"},{"omlPartgroupid":"195  ","xmonth":"1","xyear":"2016","QTY":"68"},{"omlPartgroupid":"195  ","xmonth":"2","xyear":"2016","QTY":"161"},{"omlPartgroupid":"195  ","xmonth":"3","xyear":"2016","QTY":"73"},{"omlPartgroupid":"195  ","xmonth":"4","xyear":"2016","QTY":"69"},{"omlPartgroupid":"195  ","xmonth":"5","xyear":"2016","QTY":"56"},{"omlPartgroupid":"195  ","xmonth":"6","xyear":"2016","QTY":"55"},{"omlPartgroupid":"195  ","xmonth":"7","xyear":"2016","QTY":"50"},{"omlPartgroupid":"195  ","xmonth":"8","xyear":"2016","QTY":"114"},{"omlPartgroupid":"195  ","xmonth":"9","xyear":"2016","QTY":"1046"},{"omlPartgroupid":"195  ","xmonth":"10","xyear":"2016","QTY":"883"},{"omlPartgroupid":"197  ","xmonth":"10","xyear":"2015","QTY":"34"},{"omlPartgroupid":"197  ","xmonth":"11","xyear":"2015","QTY":"76"},{"omlPartgroupid":"197  ","xmonth":"12","xyear":"2015","QTY":"114"},{"omlPartgroupid":"197  ","xmonth":"1","xyear":"2016","QTY":"173"},{"omlPartgroupid":"197  ","xmonth":"2","xyear":"2016","QTY":"327"},{"omlPartgroupid":"197  ","xmonth":"3","xyear":"2016","QTY":"134"},{"omlPartgroupid":"197  ","xmonth":"4","xyear":"2016","QTY":"125"},{"omlPartgroupid":"197  ","xmonth":"5","xyear":"2016","QTY":"200"},{"omlPartgroupid":"197  ","xmonth":"6","xyear":"2016","QTY":"104"},{"omlPartgroupid":"197  ","xmonth":"7","xyear":"2016","QTY":"99"},{"omlPartgroupid":"197  ","xmonth":"8","xyear":"2016","QTY":"191"},{"omlPartgroupid":"197  ","xmonth":"9","xyear":"2016","QTY":"845"},{"omlPartgroupid":"197  ","xmonth":"10","xyear":"2016","QTY":"578"},{"omlPartgroupid":"199  ","xmonth":"10","xyear":"2015","QTY":"35"},{"omlPartgroupid":"199  ","xmonth":"11","xyear":"2015","QTY":"75"},{"omlPartgroupid":"199  ","xmonth":"12","xyear":"2015","QTY":"76"},{"omlPartgroupid":"199  ","xmonth":"1","xyear":"2016","QTY":"105"},{"omlPartgroupid":"199  ","xmonth":"2","xyear":"2016","QTY":"229"},{"omlPartgroupid":"199  ","xmonth":"3","xyear":"2016","QTY":"147"},{"omlPartgroupid":"199  ","xmonth":"4","xyear":"2016","QTY":"73"},{"omlPartgroupid":"199  ","xmonth":"5","xyear":"2016","QTY":"50"},{"omlPartgroupid":"199  ","xmonth":"6","xyear":"2016","QTY":"58"},{"omlPartgroupid":"199  ","xmonth":"7","xyear":"2016","QTY":"103"},{"omlPartgroupid":"199  ","xmonth":"8","xyear":"2016","QTY":"4230"},{"omlPartgroupid":"199  ","xmonth":"9","xyear":"2016","QTY":"2570"},{"omlPartgroupid":"199  ","xmonth":"10","xyear":"2016","QTY":"730"}];

        var omlPartgroupid =[];
        var xyear =[];
        var xmonth =[];
        var QTY=[];
        var labelData = [];

        for(var i in data){
            omlPartgroupid.push("PartGroup"+ data[i].omlPartgroupid);
            xyear.push(data[i].xyear);
            xmonth.push(data[i].xmonth);
            QTY.push(data[i].QTY);
            labelData.push(data[i].xmonth + "|" + data[i].xyear + "|" + data[i].omlPartgroupid);

        }

       var chartdata ={
           labels:labelData,
           datasets :[
            {
           backgroundColor: 'rgba(200,200,200,0.75)',
           borderColor: 'rgba(200,200,200,0.75)',

           hoverBackground: 'rgba(200,200,200,1)',
           hoverBorderColor:  'rgba(200,200,200,1)',
           xAxisID:'time',
           data:QTY
            }
               ]
       };

        var ctx=$("#mycanvas");
        var barGraph =new Chart(ctx,{
            type: 'bar',
            data: chartdata,
            options: {
                scales: {
                    xAxes:[ {
                        id: 'time',
                        type: 'category',
                        ticks: {
                            callback: function(label) {
                                var labelArray = label.split("|");
                                return  labelArray[0] + "/" + labelArray[1];
                            }
                        }
                    },
                    {
                        id: 'partGroup',
                        type: 'category',
                        gridLines: {
                            drawOnChartArea: false, // only want the grid lines for one axis to show up
                        },
                        ticks: {
            display:true,
                            callback: function(label) {
                                var labelArray = label.split("|");
                                return labelArray[0] === "10" && labelArray[1] == "2015" ?      labelArray[2] : "";
                            }
                        }

                    }

                     ]
                }
            }

       });

<canvas id="mycanvas">


问:
Java dragging and dropping a JLabel on JFrame only when a mouse button is released
Java dragging and dropping a JLabel on JFrame only when a mouse button is released

This is a simulation of dragging and moving the icon of "My Computer" on a Windows 95 desktop. I have successfully worked out the code for dragging and moving the icon on a desktop, in this way:

A: upon clicking the icon, if either mouse button is held down and the mouse is moved, then the icon is relocated instantly to the position of the cursor.

but what I would like to achieve next is a little different: on a real Windows desktop dragging and dropping an Icon such as "My Computer" or "Recycle Bin" is:

B: upon clicking the icon, if the left mouse button is held down and the mouse is moved, a "shadow" of this icon appears along the trajectory of the cursor, but not relocated to the position of the cursor until the left mouse button is released.

C: upon clicking the icon, if the right mouse button is held down and the mouse is moved, a "shadow" of this icon appears along the trajectory of the cursor, but a popup menu containing "create shortcut" and "cancel" does not appear until the right mouse button is released.

I have achieved only A, but neither B nor C. I would like to know the code for achieving both B and C, but separately.

The following code snippet for achieving A can be safely considered as a "minimal reproducible example". I have tested it and can confirm that it is runnable (in Eclipse), on the condition that the image file is imported into the project folder.

```<code>import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class DragAndMoveMyComputer {
  public static void main(String[] args) {
    new DragAndMoveMyComputer();
  }
  Point myComputerPreviousPoint;
  DragAndMoveMyComputer() {
    JDesktopPane desktop = new JDesktopPane();
    Color teal = new Color(0, 130, 130);
    desktop.setBackground(teal);
    desktop.setLayout(null);
    JLabel myComputer = new JLabel(new ImageIcon("MyComputer.png"));
    myComputer.setBounds(2, 0, 102, 77);
    desktop.add(myComputer);
    Point myComputerStartPoint = new Point(0, 0);
    myComputer.addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        myComputerPreviousPoint = e.getPoint();
      }
    });
    myComputer.addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseDragged(MouseEvent e) {
        Point myComputerCurrentPoint = e.getPoint();
        myComputerStartPoint.translate((int)(myComputerCurrentPoint.getX() - myComputerPreviousPoint.getX()),
          (int)(myComputerCurrentPoint.getY() - myComputerPreviousPoint.getY()));
        myComputer.setBounds((int)(myComputerStartPoint.getX()), (int)(myComputerStartPoint.getY()), 102, 77);
        desktop.revalidate();
        desktop.repaint();
      }
    });
    JFrame mainFrame = new JFrame("Drag and Move My Computer");
    mainFrame.add(desktop);
    mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    mainFrame.setVisible(true);
  }
}
</code>```

An example output of this code snippet : enter image description here

Body:
Java dragging and dropping a JLabel on JFrame only when a mouse button is released

This is a simulation of dragging and moving the icon of "My Computer" on a Windows 95 desktop. I have successfully worked out the code for dragging and moving the icon on a desktop, in this way:

A: upon clicking the icon, if either mouse button is held down and the mouse is moved, then the icon is relocated instantly to the position of the cursor.

but what I would like to achieve next is a little different: on a real Windows desktop dragging and dropping an Icon such as "My Computer" or "Recycle Bin" is:

B: upon clicking the icon, if the left mouse button is held down and the mouse is moved, a "shadow" of this icon appears along the trajectory of the cursor, but not relocated to the position of the cursor until the left mouse button is released.

C: upon clicking the icon, if the right mouse button is held down and the mouse is moved, a "shadow" of this icon appears along the trajectory of the cursor, but a popup menu containing "create shortcut" and "cancel" does not appear until the right mouse button is released.

I have achieved only A, but neither B nor C. I would like to know the code for achieving both B and C, but separately.

The following code snippet for achieving A can be safely considered as a "minimal reproducible example". I have tested it and can confirm that it is runnable (in Eclipse), on the condition that the image file is imported into the project folder.

import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class DragAndMoveMyComputer {
  public static void main(String[] args) {
    new DragAndMoveMyComputer();
  }
  Point myComputerPreviousPoint;
  DragAndMoveMyComputer() {
    JDesktopPane desktop = new JDesktopPane();
    Color teal = new Color(0, 130, 130);
    desktop.setBackground(teal);
    desktop.setLayout(null);
    JLabel myComputer = new JLabel(new ImageIcon("MyComputer.png"));
    myComputer.setBounds(2, 0, 102, 77);
    desktop.add(myComputer);
    Point myComputerStartPoint = new Point(0, 0);
    myComputer.addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        myComputerPreviousPoint = e.getPoint();
      }
    });
    myComputer.addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseDragged(MouseEvent e) {
        Point myComputerCurrentPoint = e.getPoint();
        myComputerStartPoint.translate((int)(myComputerCurrentPoint.getX() - myComputerPreviousPoint.getX()),
          (int)(myComputerCurrentPoint.getY() - myComputerPreviousPoint.getY()));
        myComputer.setBounds((int)(myComputerStartPoint.getX()), (int)(myComputerStartPoint.getY()), 102, 77);
        desktop.revalidate();
        desktop.repaint();
      }
    });
    JFrame mainFrame = new JFrame("Drag and Move My Computer");
    mainFrame.add(desktop);
    mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    mainFrame.setVisible(true);
  }
}

An example output of this code snippet : enter image description here


问:
How can I define Model ViewSet for contact form that sends email in django-rest-framework?
I have a APIView for a contact that takes input data from user and send it to mail:

```<code>from django.core.mail import send_mail

class ContactView(APIView):
    serializer_class = ContactSerializer

    def post(self, request, *args, **kwargs):
        serializer_class = ContactSerializer(data = request.data)
        if serializer_class.is_valid():
            data = serializer_class.validated_data
            name = data.get('name')
            email = data.get('email')
            message = data.get('message')

            send_mail('Contact Form Mail from ' + name, message, email, ['bibekjoshi34@gmail.com'],)

            return Response({"success":"sent"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"failed"}, status=status.HTTP_400_BAD_REQUEST)
</code>```

urls.py

```<code>urlpatterns = [
    path('contactapi', views.ContactView.as_view()),
]
</code>```

Question:

How can I do it using DRF ModelViewset? This below code isn't working.

```<code>class CustomerContactViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = Contact.objects.all()
    http_method_names = ['post']

    serializer_class = ContactSerializer

    def post(self, request):
        serializer_class = ContactSerializer(data=request.data)
        if serializer_class.is_valid():
            data = serializer_class.validated_data
            full_name = data.get('full_name')
            email = data.get('email')
            phone_no = data.get('phone_no')
            message = data.get('message')

            send_mail('Mail From' + full_name, phone_no, message, email, ['bibekjoshi34@gmail.com'],)

            return Response({"success":"sent"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"failed"}, status=status.HTTP_400_BAD_REQUEST)
</code>```

What is the best way to make contact-form: that stores data in database as well as sends to the admin mail: --------> For Production Level?

Body:
I have a APIView for a contact that takes input data from user and send it to mail:

from django.core.mail import send_mail

class ContactView(APIView):
    serializer_class = ContactSerializer

    def post(self, request, *args, **kwargs):
        serializer_class = ContactSerializer(data = request.data)
        if serializer_class.is_valid():
            data = serializer_class.validated_data
            name = data.get('name')
            email = data.get('email')
            message = data.get('message')

            send_mail('Contact Form Mail from ' + name, message, email, ['bibekjoshi34@gmail.com'],)

            return Response({"success":"sent"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"failed"}, status=status.HTTP_400_BAD_REQUEST)

urls.py

urlpatterns = [
    path('contactapi', views.ContactView.as_view()),
]

Question:

How can I do it using DRF ModelViewset? This below code isn't working.

class CustomerContactViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = Contact.objects.all()
    http_method_names = ['post']

    serializer_class = ContactSerializer

    def post(self, request):
        serializer_class = ContactSerializer(data=request.data)
        if serializer_class.is_valid():
            data = serializer_class.validated_data
            full_name = data.get('full_name')
            email = data.get('email')
            phone_no = data.get('phone_no')
            message = data.get('message')

            send_mail('Mail From' + full_name, phone_no, message, email, ['bibekjoshi34@gmail.com'],)

            return Response({"success":"sent"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"failed"}, status=status.HTTP_400_BAD_REQUEST)

What is the best way to make contact-form: that stores data in database as well as sends to the admin mail: --------> For Production Level?


问:
how to pass the Integrity error django and DRF without stoping execution raising the error
I am byulding an API using django and DRF my code is this

models.py

```<code>class Company(models.Model):
    """Company object."""
    name_company = models.CharField(max_length=255)
    symbol = models.CharField(max_length=10, unique=True)
    cik = models.CharField(max_length=150, blank=True)
    sector = models.CharField(max_length=150, blank=True)
    industry_category = models.CharField(max_length=150, blank=True)
    company_url = models.TextField(blank=True)
    description = models.TextField(blank=True)

    def __str__(self):
        return self.name_company

</code>```

views.py

```<code>class CompanyViewSet(viewsets.ModelViewSet):
    """View for manage company APIs."""
    serializer_class = serializers.CompanyDetailSerializer
    queryset = Company.objects.all()
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        """Return the serializer class for request."""
        if self.action == 'list':
            return serializers.CompanySerializer

        return self.serializer_class

    def perform_create(self, serializer):
        """Create a new Company."""
        try:
            serializer.save()
        except IntegrityError:
            print('Symbol exists already.')
            pass

</code>```

serializers.py

```<code>class CompanySerializer(serializers.ModelSerializer):
    """Serializer for Company."""

    class Meta:
        model = Company
        fields = [
            'id', 'name_company', 'symbol', 'cik', 'sector',
            'industry_category', 'company_url',
        ]
        read_only_fields = ['id']

    def create(self, validated_data):
        try:
            instance, created = Company.objects.get_or_create(**validated_data)
            if created:
                return instance
        except IntegrityError:
            pass

class CompanyDetailSerializer(CompanySerializer):
    """Serializer for Company details."""

    class Meta(CompanySerializer.Meta):
        fields = CompanySerializer.Meta.fields + ['description']
</code>```

And right now i am doing unit tests using in this file.

test_company.py

```<code>def create_company(**params):
    """Create and return a sample company."""
    defaults = {
        'name_company': 'Apple',
        'symbol': 'AAPL',
        'cik': '0000320193',
        'sector': 'Technology',
        'industry_category': 'Consumer Electronics',
        'company_url': 'https://www.apple.com/',
        'description':'',
    }
    defaults.update(params)

    company = Company.objects.create(**defaults)
    return company

def test_retrieve_companies(self):
        """Test retrieving a list of Companies."""
        create_company()
        create_company()
        create_company(
            name_company='Tesla',
            symbol='TSLA',
        )

        res = self.client.get(COMPANIES_URL)

        companies = Company.objects.all().order_by('id')
        serializer = CompanySerializer(companies, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)
</code>```
```<code>I am getting IntegrityError, what i want is that the run time continue without stopping execution raising the error that is why i am testing it inserting APPLE twice.

I am trying to catch the error with this code in the views.py but does not catch it.

</code>```

def perform_create(self, serializer):
"""Create a new Company."""
try:
serializer.save()
except IntegrityError:
print('Symbol exists already.')
pass

```<code>my error is this:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "core_company_symbol_50a489f1_uniq"
DETAIL:  Key (symbol)=(AAPL) already exists.

Thank you in advance.

</code>```

Body:
I am byulding an API using django and DRF my code is this

models.py

class Company(models.Model):
    """Company object."""
    name_company = models.CharField(max_length=255)
    symbol = models.CharField(max_length=10, unique=True)
    cik = models.CharField(max_length=150, blank=True)
    sector = models.CharField(max_length=150, blank=True)
    industry_category = models.CharField(max_length=150, blank=True)
    company_url = models.TextField(blank=True)
    description = models.TextField(blank=True)

    def __str__(self):
        return self.name_company

views.py

class CompanyViewSet(viewsets.ModelViewSet):
    """View for manage company APIs."""
    serializer_class = serializers.CompanyDetailSerializer
    queryset = Company.objects.all()
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        """Return the serializer class for request."""
        if self.action == 'list':
            return serializers.CompanySerializer

        return self.serializer_class

    def perform_create(self, serializer):
        """Create a new Company."""
        try:
            serializer.save()
        except IntegrityError:
            print('Symbol exists already.')
            pass

serializers.py

class CompanySerializer(serializers.ModelSerializer):
    """Serializer for Company."""

    class Meta:
        model = Company
        fields = [
            'id', 'name_company', 'symbol', 'cik', 'sector',
            'industry_category', 'company_url',
        ]
        read_only_fields = ['id']

    def create(self, validated_data):
        try:
            instance, created = Company.objects.get_or_create(**validated_data)
            if created:
                return instance
        except IntegrityError:
            pass

class CompanyDetailSerializer(CompanySerializer):
    """Serializer for Company details."""

    class Meta(CompanySerializer.Meta):
        fields = CompanySerializer.Meta.fields + ['description']

And right now i am doing unit tests using in this file.

test_company.py

def create_company(**params):
    """Create and return a sample company."""
    defaults = {
        'name_company': 'Apple',
        'symbol': 'AAPL',
        'cik': '0000320193',
        'sector': 'Technology',
        'industry_category': 'Consumer Electronics',
        'company_url': 'https://www.apple.com/',
        'description':'',
    }
    defaults.update(params)

    company = Company.objects.create(**defaults)
    return company

def test_retrieve_companies(self):
        """Test retrieving a list of Companies."""
        create_company()
        create_company()
        create_company(
            name_company='Tesla',
            symbol='TSLA',
        )

        res = self.client.get(COMPANIES_URL)

        companies = Company.objects.all().order_by('id')
        serializer = CompanySerializer(companies, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)

I am getting IntegrityError, what i want is that the run time continue without stopping execution raising the error that is why i am testing it inserting APPLE twice.

I am trying to catch the error with this code in the views.py but does not catch it.

def perform_create(self, serializer):
"""Create a new Company."""
try:
serializer.save()
except IntegrityError:
print('Symbol exists already.')
pass

my error is this:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "core_company_symbol_50a489f1_uniq"
DETAIL:  Key (symbol)=(AAPL) already exists.

Thank you in advance.


问:
Typescript: Get error "CredentialsProviderError" when calling lambda.invoke recursivly
Things run OK when executing this code from another lambda fuction:

```<code>const payload = {
  FunctionName: 'fileLoaderCcAccountInfoHandler',
  LogType: 'Tail',
  Payload: fromUtf8(JSON.stringify(event)),
  InvocationType: 'Event',
};
const lambda = new Lambda({ region: 'us-east-1' });
try {
  const response = await lambda.invoke(payload);
  console.log(response);
} catch (e) {
  console.log(e);
}
</code>```

but when I call it recursibly from itself, I get this error:

"CredentialsProviderError: Could not load credentials from any providers"

Any idea what is going wrong and how to resolve this?

Thank you.

Body:
Things run OK when executing this code from another lambda fuction:

const payload = {
  FunctionName: 'fileLoaderCcAccountInfoHandler',
  LogType: 'Tail',
  Payload: fromUtf8(JSON.stringify(event)),
  InvocationType: 'Event',
};
const lambda = new Lambda({ region: 'us-east-1' });
try {
  const response = await lambda.invoke(payload);
  console.log(response);
} catch (e) {
  console.log(e);
}

but when I call it recursibly from itself, I get this error:

"CredentialsProviderError: Could not load credentials from any providers"

Any idea what is going wrong and how to resolve this?

Thank you.


问:
Electron forge installation and uninstallation with msi package
Thanks in advance.

I have created one electron application with msi Support using electron forge maker.

{
    "name": "@electron-forge/maker-wix",
    "config": {
        "name": "XYZ",
        "manufacturer": "XYZ",
        "appIconPath": "x.ico",
        "features":{
            "autoLaunch": true
        },
        "ui": {
            "chooseDirectory": true
        }
    }
}
```

Here is my wix configuration
Installation and desktop shortcut everything working fine. I am able to use the product.

I have 2 question with this regarding installation and uninstallation:

After installation app I not launched automatically. I have manually launch via desktop shortcut or via window search.

While installing the application i am getting below window[enter image description here]

(https://i.stack.imgur.com/A4kbl.png)

Is that default in electron forge maker or we can able to customize it. I want to launch the application after installation without user interaction and also I want to uninstall the application without restart or reboot machine?

Could anyone pls help on this?

I want to launch the application after installation without user interaction and also I want to uninstall the application without restart or reboot machine?

Body:
Thanks in advance.

I have created one electron application with msi Support using electron forge maker.

{
    "name": "@electron-forge/maker-wix",
    "config": {
        "name": "XYZ",
        "manufacturer": "XYZ",
        "appIconPath": "x.ico",
        "features":{
            "autoLaunch": true
        },
        "ui": {
            "chooseDirectory": true
        }
    }
}

Here is my wix configuration
Installation and desktop shortcut everything working fine. I am able to use the product.

I have 2 question with this regarding installation and uninstallation:

After installation app I not launched automatically. I have manually launch via desktop shortcut or via window search.

While installing the application i am getting below window[enter image description here]

(https://i.stack.imgur.com/A4kbl.png)

Is that default in electron forge maker or we can able to customize it. I want to launch the application after installation without user interaction and also I want to uninstall the application without restart or reboot machine?

Could anyone pls help on this?

I want to launch the application after installation without user interaction and also I want to uninstall the application without restart or reboot machine?


问:
How to solve django.db.utils.OperationalError: (1050, "Table '###' already exists") error when running tests in Django
I am working with django.test package in my project, and have implemented some testcases. I have a MySQL database, and have created a test database with no problem.

But now when I am running my tests it shows the below error.

```<code>Type 'yes' if you would like to try deleting the test database 'test_sepantadb', or 'no' to cancel: Creating test database for alias 'default'...
Got an error creating the test database: (1007, "Can't create database 'test_sepantadb'; database exists")
</code>```

And after I type yes to the console, it shows the below errors, and I don't know how to solve them.

```<code>Destroying old test database for alias 'default'...
Traceback (most recent call last):
  File "D:\ABDAL\SepantaEnv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute
    return self.cursor.execute(sql)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
    return self.cursor.execute(query, args)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\cursors.py", line 148, in execute
    result = self._query(query)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\cursors.py", line 310, in _query
    conn.query(q)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 548, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
    result.read()
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 1156, in read
    first_packet = self.connection._read_packet()
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
    packet.raise_for_error()
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
    err.raise_mysql_exception(self._data)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.OperationalError: (1050, "Table 'react_arimapredictedvalues' already exists")
</code>```

I have tried the solution which have been provided in this link. But it does not solve it for me.

I have also run the below command for the second time in my MySQL shell to check the privileges, but again nothing does not change.

```<code>mysql> GRANT ALL PRIVILEGES ON test_sepantadb.* TO 'sepanta'@'localhost';
Query OK, 0 rows affected (0.00 sec)
</code>```

I have also tried two other solutions. I have deleted the test databse from mysql shell with command prompt, and also change my test database name, but none of these two solutions solved my problem.

These are also the content of my django_migrations table in test_sepantadb database:

I will be grateful for any help or advice on how to solve this error.

Body:
I am working with django.test package in my project, and have implemented some testcases. I have a MySQL database, and have created a test database with no problem.

But now when I am running my tests it shows the below error.

Type 'yes' if you would like to try deleting the test database 'test_sepantadb', or 'no' to cancel: Creating test database for alias 'default'...
Got an error creating the test database: (1007, "Can't create database 'test_sepantadb'; database exists")

And after I type yes to the console, it shows the below errors, and I don't know how to solve them.

Destroying old test database for alias 'default'...
Traceback (most recent call last):
  File "D:\ABDAL\SepantaEnv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute
    return self.cursor.execute(sql)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
    return self.cursor.execute(query, args)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\cursors.py", line 148, in execute
    result = self._query(query)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\cursors.py", line 310, in _query
    conn.query(q)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 548, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
    result.read()
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 1156, in read
    first_packet = self.connection._read_packet()
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
    packet.raise_for_error()
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
    err.raise_mysql_exception(self._data)
  File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.OperationalError: (1050, "Table 'react_arimapredictedvalues' already exists")

I have tried the solution which have been provided in this link. But it does not solve it for me.

I have also run the below command for the second time in my MySQL shell to check the privileges, but again nothing does not change.

mysql> GRANT ALL PRIVILEGES ON test_sepantadb.* TO 'sepanta'@'localhost';
Query OK, 0 rows affected (0.00 sec)

I have also tried two other solutions. I have deleted the test databse from mysql shell with command prompt, and also change my test database name, but none of these two solutions solved my problem.

These are also the content of my django_migrations table in test_sepantadb database:

I will be grateful for any help or advice on how to solve this error.


问:
Return List<int> from reader.stream.listen with flutter_libserialport
I try to use flutter libserialport bull to implement Modbus RTU, however after calling the function it doesn't work.

List<int> receivedData = await readRegisters(0xFE, 0x0000, 0x001A);

print('Data: $receivedData');

When I call, nothing prints. However, it works if I use a private list and setState()!

```<code>await reader.stream.listen((data) {
    print('stream : $data');
    setState(() {
        response!.addAll(data);
    });
}).asFuture();
</code>```

Output:
enter image description here

But after await as I called, I do want it to return for the instance variable. how I can solve it

```<code>Future<List<int>> readRegisters(int slaveID, int startAddress, int numberOfRegisters) async {
  // construct the Modbus Read Holding Registers command
  List<int> data = [slaveID,
    0x03,
    startAddress >> 8,
    startAddress & 0xFF,
    numberOfRegisters >> 8,
    numberOfRegisters & 0xFF  ];
  int calculatedChecksum = calculateModbusChecksum(data);
  data.add(calculatedChecksum & 0xFF);
  data.add(calculatedChecksum >> 8);
  // write the command to the serial port
  port.write(command(data));
  SerialPortReader reader = SerialPortReader(port, timeout: 1000);
  List<int> response = [];
  int bytesReceived = 0;
  while (bytesReceived < numberOfRegisters) {
    await reader.stream.listen((receivedData) {
      print('received : $receivedData');
      if (receivedData.isNotEmpty) {
        response.addAll(receivedData);
        bytesReceived += receivedData.length;
      }
    }).asFuture(response) ;
  }
  return response;
}
</code>```

List<int> receivedData = await readRegisters(0xFE, 0x0000, 0x001A) as List<int>; Future.delayed(const Duration(seconds: 1),()=>  print('Data: $receivedData'));
but they not return anything

Body:
I try to use flutter libserialport bull to implement Modbus RTU, however after calling the function it doesn't work.

List<int> receivedData = await readRegisters(0xFE, 0x0000, 0x001A);

print('Data: $receivedData');

When I call, nothing prints. However, it works if I use a private list and setState()!

await reader.stream.listen((data) {
    print('stream : $data');
    setState(() {
        response!.addAll(data);
    });
}).asFuture();

Output:
enter image description here

But after await as I called, I do want it to return for the instance variable. how I can solve it

Future<List<int>> readRegisters(int slaveID, int startAddress, int numberOfRegisters) async {
  // construct the Modbus Read Holding Registers command
  List<int> data = [slaveID,
    0x03,
    startAddress >> 8,
    startAddress & 0xFF,
    numberOfRegisters >> 8,
    numberOfRegisters & 0xFF  ];
  int calculatedChecksum = calculateModbusChecksum(data);
  data.add(calculatedChecksum & 0xFF);
  data.add(calculatedChecksum >> 8);
  // write the command to the serial port
  port.write(command(data));
  SerialPortReader reader = SerialPortReader(port, timeout: 1000);
  List<int> response = [];
  int bytesReceived = 0;
  while (bytesReceived < numberOfRegisters) {
    await reader.stream.listen((receivedData) {
      print('received : $receivedData');
      if (receivedData.isNotEmpty) {
        response.addAll(receivedData);
        bytesReceived += receivedData.length;
      }
    }).asFuture(response) ;
  }
  return response;
}

List<int> receivedData = await readRegisters(0xFE, 0x0000, 0x001A) as List<int>; Future.delayed(const Duration(seconds: 1),()=>  print('Data: $receivedData'));
but they not return anything


问:
How to create running totals in CouchDB (like SQL window functions)
Edited the question for clarity:

Assume I have the following documents in CouchDB:

{
  "_id": "1",
  "date": 1672119898,
  "amount": 120,
  "owner": "user_1"
},
{
  "_id": "2",
  "date": 1672119897,
  "amount": 25,
  "owner": "user_1"
},
{
  "_id": "3",
  "date": 1672119895,
  "amount": 40,
  "owner": "user_2"
},
{
  "_id": "4",
  "date": 1672119899,
  "amount": 70,
  "owner": "user_1"
},
{
  "_id": "5",
  "date": 1672119891,
  "amount": 33,
  "owner": "user_1"
},
{
  "_id": "6",
  "date": 1672119893,
  "amount": 11,
  "owner": "user_2"
}
```
<p>And I'd like to create a view that returns the running total: ordered by ascending date, running total by owner.</p>
<p>Easy to do in SQL with window functions. But not sure how to achieve the same with CouchDB. I have no code to show.</p>
<p>Expected Output with running totals by owner, sorted by date descending:</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "_id": "4",
    "date": 1672119899,
    "amount": 70,
    "owner": "user_1",
    "totalAmount": 248 // 178 + 70
  },
  {
    "_id": "1",
    "date": 1672119898,
    "amount": 120,
    "owner": "user_1",
    "totalAmount": 178 // 120 + 58
  },
  {
    "_id": "2",
    "date": 1672119897,
    "amount": 25,
    "owner": "user_1",
    "totalAmount": 58 // 25 + 33
  },
  {
    "_id": "5",
    "date": 1672119891,
    "amount": 33,
    "owner": "user_1",
    "totalAmount": 33
  },
  {
    "_id": "3",
    "date": 1672119895,
    "amount": 40,
    "owner": "user_2",
    "totalAmount": 51 // 40 + 51
  },
  {
    "_id": "6",
    "date": 1672119893,
    "amount": 11,
    "owner": "user_2",
    "totalAmount": 11
  }
]
</code>```

Body:
Edited the question for clarity:

Assume I have the following documents in CouchDB:

{
  "_id": "1",
  "date": 1672119898,
  "amount": 120,
  "owner": "user_1"
},
{
  "_id": "2",
  "date": 1672119897,
  "amount": 25,
  "owner": "user_1"
},
{
  "_id": "3",
  "date": 1672119895,
  "amount": 40,
  "owner": "user_2"
},
{
  "_id": "4",
  "date": 1672119899,
  "amount": 70,
  "owner": "user_1"
},
{
  "_id": "5",
  "date": 1672119891,
  "amount": 33,
  "owner": "user_1"
},
{
  "_id": "6",
  "date": 1672119893,
  "amount": 11,
  "owner": "user_2"
}

And I'd like to create a view that returns the running total: ordered by ascending date, running total by owner.

Easy to do in SQL with window functions. But not sure how to achieve the same with CouchDB. I have no code to show.

Expected Output with running totals by owner, sorted by date descending:

[
  {
    "_id": "4",
    "date": 1672119899,
    "amount": 70,
    "owner": "user_1",
    "totalAmount": 248 // 178 + 70
  },
  {
    "_id": "1",
    "date": 1672119898,
    "amount": 120,
    "owner": "user_1",
    "totalAmount": 178 // 120 + 58
  },
  {
    "_id": "2",
    "date": 1672119897,
    "amount": 25,
    "owner": "user_1",
    "totalAmount": 58 // 25 + 33
  },
  {
    "_id": "5",
    "date": 1672119891,
    "amount": 33,
    "owner": "user_1",
    "totalAmount": 33
  },
  {
    "_id": "3",
    "date": 1672119895,
    "amount": 40,
    "owner": "user_2",
    "totalAmount": 51 // 40 + 51
  },
  {
    "_id": "6",
    "date": 1672119893,
    "amount": 11,
    "owner": "user_2",
    "totalAmount": 11
  }
]