问:
SSIS Check GUID Equals "00000000-0000-0000-0000-000000000000"
I am doing a check for new GUID '00000000-0000-0000-0000-000000000000' in a Conditional Split step, but the expression is not recognized.

```<code>[WorkOrder.msdyn_workorderid] == "00000000-0000-0000-0000-000000000000"
</code>```

The data types "DT_GUID" and "DT_WSTR" are incompatible for binary
operator "==". The operand types could not be implicitly cast into
compatible types for the operation. To perform this operation, one or
both operands need to be explicitly cast with a cast operator.

May I know how can a GUID be converted to string, or the right method to conduct this check? Thank you.

Body:
I am doing a check for new GUID '00000000-0000-0000-0000-000000000000' in a Conditional Split step, but the expression is not recognized.

[WorkOrder.msdyn_workorderid] == "00000000-0000-0000-0000-000000000000"

The data types "DT_GUID" and "DT_WSTR" are incompatible for binary
operator "==". The operand types could not be implicitly cast into
compatible types for the operation. To perform this operation, one or
both operands need to be explicitly cast with a cast operator.

May I know how can a GUID be converted to string, or the right method to conduct this check? Thank you.


来源: stackexchange

问:
How to resolve Argument of type 'X' is not assignable to parameter of type 'never' when manipulating an array in TypeScript?
I have this long list of types, which essentially boil down to the following:

All types have a like property set to an enum constant.

The Partial types have a children array property.

Each Partial accepts different types of items in the children array.

The Full types don't have a children property, they have other properties.

Given that, I am writing this simple function to replace a child item with another item, which should match the possible types in children for that object. Essentially just children.splice(children.indexOf(item), 1), but in TypeScript form:

```<code>export function replaceASTChild<
  A extends AST,
  X extends ASTPartialType<AST>,
  B extends ASTType<AST>,
>(input: APIInputType, a: A, x: X, b: B): void {
  // irrelevant, gets the input.scope.parent (1 parent up)
  const objectScope = api.assumeObjectScope(input, 1)
  // assert the object
  api.assertASTPartial(objectScope.data, a)
  const index = objectScope.data.children.indexOf(x)
  objectScope.data.children[index] = b
}
</code>```

How do I replace it properly and avoid the error in the title?

Here is a minimal example to demonstrate the errors I am facing.

```<code>type AInitialType = {
  children: Array<string>
}

type AFinalType = {
  foo: string
}

type BInitialType = {
  children: Array<number>
}

type BFinalType = {
  bar: number
}

type CInitialType = {
  children: Array<AInitialType | BInitialType | AFinalType | BFinalType>
}

type CFinalType = {
  items: Array<AFinalType | BFinalType>
}

type XInitialType = AInitialType | BInitialType
type XFinalType = AFinalType | BFinalType

export function replaceChild(container: XInitialType, item: string | number, replacement: XFinalType): void {
  const index = container.children.indexOf(item)
  container.children[index] = replacement
}

const elementInitial1: AInitialType = {
  children: ['hello world']
}
const container1: CInitialType = {
  children: [elementInitial1]
}

replaceChild(container1, elementInitial1, { foo: 'hello world' })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this long list of types, which essentially boil down to the following:

All types have a like property set to an enum constant.

The Partial types have a children array property.

Each Partial accepts different types of items in the children array.

The Full types don't have a children property, they have other properties.

Given that, I am writing this simple function to replace a child item with another item, which should match the possible types in children for that object. Essentially just children.splice(children.indexOf(item), 1), but in TypeScript form:

export function replaceASTChild<
  A extends AST,
  X extends ASTPartialType<AST>,
  B extends ASTType<AST>,
>(input: APIInputType, a: A, x: X, b: B): void {
  // irrelevant, gets the input.scope.parent (1 parent up)
  const objectScope = api.assumeObjectScope(input, 1)
  // assert the object
  api.assertASTPartial(objectScope.data, a)
  const index = objectScope.data.children.indexOf(x)
  objectScope.data.children[index] = b
}

How do I replace it properly and avoid the error in the title?

Here is a <a href="https://www.typescriptlang.org/play?#code/FAFwngDgpgBAggSQHYEsQoIYBsAqlYC8MA3sDDAMYAWKWAJgE5RIBc8DDGYAPAM4gMUSAOYA+YAF9gofPABiQ7HmgwipcgDMA9lrb9BIydPAqAQsjSZcstWUo16TVu048kAVwC2AIygNxUjJmCkhKNiR23hgMbB4+fkZBsADCFuhhKrbk1LSMzGxwHFzciKjp1ioAPjDmZVbKsNVwIRmNNS0VUAHGsskdDaoR5GhQnrwFRTzNip0w1ab9+N1JMAAaafXhpZatczUbrSuri5nyMwPzJ1DSUAAeEFoMIDAa7kgU6FpIMEwQWBgUKDJBx0AAUFC+IAwQj8bHWdVaABoYCNPHoBEJhHs4r4GMjfv9AZ5mCA4VcAJRsABuWhQdCGlC+-BRSDod0GEKQUJhDAAdDlHMxeUI2bcAPIaUGo8l2TncpB+fkgpwAbRFdwAuoMCQDRiTEpzmVAsHquQcsABGArmgZZey5JxsFUAcioxqwWhgAHdHvRnRqjIbnnLoQqGFaYKkEbM7QK8s4VcbTSBzRaA4EdYDgblwZDQ34Lcik8SzdHCyQXjo2K73Z6fQw-TAJOSgA" rel="nofollow noreferrer">minimal example to demonstrate the errors I am facing.

type AInitialType = {
  children: Array<string>
}

type AFinalType = {
  foo: string
}

type BInitialType = {
  children: Array<number>
}

type BFinalType = {
  bar: number
}

type CInitialType = {
  children: Array<AInitialType | BInitialType | AFinalType | BFinalType>
}

type CFinalType = {
  items: Array<AFinalType | BFinalType>
}

type XInitialType = AInitialType | BInitialType
type XFinalType = AFinalType | BFinalType

export function replaceChild(container: XInitialType, item: string | number, replacement: XFinalType): void {
  const index = container.children.indexOf(item)
  container.children[index] = replacement
}

const elementInitial1: AInitialType = {
  children: ['hello world']
}
const container1: CInitialType = {
  children: [elementInitial1]
}

replaceChild(container1, elementInitial1, { foo: 'hello world' })


问:
Unable to import powershell module remotley
I'm importing module remotely. module located in C:\Users\Ananth\Documents\WindowsPowerShell\Modules\MSOnline\. I am able to view the module remotely. while importing getting below error. if try to execute in powershell application module importing successfully in both bit versions.

```<code> Import-Module : Could not load file or assembly 'file:///C:\Users\CAC-Dev\Documents\WindowsPowerShell\Modules\MSOnline\
1.1.183.66\Microsoft.Online.Administration.Automation.PSModule.dll' or one of its dependencies. An attempt was made to
load a program with an incorrect format.
At line:1 char:1
+ Import-Module MSOnline
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Import-Module], BadImageFormatException
+ FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand

Could not load file or assembly 'file:///C:\Users\CAC-Dev\Documents\WindowsPowerShell\Modules\MSOnline\
1.1.183.66\Microsoft.Online.Administration.Automation.PSModule.dll'
</code>```

Body:
I'm importing module remotely. module located in C:\Users\Ananth\Documents\WindowsPowerShell\Modules\MSOnline\. I am able to view the module remotely. while importing getting below error. if try to execute in powershell application module importing successfully in both bit versions.

 Import-Module : Could not load file or assembly 'file:///C:\Users\CAC-Dev\Documents\WindowsPowerShell\Modules\MSOnline\
1.1.183.66\Microsoft.Online.Administration.Automation.PSModule.dll' or one of its dependencies. An attempt was made to
load a program with an incorrect format.
At line:1 char:1
+ Import-Module MSOnline
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Import-Module], BadImageFormatException
+ FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand

Could not load file or assembly 'file:///C:\Users\CAC-Dev\Documents\WindowsPowerShell\Modules\MSOnline\
1.1.183.66\Microsoft.Online.Administration.Automation.PSModule.dll'


问:
How to debug a TypeScript union type missing a property?
I have about 50 complex types (here are some), scattered over multiple files, and probably one or two of them are missing a children: Array<...> property (I forgot to add it probably on initial code write/refactor). How can I efficiently figure out what type is missing this property? Rather than having to intensely visibly look at each type definition with my own eyes to verify it exists (which is difficult and error prone). Is there a way to inspect all the generated type definitions and see what is missing the prop?

The error occurs because I have this essentially:

```<code>type MyType = My1Type | My2Type | ... | My50Type
</code>```

The error is something like MyType does not have children property. Which one though?

Body:
I have about 50 complex types (here are some), scattered over multiple files, and probably one or two of them are missing a children: Array<...> property (I forgot to add it probably on initial code write/refactor). How can I efficiently figure out what type is missing this property? Rather than having to intensely visibly look at each type definition with my own eyes to verify it exists (which is difficult and error prone). Is there a way to inspect all the generated type definitions and see what is missing the prop?

The error occurs because I have this essentially:

type MyType = My1Type | My2Type | ... | My50Type

The error is something like MyType does not have children property. Which one though?


问:
android.security.KeyStoreException: Incompatible digest in Kotlin
i want to get value hashed in kotlin with private key RSA, but i have error 'android.security.KeyStoreException: Incompatible digest'.

this my code

```<code>    fun generatePairKey() {
            val start: Calendar = GregorianCalendar()
            val end: Calendar = GregorianCalendar()
            end.add(Calendar.YEAR, 1)
            val kpg: KeyPairGenerator = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"
            )
            kpg.initialize(
                KeyGenParameterSpec.Builder(
                    KopraMobile().BIOMETRIC_ALIAS_KEY_PAIR,
                    KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT

                ).setKeySize(2048)
                    .setUserAuthenticationRequired(false)
                    .setDigests(
                        KeyProperties.DIGEST_SHA256,
                        KeyProperties.DIGEST_SHA1
                    )
                    .setCertificateNotBefore(start.time)
                    .setCertificateNotAfter(end.time)
                    .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                    .build()
            )
            kpg.generateKeyPair()
        }

        fun getPrivateyPair(): PrivateKey {
            val keyStore: KeyStore = KeyStore.getInstance("AndroidKeyStore")
            keyStore.load(null)
            val entry: KeyStore.Entry =
                keyStore.getEntry(KopraMobile().BIOMETRIC_ALIAS_KEY_PAIR, null)
            return (entry as KeyStore.PrivateKeyEntry).privateKey
        }

        fun getPublicKeyPair(): PublicKey {
            val keyStore: KeyStore = KeyStore.getInstance("AndroidKeyStore")
            keyStore.load(null)
            return keyStore.getCertificate(KopraMobile().BIOMETRIC_ALIAS_KEY_PAIR).getPublicKey()
        }

fun getValAuthorization(_context: Context): String {
            var encoded = ""
            try {

                val randomString = getRandomString(10)
                val time = System.currentTimeMillis()
                val random = (randomString + "" + time)
                val rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
                rsaCipher.init(Cipher.ENCRYPT_MODE, getPrivateyPair())
                val byteArray = random.toByteArray(Charsets.UTF_8)
                val cipherText = rsaCipher.doFinal(byteArray)
                val randomHash = Base64.encodeToString(cipherText, Base64.NO_WRAP)
                encoded = "Basic " + Base64.encodeToString(
                    ("$random:$randomHash").toByteArray(),
                    Base64.NO_WRAP
                )

            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
            return encoded
        }

        fun getRandomString(length: Int): String {
            val charset = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz0123456789"
            return (1..length)
                .map { charset.random() }
                .joinToString("")
        }
</code>```

i get error

android.security.KeyStoreException: Incompatible digest

when try to call getValAuthorization() on the part

```<code>rsaCipher.init(Cipher.ENCRYPT_MODE, getPrivateyPair())
</code>```

how to solved it? thanks

Body:
i want to get value hashed in kotlin with private key RSA, but i have error 'android.security.KeyStoreException: Incompatible digest'.

this my code

    fun generatePairKey() {
            val start: Calendar = GregorianCalendar()
            val end: Calendar = GregorianCalendar()
            end.add(Calendar.YEAR, 1)
            val kpg: KeyPairGenerator = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"
            )
            kpg.initialize(
                KeyGenParameterSpec.Builder(
                    KopraMobile().BIOMETRIC_ALIAS_KEY_PAIR,
                    KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT

                ).setKeySize(2048)
                    .setUserAuthenticationRequired(false)
                    .setDigests(
                        KeyProperties.DIGEST_SHA256,
                        KeyProperties.DIGEST_SHA1
                    )
                    .setCertificateNotBefore(start.time)
                    .setCertificateNotAfter(end.time)
                    .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                    .build()
            )
            kpg.generateKeyPair()
        }

        fun getPrivateyPair(): PrivateKey {
            val keyStore: KeyStore = KeyStore.getInstance("AndroidKeyStore")
            keyStore.load(null)
            val entry: KeyStore.Entry =
                keyStore.getEntry(KopraMobile().BIOMETRIC_ALIAS_KEY_PAIR, null)
            return (entry as KeyStore.PrivateKeyEntry).privateKey
        }

        fun getPublicKeyPair(): PublicKey {
            val keyStore: KeyStore = KeyStore.getInstance("AndroidKeyStore")
            keyStore.load(null)
            return keyStore.getCertificate(KopraMobile().BIOMETRIC_ALIAS_KEY_PAIR).getPublicKey()
        }

fun getValAuthorization(_context: Context): String {
            var encoded = ""
            try {

                val randomString = getRandomString(10)
                val time = System.currentTimeMillis()
                val random = (randomString + "" + time)
                val rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
                rsaCipher.init(Cipher.ENCRYPT_MODE, getPrivateyPair())
                val byteArray = random.toByteArray(Charsets.UTF_8)
                val cipherText = rsaCipher.doFinal(byteArray)
                val randomHash = Base64.encodeToString(cipherText, Base64.NO_WRAP)
                encoded = "Basic " + Base64.encodeToString(
                    ("$random:$randomHash").toByteArray(),
                    Base64.NO_WRAP
                )

            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
            return encoded
        }

        fun getRandomString(length: Int): String {
            val charset = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz0123456789"
            return (1..length)
                .map { charset.random() }
                .joinToString("")
        }

i get error

android.security.KeyStoreException: Incompatible digest

when try to call getValAuthorization() on the part

rsaCipher.init(Cipher.ENCRYPT_MODE, getPrivateyPair())

how to solved it? thanks


问:
Whole website form not displaying, IE 9 compatibility mode?
Our whole form does not show if IE 9 compatibility mode is turned on.

Our DOCTYPE:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code>```

What is wrong?

ContentLicense: CC BY-SA 3.0

Body:
Our whole form does not show if IE 9 compatibility mode is turned on.

Our DOCTYPE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

What is wrong?


问:
How to annotate multi field index in apache geode spring boot application
I am developing a Spring Boot Client cache application (spring-geode-starter version 1.7.5) with a region name say 'Element' having 5 fields (say, id, code1,stDate,endDate,code2). Now I have OQL , i.e. a single select statement from the 4 fields (code1,stDate,endDate,code2) with and & where conditions. I see @Indexed for single fields and @EnableIndexing are used in tutorials to create indexes. ( https://docs.spring.io/spring-boot-data-geode-build/1.7.x/reference/html5/ )

my objective is: To create a single index from client cache application on these 4 fields in sequence code1+code2+stDate+endDate, i.e. single multi field index
can any one help me ?


问:
How to read dictionary_page values in a parquet file?
I saw dictionary_page_offset and has_dictionary_page in the document but couldn't find a way to read the dictionary values.

MY current code not sure is right way.

     for group in range(pq_file.metadata.num_row_groups):
         for col in range(pq_file.metadata.num_columns):
             col_log = {}
             col_meta = pq_file.metadata.row_group(group).column(col)
             dict_page_offset =col_meta.dictionary_page_offset
             print(dict_page_offset)
             dict_page = pq_file.read_row_group(0, columns=[col])
             print(dict_page.to_pylist())
```


问:
WebRTC - receiving H264 key frames
I've been playing with WebRTC using libdatachannel, experimenting and learning.

Wrote some code to parse RTP packets into NALU's, and testing connecting to a "known good" server which sends H264 video.

Problem:

I'm only seeing NALU's with type = 1 (fragmented into multiple FU-A's) and sometimes type = 24 (which contain embedded SPS and PPS NALU's).

So I don't understand how to decode / render this stream - I would expect the server to send a NALU with a key frame (NALU type 5) automatically to a newly connected client, but it does not.

What am I missing to be able to decode the stream? What should I do to receive a key frame quickly? If my understanding is correct, I need a key frame to start decoding / rendering.

Tried requesting a key frame from code - it does arrive (type 5) but after some delay which is undesirable.

And yet the stream plays perfectly fine with a web browser client (Chrome, JavaScript) and starts up quickly.

Am I maybe overthinking this, and the browser also has a delay but I'm just perceiving it as instant?

In any case, what's the situation with key frames? Is a client supposed to request them (and without that, a server should not be expected to send them)?

If so what's a good interval? One second, two, three?

Title: WebRTC - receiving H264 key frames


问:
tried to redefine existing error around graphql
I have 2 project(graphql client) with schema.graphqls each fro different graphql endpoints, and have some same definitions.

Project A
--schema.graphqls
--type Order...
type Product...
Project B
--schema.graphqls
--type order...
type Product...

The project A and B managed by a parent project like below

```<code><modules>
    <module>../projectA</module>
    <module>../proejctB</module>
</code>```

So, when I run one of the 2 project will throw the error below

```<code>There are problems with the GraphQL Schema:
     * 'Mutation' type [@307:1] tried to redefine existing 'Mutation' type [@10:1]
     * 'Order' type [@374:1] tried to redefine existing 'Order' type [@455:1]
     * 'OrderConnection' type [@421:1] tried to redefine existing 'OrderConnection' type [@439:1]
     * 'OrderEdge' type [@429:1] tried to redefine existing 'OrderEdge' type [@447:1]
     * 'PaymentMethod' type [@502:1] tried to redefine existing 'PaymentMethod' type [@501:1]
     * 'Product' type [@518:1] tried to redefine existing 'Product' type [@571:1]
</code>```

How can I resolve the issue? Thanks a lot!

Body:
I have 2 project(graphql client) with schema.graphqls each fro different graphql endpoints, and have some same definitions.

Project A
--schema.graphqls
--type Order...
type Product...
Project B
--schema.graphqls
--type order...
type Product...

The project A and B managed by a parent project like below

<modules>
    <module>../projectA</module>
    <module>../proejctB</module>

So, when I run one of the 2 project will throw the error below

There are problems with the GraphQL Schema:
     * 'Mutation' type [@307:1] tried to redefine existing 'Mutation' type [@10:1]
     * 'Order' type [@374:1] tried to redefine existing 'Order' type [@455:1]
     * 'OrderConnection' type [@421:1] tried to redefine existing 'OrderConnection' type [@439:1]
     * 'OrderEdge' type [@429:1] tried to redefine existing 'OrderEdge' type [@447:1]
     * 'PaymentMethod' type [@502:1] tried to redefine existing 'PaymentMethod' type [@501:1]
     * 'Product' type [@518:1] tried to redefine existing 'Product' type [@571:1]

How can I resolve the issue? Thanks a lot!


问:
Independent Effect of Custom Paint widget in flutter
When I click on List view item it changes. I want when index changes custom paint effect of previous image save and want to move this paint part only to next widget if user selects apply changes to "yes". When I change by clicking paint and eraser effect remains same which I don't want.

Here is my code:


问:
In my code I have to tell the user how much of his salary he has to pay as tax
but my code is not working. I have put double tax = 5/100*salary but it's only showing 0.0.

This is what I have tried.

package company;
import java.util.Scanner;
public class p6 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter your Salary(in lakhs): ");
        double salary=sc.nextDouble();
        if(salary<2.5)
        {
            System.out.println("You don't have to pay any tax.");
        }
        else if(salary>=2.5&&salary<5.0)
        {
            System.out.println("You have to pay 5% of your salary as tax.");
            double tax=5/100*salary;
            System.out.println(tax);
        }
        else if(salary >=5.0 && salary < 10.0)
        {
            System.out.println("You have to pay 20% of your salary as tax.");
            double tax=20/100*salary;
            System.out.println(tax);

        }
        else {
            System.out.println("You have to pay 30% of your salary as tax.");
            double tax=30/100*salary;
            System.out.println(tax);
        }
    }
}
```

OUTPUT:-
Enter your Salary(in lakhs): 3
You have to pay 5% of your salary as tax.
0.0

Body:
but my code is not working. I have put double tax = 5/100*salary but it's only showing 0.0.

This is what I have tried.

package company;
import java.util.Scanner;
public class p6 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter your Salary(in lakhs): ");
        double salary=sc.nextDouble();
        if(salary<2.5)
        {
            System.out.println("You don't have to pay any tax.");
        }
        else if(salary>=2.5&&salary<5.0)
        {
            System.out.println("You have to pay 5% of your salary as tax.");
            double tax=5/100*salary;
            System.out.println(tax);
        }
        else if(salary >=5.0 && salary < 10.0)
        {
            System.out.println("You have to pay 20% of your salary as tax.");
            double tax=20/100*salary;
            System.out.println(tax);

        }
        else {
            System.out.println("You have to pay 30% of your salary as tax.");
            double tax=30/100*salary;
            System.out.println(tax);
        }
    }
}

OUTPUT:-
Enter your Salary(in lakhs): 3
You have to pay 5% of your salary as tax.
0.0


问:
Copyleaks export query with scan id and results internet id?
I am using copyleaks in the Laravel your php sdk, and able to successfully submit & scans method.

If we have completed our scan successfully and getting response in our web hook, with scan id and multiple result internet id. So, do we need to export all result internet id or only first result internet id?


问:
invalid table number error in crystal Report
When you run the Report, the following error occurs: 'Invalid Table Number'.

Can anyone tell me why?

Report having SubReport in it.

I am Using Crystal 10

I already tried with Set DataSource Location and Verify Database


问:
How to add icons inside node in Ant design Radial graph component?
I need to add different icons for each node in Radial graph component

I saw Ant Design documentation, there were some properties to change node type to circle, rect, icon-node. But not explained how to set icons inside node


问:
How to add ripple animation in imageView?
I'm trying to show a ripple animation in imageView before loading the image from the server.

I tried below code:

```<code>        ImageView imageView = findViewById(R.id.image_view);

// Create a RippleDrawable with a solid color background and no foreground
        RippleDrawable rippleDrawable = new RippleDrawable(
                ColorStateList.valueOf(Color.BLACK), // Ripple color
                null, // Background drawable
                null // Foreground drawable
        );

// Create an AnimationDrawable that wraps the RippleDrawable
        AnimationDrawable animationDrawable = new AnimationDrawable();
        animationDrawable.addFrame(rippleDrawable, 1000); // Add the RippleDrawable, with a duration of 1000 ms
        animationDrawable.setOneShot(false); // Set the animation to loop indefinitely

// Set the AnimationDrawable as the background of the ImageView
        imageView.setBackground(animationDrawable);

// Start the animation

        animationDrawable.start();
</code>```
```<code>    <ImageView
        android:id="@+id/image_view"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</code>```

This is not working

Body:
I'm trying to show a ripple animation in imageView before loading the image from the server.

I tried below code:

        ImageView imageView = findViewById(R.id.image_view);

// Create a RippleDrawable with a solid color background and no foreground
        RippleDrawable rippleDrawable = new RippleDrawable(
                ColorStateList.valueOf(Color.BLACK), // Ripple color
                null, // Background drawable
                null // Foreground drawable
        );

// Create an AnimationDrawable that wraps the RippleDrawable
        AnimationDrawable animationDrawable = new AnimationDrawable();
        animationDrawable.addFrame(rippleDrawable, 1000); // Add the RippleDrawable, with a duration of 1000 ms
        animationDrawable.setOneShot(false); // Set the animation to loop indefinitely

// Set the AnimationDrawable as the background of the ImageView
        imageView.setBackground(animationDrawable);

// Start the animation

        animationDrawable.start();

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

This is not working


问:
Ec2 instance out of service
I have an ec2 instance. and I use this instance for serving Nodejs applications with GitHub action. everything is working as expected. but sometimes like after 1/2 days, the instance is not reachable by anything. it's showing an offline flag on the GitHub action tab. But, in the AWS ec2 console. it's showing running. All stats look normal.  I actually have no idea why this behaves like this.

every time this happened, I have to stop and start the instance manually to up and run my server.

EC2 monitor stats

I actually think, there may be resource limitations, therefore the instance is hanging. but after I upgrade my instance type to t2.xlarge it still happens.

Title: Ec2 instance out of service


问:
How to get class name of listener using event type passed in laravel?
I have one event named "Search" and listener class named as "TestDataSend" and would like to call listen like

Event called like

```<code>$eventData = [
    "type_id" => $id,
     "event_type" => 'search_event',
];
event(new SearchEvent($eventData));
</code>```

so I would like to

```<code>(new $listener)->handle($event);
</code>```

so how can I get the class name of listener based on event type?

Body:
I have one event named "Search" and listener class named as "TestDataSend" and would like to call listen like

Event called like

$eventData = [
    "type_id" => $id,
     "event_type" => 'search_event',
];
event(new SearchEvent($eventData));

so I would like to

(new $listener)->handle($event);

so how can I get the class name of listener based on event type?


问:
Kafka Streams add name to a block of steps in topology
I am creating a kafka streams  library. I am trying to make the topology generic by having a fixed base topology and let the client modify on top of it.

Here is what it looks like:

```<code>@Override
public void configureTopology(final Topology topology) {
    KafkaStreamsInfrastructureCustomizer.super.configureTopology(topology);
    modifyTopology(topology);
}

@Override
public void configureBuilder(final StreamsBuilder builder) {

    final Consumed<A, B> consumed = config.getConsumed();
    final KStream<A, B> source = builder.stream(config.getSourceTopic(), consumed);
    final KStream<C, D> preProcessedStream = preProcess(builder, source);

    // Skipping the other topology steps which contain transformers.
    preProcessedStream.process(processorSupplier,
            Named.as("terminal-processor"));
}

public void modifyTopology(final Topology topology) {}

protected abstract KStream<C, D> preProcess(StreamsBuilder builder, KStream<A, B> stream);
</code>```

The preProcessStream is a function which the client will implement if they want to perform some preprocessing.

They will use the modifyTopology to add new processors to the existing topology.

Questions:

How can I add a name to the preProcess step so that if someone wants to add a processor in modifyTopology to consume after preProcess step, they can do so like below:

```<code>public void modifyTopology(final Topology topology) {
  topology.addProcessor("processor-name", OtherProcessor::new, "name-of-preprocess-step");
}
</code>```

I am aware I can do so by adding a always true filter step with name. But is there any other way?

Is it fine to use both configureBuilder and configureTopology like this?
I want to use configureBuilder because I am using a Transformer in my fixed topology.

I am aware that I can use a processor with context.forward in place of transformer but I want to make the library easy to implement for clients.

Body:
I am creating a kafka streams  library. I am trying to make the topology generic by having a fixed base topology and let the client modify on top of it.

Here is what it looks like:

@Override
public void configureTopology(final Topology topology) {
    KafkaStreamsInfrastructureCustomizer.super.configureTopology(topology);
    modifyTopology(topology);
}

@Override
public void configureBuilder(final StreamsBuilder builder) {

    final Consumed consumed = config.getConsumed();
    final KStream source = builder.stream(config.getSourceTopic(), consumed);
    final KStream<C, D> preProcessedStream = preProcess(builder, source);

    // Skipping the other topology steps which contain transformers.
    preProcessedStream.process(processorSupplier,
            Named.as("terminal-processor"));
}

public void modifyTopology(final Topology topology) {}

protected abstract KStream<C, D> preProcess(StreamsBuilder builder, KStream stream);

The preProcessStream is a function which the client will implement if they want to perform some preprocessing.

They will use the modifyTopology to add new processors to the existing topology.

Questions:

How can I add a name to the preProcess step so that if someone wants to add a processor in modifyTopology to consume after preProcess step, they can do so like below:

public void modifyTopology(final Topology topology) {
  topology.addProcessor("processor-name", OtherProcessor::new, "name-of-preprocess-step");
}

I am aware I can do so by adding a always true filter step with name. But is there any other way?

Is it fine to use both configureBuilder and configureTopology like this?
I want to use configureBuilder because I am using a Transformer in my fixed topology.

I am aware that I can use a processor with context.forward in place of transformer but I want to make the library easy to implement for clients.


问:
How to extract the coordinates of a recognized object in the YOLO model?
I trained the model on my custom objects and it finds them, but I need to track where exactly they go to the left and to the right, whether they cross the "line".

```<code>cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    # Make detections
    if type(frame) == type(None):
        break

    results = model(frame, size=640)

    cv2.imshow('YOLO', np.squeeze(results.render()))

    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
</code>```

I watched a YouTube video on this topic, but there is no talk about applying model prediction, but only contour analysis. Contour analysis doesn't really work for me.

The only thing is to look for the class name in the YOLO prediction and track it somehow.

I am new and may not know much.

I think someone already did it a long time ago, but it's called by a different mou and I can't find it by keywords.

Body:
I trained the model on my custom objects and it finds them, but I need to track where exactly they go to the left and to the right, whether they cross the "line".

cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    # Make detections
    if type(frame) == type(None):
        break

    results = model(frame, size=640)

    cv2.imshow('YOLO', np.squeeze(results.render()))

    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

I watched a YouTube video on this topic, but there is no talk about applying model prediction, but only contour analysis. Contour analysis doesn't really work for me.

The only thing is to look for the class name in the YOLO prediction and track it somehow.

I am new and may not know much.

I think someone already did it a long time ago, but it's called by a different mou and I can't find it by keywords.


问:
Conditional logic in a way that does not create a conflict. Jotform
In Jotform I want to display different thank you message based on the Answers/Options selected.

Example

```<code>A > B => Display Oily + Dry
A > C => Display Oily + Wet
B > A => Display Dry + Oily
B > C => Display Dry + Wet
C > A => Display Wet + Oily
C > B => Display Wet + Dry
</code>```

But in the above condition

```<code>For
A > B &
B > A
</code>```

It displays the same result Oily + Dry

Can this conditions be achieved in a different way

Body:
In Jotform I want to display different thank you message based on the Answers/Options selected.

Example

A > B => Display Oily + Dry
A > C => Display Oily + Wet
B > A => Display Dry + Oily
B > C => Display Dry + Wet
C > A => Display Wet + Oily
C > B => Display Wet + Dry

But in the above condition

For
A > B &
B > A

It displays the same result Oily + Dry

Can this conditions be achieved in a different way


问:
How to use data from DB as initial state with Zustand
I'm using the T3 stack (TypeScript, tRPC, Prisma, Next, etc) and I want to either load data from my database using a tRPC query, or use an empty array in my Zustand store. I keep getting an error saying:

You might have mismatching versions of React and the renderer (such as React DOM)

You might be breaking the Rules of Hooks

You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug
and fix this problem. error - TypeError: Cannot read properties of
null (reading 'useContext')
(node:internal/process/task_queues:96:5) {   page: '/' }

here's the code generating the error:

```<code>type Image = {
  url: string;
  prompt: string;
};

interface UserState {
  images: Image[] | [];
  isLoading: boolean;
  addImage: (url: string, prompt: string) => void;
  removeImage: (url: string, prompt: string) => void;
  setLoading: () => void;
}

export const useStore = create<UserState>((set) => {
  const { data: sessionData } = useSession();

  const dbImages = trpc.images.list.useQuery({
    limit: 20,
    userId: sessionData?.user?.id ?? "",
  }).data?.items;

  return {
    // initial state
    images: dbImages ? dbImages : [],
    isLoading: false,
    // methods for manipulating state
    addImage: (url, prompt) => {
      set((state) => ({
        images: [
          ...state.images,
          {
            url: url,
            prompt: prompt,
          } as Image,
        ],
      }));
    },
    removeImage: (url: string) => {
      set((state) => ({
        images: state.images?.filter((x) => x.url !== url),
      }));
    },
    setLoading: () => {
      set((state) => ({
        isLoading: !state.isLoading,
      }));
    },
  };
});
</code>```

What am I doing wrong here? I'm still in the learning phases and would appreciate best practices, etc.

Body:
I'm using the T3 stack (TypeScript, tRPC, Prisma, Next, etc) and I want to either load data from my database using a tRPC query, or use an empty array in my Zustand store. I keep getting an error saying:

You might have mismatching versions of React and the renderer (such as React DOM)

You might be breaking the Rules of Hooks

You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug
and fix this problem. error - TypeError: Cannot read properties of
null (reading 'useContext')
(node:internal/process/task_queues:96:5) {   page: '/' }

here's the code generating the error:

type Image = {
  url: string;
  prompt: string;
};

interface UserState {
  images: Image[] | [];
  isLoading: boolean;
  addImage: (url: string, prompt: string) => void;
  removeImage: (url: string, prompt: string) => void;
  setLoading: () => void;
}

export const useStore = create<UserState>((set) => {
  const { data: sessionData } = useSession();

  const dbImages = trpc.images.list.useQuery({
    limit: 20,
    userId: sessionData?.user?.id ?? "",
  }).data?.items;

  return {
    // initial state
    images: dbImages ? dbImages : [],
    isLoading: false,
    // methods for manipulating state
    addImage: (url, prompt) => {
      set((state) => ({
        images: [
          ...state.images,
          {
            url: url,
            prompt: prompt,
          } as Image,
        ],
      }));
    },
    removeImage: (url: string) => {
      set((state) => ({
        images: state.images?.filter((x) => x.url !== url),
      }));
    },
    setLoading: () => {
      set((state) => ({
        isLoading: !state.isLoading,
      }));
    },
  };
});

What am I doing wrong here? I'm still in the learning phases and would appreciate best practices, etc.


问:
Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided using GeckoDriver
I am trying to run selenium python script using selenium V4.7.2 on Firefox.
I am on windows 11 64 bit.

Chrome is running without using WebDriverManager with the below mentioned code -

```<code>from selenium import webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.wikipedia.org/")
</code>```

But when running through Firefox, It is throwing me an error when using the below code -

```<code>from selenium import webdriver
driver = webdriver.Firefox()
driver.maximize_window()
driver.get("https://www.wikipedia.org/")
</code>```

Error is -

"selenium.common.exceptions.SessionNotCreatedException: Message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line"

My firefox is the latest version i.e, 108.0.1 and GeckDriver version is 0.32.0

Firefox is installed in the default location i.e, "C:\Program Files\Mozilla Firefox"

Any help is highly appreciated. Stuck here since a week.

I have tried re-installing firefox.
Also tried adding GeckoDriver.exe in System path. (Environment variable)
Also my geckdriver version is 64 bit same as my laptop's config.

I am able to run through Firefox using WebDriverManager, but in the latest version of Selenium 4.6.0 there is no need to import WebDriverManager, that's why was trying to run without WebDriverManager.

If anyone could provide me with the solution that would be helpful.

Body:
I am trying to run selenium python script using selenium V4.7.2 on Firefox.
I am on windows 11 64 bit.

Chrome is running without using WebDriverManager with the below mentioned code -

from selenium import webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.wikipedia.org/")

But when running through Firefox, It is throwing me an error when using the below code -

from selenium import webdriver
driver = webdriver.Firefox()
driver.maximize_window()
driver.get("https://www.wikipedia.org/")

Error is -

"selenium.common.exceptions.SessionNotCreatedException: Message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line"

My firefox is the latest version i.e, 108.0.1 and GeckDriver version is 0.32.0

Firefox is installed in the default location i.e, "C:\Program Files\Mozilla Firefox"

Any help is highly appreciated. Stuck here since a week.

I have tried re-installing firefox.
Also tried adding GeckoDriver.exe in System path. (Environment variable)
Also my geckdriver version is 64 bit same as my laptop's config.

I am able to run through Firefox using WebDriverManager, but in the latest version of Selenium 4.6.0 there is no need to import WebDriverManager, that's why was trying to run without WebDriverManager.

If anyone could provide me with the solution that would be helpful.


问:
SQL DropDownList - ListItem inserts
I have a dropdownlist (DDL) for a user to select between two values to insert into the database via codebehind/stored procedure file. All my forms work well with the DDL method except when I try to add the DDL in an 'if else' statement. When I do this the form acts normal as if the information was inserted but doesn't insert values into the database.

ASPX CODE

```<code><tr><td>Active: </td><td>
  <asp:DropDownList ID="DropDownListActive" runat="server" AutoPostBack="True"
    Width="128px" AppendDataBoundItems="true" Height="22px">
    <asp:ListItem>Select</asp:ListItem>
    <asp:ListItem>Yes</asp:ListItem>
    <asp:ListItem>No</asp:ListItem>
  </asp:DropDownList>
  <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</td></tr>
</code>```

CODE-BEHIND:

```<code>if (DropDownListActive.SelectedValue == "Select")
{
    Label1.Text = "Please select Yes or No.";
    return;
}
else
{
    cmd.Parameters.Add(new SqlParameter("@Active", SqlDbType.VarChar, 3));
    cmd.Parameters["@Active"].Value = DropDownListActive.SelectedValue;
}
</code>```

Title: SQL DropDownList - ListItem inserts

Body:
I have a dropdownlist (DDL) for a user to select between two values to insert into the database via codebehind/stored procedure file. All my forms work well with the DDL method except when I try to add the DDL in an 'if else' statement. When I do this the form acts normal as if the information was inserted but doesn't insert values into the database.

ASPX CODE

Active:
  <asp:DropDownList ID="DropDownListActive" runat="server" AutoPostBack="True"
    Width="128px" AppendDataBoundItems="true" Height="22px">
    <asp:ListItem>Select</asp:ListItem>
    <asp:ListItem>Yes</asp:ListItem>
    <asp:ListItem>No</asp:ListItem>
  </asp:DropDownList>
  <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

CODE-BEHIND:

if (DropDownListActive.SelectedValue == "Select")
{
    Label1.Text = "Please select Yes or No.";
    return;
}
else
{
    cmd.Parameters.Add(new SqlParameter("@Active", SqlDbType.VarChar, 3));
    cmd.Parameters["@Active"].Value = DropDownListActive.SelectedValue;
}


问:
Why is Ajax request not working as intended in rails
I'm following a tutorial on ruby on rails. In the tutorial the tutor is able to display the errors on saving using the @article.erros.any but in my case @article.save doesn't even finish process and i get this in my console

```<code>Started POST "/articles" for ::1 at 2022-12-28 16:24:05 +1100
Processing by ArticlesController#create as TURBO_STREAM
  Parameters: {"authenticity_token"=>"[FILTERED]", "article"=>{"title"=>"", "description"=>""}, "commit"=>"Create Article"}
  Rendering layout layouts/application.html.erb
  Rendering articles/new.html.erb within layouts/application
  Rendered articles/new.html.erb within layouts/application (Duration: 7.7ms | Allocations: 4887)
  Rendered layout layouts/application.html.erb (Duration: 12.9ms | Allocations: 7084)
Completed 200 OK in 16ms (Views: 13.4ms | ActiveRecord: 0.0ms | Allocations: 8264)
</code>```

and this is my browser

This is my controller

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def destroy
    @article.destroy
    redirect_to articles_path
  end

  private

  def article_params
    params.require(:article).permit(:title, :description)
  end
end
```
<p>and this is my html.erb</p>
<pre class="lang-rb prettyprint-override"><code><h1>Create a new article</h1>
<% if @article.errors.any? %>
  <h2> The following errors prevented the article from being saved</h2>
  <ul>
    <li>
      <% @article.errors.full_messages.each do |msg| %>
        <%= msg %>
      <% end %>
    </li>
  </ul>
<% end %>

<%= form_with(model: @article, url: articles_path, local: true) do |form| %>
  <p>
    <%= form.label :title %><br/>
    <%= form.text_field :title %>
  </p>
  <p>
    <%= form.label :description %> <br/>
    <%= form.text_area :description %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

</code>```

I have validate in my model that should prevent submission and display the error but nothing happens

  validates :title, presence: true, length: { minimum: 6, maximum: 100 }
  validates :description, presence: true, length: { minimum: 10, maximum: 300 }
```
<p>when I use <code>@article.save!</code> using the bang operator <code>!</code> it kind of works but it reloads the page</p>
```ActiveRecord::RecordInvalid (Validation failed: Title can't be blank, Title is too short (minimum is 6 characters), Description can't be blank, Description is too short (minimum is 10 characters)):

app/controllers/articles_controller.rb:20:in `create'
Started GET "/articles/new" for ::1 at 2022-12-28 16:15:04 +1100
Processing by ArticlesController#new as HTML
  Rendering layout layouts/application.html.erb
  Rendering articles/new.html.erb within layouts/application
  Rendered articles/new.html.erb within layouts/application (Duration: 1.4ms | Allocations: 969)
  Rendered layout layouts/application.html.erb (Duration: 5.8ms | Allocations: 3190)
Completed 200 OK in 7ms (Views: 6.2ms | ActiveRecord: 0.0ms | Allocations: 3446)
```

I'm really new to rails and using rails 7. searching through other issues, it doesn't appear other people are encountering this issue. Any help is appreciated

Body:
I'm following a tutorial on ruby on rails. In the tutorial the tutor is able to display the errors on saving using the @article.erros.any but in my case @article.save doesn't even finish process and i get this in my console

Started POST "/articles" for ::1 at 2022-12-28 16:24:05 +1100
Processing by ArticlesController#create as TURBO_STREAM
  Parameters: {"authenticity_token"=>"[FILTERED]", "article"=>{"title"=>"", "description"=>""}, "commit"=>"Create Article"}
  Rendering layout layouts/application.html.erb
  Rendering articles/new.html.erb within layouts/application
  Rendered articles/new.html.erb within layouts/application (Duration: 7.7ms | Allocations: 4887)
  Rendered layout layouts/application.html.erb (Duration: 12.9ms | Allocations: 7084)
Completed 200 OK in 16ms (Views: 13.4ms | ActiveRecord: 0.0ms | Allocations: 8264)

and this is my browser

This is my controller

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def destroy
    @article.destroy
    redirect_to articles_path
  end

  private

  def article_params
    params.require(:article).permit(:title, :description)
  end
end

and this is my html.erb

Create a new article

<% if @article.errors.any? %>

 The following errors prevented the article from being saved

      <% @article.errors.full_messages.each do |msg| %>
        <%= msg %>
      <% end %>

<% end %>

<%= form_with(model: @article, url: articles_path, local: true) do |form| %>

    <%= form.label :title %>

    <%= form.text_field :title %>

    <%= form.label :description %>

    <%= form.text_area :description %>

    <%= form.submit %>

<% end %>

I have validate in my model that should prevent submission and display the error but nothing happens

  validates :title, presence: true, length: { minimum: 6, maximum: 100 }
  validates :description, presence: true, length: { minimum: 10, maximum: 300 }

when I use @article.save! using the bang operator ! it kind of works but it reloads the page

ActiveRecord::RecordInvalid (Validation failed: Title can't be blank, Title is too short (minimum is 6 characters), Description can't be blank, Description is too short (minimum is 10 characters)):

app/controllers/articles_controller.rb:20:in `create'
Started GET "/articles/new" for ::1 at 2022-12-28 16:15:04 +1100
Processing by ArticlesController#new as HTML
  Rendering layout layouts/application.html.erb
  Rendering articles/new.html.erb within layouts/application
  Rendered articles/new.html.erb within layouts/application (Duration: 1.4ms | Allocations: 969)
  Rendered layout layouts/application.html.erb (Duration: 5.8ms | Allocations: 3190)
Completed 200 OK in 7ms (Views: 6.2ms | ActiveRecord: 0.0ms | Allocations: 3446)

I'm really new to rails and using rails 7. searching through other issues, it doesn't appear other people are encountering this issue. Any help is appreciated


问:
why do i get the syntax error "'list' object has no attribute 'split'"
```<code># import Sastrawi package
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
# create stemmer
factory = StemmerFactory()
stemmer = factory.create_stemmer()

def stemming(text):
    text = [stemmer.stem(word) for word in text.split()]
    return text
data['abstrak'] = data['abstrak'].apply(stemming)
data['judul'] = data['judul'].apply(stemming)
data.head()
</code>```

On the marked line of code,  text = [stemmer.stem(word) for word in text.split()],  I get an error 'list' object has no attribute 'split'

When I remove that line from the code, the same error appears at the next line of code, again for no apparent reason.

On the marked line of code,  text = [stemmer.stem(word) for word in text.split()],  I get an error 'list' object has no attribute 'split'

When I remove that line from the code, the same error appears at the next line of code, again for no apparent reason.

Body:
# import Sastrawi package
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
# create stemmer
factory = StemmerFactory()
stemmer = factory.create_stemmer()

def stemming(text):
    text = [stemmer.stem(word) for word in text.split()]
    return text
data['abstrak'] = data['abstrak'].apply(stemming)
data['judul'] = data['judul'].apply(stemming)
data.head()

On the marked line of code,  text = [stemmer.stem(word) for word in text.split()],  I get an error 'list' object has no attribute 'split'

When I remove that line from the code, the same error appears at the next line of code, again for no apparent reason.

On the marked line of code,  text = [stemmer.stem(word) for word in text.split()],  I get an error 'list' object has no attribute 'split'

When I remove that line from the code, the same error appears at the next line of code, again for no apparent reason.


问:
Can not find the issue in my .zshrc file (macOS)
I am getting this error when I try to source ~/.zshrc

Error: /Users/saad/.zshrc:10: parse error near \n'

I can't figure what the issue is, here is my zshrc file

```<code>export PATH="$PATH:/Users/saad/developement/flutter/bin"
export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.17)
export PATH="$HOME/.yarn/bin:$HOME/.config/yarn/global/node_modules/.bin:$PATH"
export PATH=$ANDROID_HOME/emulator:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH
export ANDROID_HOME="/Users/saad/Library/Android/sdk"
export ANDROID_SDK_ROOT=<your path>
export PATH="$HOME/.rbenv/shims:$PATH"
export PATH="$PATH:$HOME/.rvm/bin"
export NVM_DIR="$HOME/.nvm"
. "/usr/local/opt/nvm/nvm.sh"
</code>```

Body:
I am getting this error when I try to source ~/.zshrc

Error: /Users/saad/.zshrc:10: parse error near \n'

I can't figure what the issue is, here is my zshrc file

export PATH="$PATH:/Users/saad/developement/flutter/bin"
export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.17)
export PATH="$HOME/.yarn/bin:$HOME/.config/yarn/global/node_modules/.bin:$PATH"
export PATH=$ANDROID_HOME/emulator:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH
export ANDROID_HOME="/Users/saad/Library/Android/sdk"
export ANDROID_SDK_ROOT=<your path>
export PATH="$HOME/.rbenv/shims:$PATH"
export PATH="$PATH:$HOME/.rvm/bin"
export NVM_DIR="$HOME/.nvm"
. "/usr/local/opt/nvm/nvm.sh"


问:
Can I use XAML Designer in a CMake-controlled project?
I have a CMake project which I've opened in Visual Studio 2022 Professional as a directory, using a CMakePresets.txt to make some build presets.

I have a dotnet new wpf project added to this CMake project with include_external_msproject(....csproj TYPE "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC").

I want to be able to design the .xaml files using the WYSIWYG XAML Designer tool in Visual Studio, but don't have that option in this directory view (which is mandated for the CMakePresets integration).

Is this possible?

Workaround for now is to configure CMake, and then open the .sln with Visual Studio. I can then find the project in the list and use the designer. It's just clunky to have to re-open the same project a different way.


问:
"'dotnet.exe' exited with code -2147450750 " error in visual studio 2022 for MAUI
got "'dotnet.exe' exited with code -2147450750 " error while running android emulator choose "Release" instead of Debug in visual studio 2022 for MAUI.

How to fix it...

I installed .net latest version


问:
How to prevent REST Url from inspecting in flutter web?
REST Url are explode in flutter web app as in attached image. Are there any ways to prevent from inspecting?


问:
IONIC Angular Toggle Button Value for item filters
I want to make some advanced filtering in my ionic angular app. I'm using pipe to filter keys and it works perfectly for me when using input type.
There's a rating fields that only have 3 different type of string : 1,2 or/and 3 that I want to implement this filter by toggle button or checkbox not by using input and typing the number.

Here's my code
filter.pipe.ts

```<code>export class FilterPipe implements PipeTransform {
  transform(items: Array<any>, filter: { [key: string]: any }): Array<any> {
    if (Object.keys(filter).length == 0) return items;
    console.log(filter);

    let filterKeys = Object.keys(filter);

    return items.filter(item => {
      return filterKeys.every(keyName => {
        // console.log(keyName);
        return (
          new RegExp(filter[keyName], 'gi').test(item[keyName]) ||
          filter[keyName] === ''
        );
      });
    });
}
</code>```

test.page.ts

```<code>type objField = { name: string; rating: string; categories: string };

export class TestPage implements OnInit {

foods: any[] = [];
  fields = {
    name: '',
    rating: '',
    categories: ''
  };
  filter = {};

}

updateFilters() {
  Object.keys(this.fields).forEach(key =\> this.fields\[key as keyof typeof this.fields\] === '' ?    delete this.fields\[key as keyof typeof this.fields\] : key);
  this.filter = Object.assign({}, this.fields);
  console.log('aa', this.fields)
}

ngOnInit() {
 this.people = [
  { name: 'Banana', rating: '1', category: 'fruits' },
  { name: 'Almonds', rating: '3', category: 'nuts' },
  { name: 'Banana2', rating: '2', category: 'fruits' },
  { name: 'Almonds2', rating: '3', category: 'nuts' },
 ];
}
</code>```

test.page.html

```<code><ion-content>
  {{fields | json}} <br><br>
  Name:
  <input
    type="text"
    [(ngModel)]="fields.name"
    (ngModelChange)="updateFilters()"
  />
  <br />
  rating:
  <input type="text"
    [(ngModel)]="fields.rating"
    (ngModelChange)="updateFilters()"
  />
  <br />
  Category:
  <input type="text"
    [(ngModel)]="fields.categories"
    (ngModelChange)="updateFilters()"
  />
  <ion-item>
    <p class="item-high" slot="start">High</p>
    <ion-toggle slot="end" class=" toggle-high" mode="ios"
      [(ngModel)]="fields.rating"
      (ngModelChange)="updateFilters()">
    </ion-toggle>
  </ion-item>
  <table class="table">
    <thead>
      <tr>
        <th scope="col">Name</th>
        <th scope="col">Rating</th>
        <th scope="col">Categories</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let f of foods | myFilter :filter;">
        <td>{{f.name }}</td>
        <td>{{f.rating}}</td>
        <td>{{f.categories}}</td>
      </tr>
    </tbody>
  </table>
</ion-content>
</code>```

I tried adding [checked]="fields.rating === '1' ? true : false" and ng-true-value = "1"

but to be honest I just take it all from any references from all around google because I'm new to angular and typescript.

at this time the toggle button just return true or false to the rating field, I will have 3 toggles for each rating return value 1,2 or 3 to when set to true. And how to implement and operation that return 1 | 2 | 3 when all set to true.

Body:
I want to make some advanced filtering in my ionic angular app. I'm using pipe to filter keys and it works perfectly for me when using input type.
There's a rating fields that only have 3 different type of string : 1,2 or/and 3 that I want to implement this filter by toggle button or checkbox not by using input and typing the number.

Here's my code
filter.pipe.ts

export class FilterPipe implements PipeTransform {
  transform(items: Array<any>, filter: { [key: string]: any }): Array<any> {
    if (Object.keys(filter).length == 0) return items;
    console.log(filter);

    let filterKeys = Object.keys(filter);

    return items.filter(item => {
      return filterKeys.every(keyName => {
        // console.log(keyName);
        return (
          new RegExp(filter[keyName], 'gi').test(item[keyName]) ||
          filter[keyName] === ''
        );
      });
    });
}

test.page.ts

type objField = { name: string; rating: string; categories: string };

export class TestPage implements OnInit {

foods: any[] = [];
  fields = {
    name: '',
    rating: '',
    categories: ''
  };
  filter = {};

}

updateFilters() {
  Object.keys(this.fields).forEach(key =\> this.fields\[key as keyof typeof this.fields\] === '' ?    delete this.fields\[key as keyof typeof this.fields\] : key);
  this.filter = Object.assign({}, this.fields);
  console.log('aa', this.fields)
}

ngOnInit() {
 this.people = [
  { name: 'Banana', rating: '1', category: 'fruits' },
  { name: 'Almonds', rating: '3', category: 'nuts' },
  { name: 'Banana2', rating: '2', category: 'fruits' },
  { name: 'Almonds2', rating: '3', category: 'nuts' },
 ];
}

test.page.html

<ion-content>
  {{fields | json}}

  Name:
  <input
    type="text"
    [(ngModel)]="fields.name"
    (ngModelChange)="updateFilters()"
  />

  rating:
  <input type="text"
    [(ngModel)]="fields.rating"
    (ngModelChange)="updateFilters()"
  />

  Category:
  <input type="text"
    [(ngModel)]="fields.categories"
    (ngModelChange)="updateFilters()"
  />
  <ion-item>

High

    <ion-toggle slot="end" class=" toggle-high" mode="ios"
      [(ngModel)]="fields.rating"
      (ngModelChange)="updateFilters()">
    </ion-toggle>
  </ion-item>

        Name
        Rating
        Categories

        {{f.name }}
        {{f.rating}}
        {{f.categories}}

</ion-content>

I tried adding [checked]="fields.rating === '1' ? true : false" and ng-true-value = "1"

but to be honest I just take it all from any references from all around google because I'm new to angular and typescript.

at this time the toggle button just return true or false to the rating field, I will have 3 toggles for each rating return value 1,2 or 3 to when set to true. And how to implement and operation that return 1 | 2 | 3 when all set to true.


问:
why core data can't save NSNumber value?
I create NSNumber, use bool value control NSNumber.

I build simulator, core data have NSNumber data.

but i turn off simulator. Restart simulator again. NSNumber data not see

thank you for help.

core data value

```<code>@NSManaged public var cIsLike: NSNumber

 var isLike: Bool {
        get {
            return Bool(truncating: cIsLike)
        }
        set {
            cIsLike = NSNumber(value: newValue)
        }
    }
</code>```

change bool and save data code

```<code>private let moc: NSManagedObjectContext
    private var videoArray = [CoreVideo]()

    init(moc: NSManagedObjectContext) {
        self.moc = moc

    }

func updateVideo(currentVideo video: CoreVideo, isLike newValue: Bool) {
        video.isLike = newValue
        save()
    }

 private func save() {
        do {
            try moc.save()

        } catch let error as NSError {
            print("Save failed: \(error.localizedDescription)")
        }
    }
</code>```

Body:
I create NSNumber, use bool value control NSNumber.

I build simulator, core data have NSNumber data.

but i turn off simulator. Restart simulator again. NSNumber data not see

thank you for help.

core data value

@NSManaged public var cIsLike: NSNumber

 var isLike: Bool {
        get {
            return Bool(truncating: cIsLike)
        }
        set {
            cIsLike = NSNumber(value: newValue)
        }
    }

change bool and save data code

private let moc: NSManagedObjectContext
    private var videoArray = [CoreVideo]()

    init(moc: NSManagedObjectContext) {
        self.moc = moc

    }

func updateVideo(currentVideo video: CoreVideo, isLike newValue: Bool) {
        video.isLike = newValue
        save()
    }

 private func save() {
        do {
            try moc.save()

        } catch let error as NSError {
            print("Save failed: \(error.localizedDescription)")
        }
    }


问:
How to authorize Google Apps Scripts inside a Google Workspace when using Slack Events API

I can't seem to access a Google Scripts webapp via HTTP requests when it's exposed to only my workspace domain, though the same works when I allow anyone (even anonymous) to access it (from a personal account created for testing)

I'm currently trying to use the Events API from Slack's and listen to calls via a Google Apps Script. Here's what that looks like on Slack's side:
This is the screen I'm pasting the Scripts URL into

Now, if I do this with my personal account, it works with the following code in the script because I've configured it to run as myself and allow anyone on the internet to run it, even anonymously:

```<code>function doPost(e) {
  var v = JSON.parse(e.postData.contents);  // Added
  return ContentService.createTextOutput(v.challenge);  // Added
}
</code>```

This is how the webapp's URL looks - https://script.google.com/a/macros/scripbox.com/s/{scriptId}/exec

However, if I try to do the same from my Google Workspace account, I don't have the option to allow anonymous users to have access. The broadest option I have is "Anyone within {{workspace}}". How can I add authorization to my script URL so that anyone from my workspace's domain is able to access/use this webapp via http requests?

Body:
I can't seem to access a Google Scripts webapp via HTTP requests when it's exposed to only my workspace domain, though the same works when I allow anyone (even anonymous) to access it (from a personal account created for testing)

I'm currently trying to use the Events API from Slack's and listen to calls via a Google Apps Script. Here's what that looks like on Slack's side:
This is the screen I'm pasting the Scripts URL into

Now, if I do this with my personal account, it works with the following code in the script because I've configured it to run as myself and allow anyone on the internet to run it, even anonymously:

function doPost(e) {
  var v = JSON.parse(e.postData.contents);  // Added
  return ContentService.createTextOutput(v.challenge);  // Added
}

This is how the webapp's URL looks - https://script.google.com/a/macros/scripbox.com/s/{scriptId}/exec

However, if I try to do the same from my Google Workspace account, I don't have the option to allow anonymous users to have access. The broadest option I have is "Anyone within {{workspace}}". How can I add authorization to my script URL so that anyone from my workspace's domain is able to access/use this webapp via http requests?


问:
Facing problem to write in file using fputs()
```<code>#include <stdio.h>

int main(){

    FILE *fp;
    char name[25];
    int i;
    float cgpa;

    fp = fopen("FileExercise.txt", "w");

    if(fp==NULL) printf("File doesn't exist.\n");
    else{
        printf("File has opened.\n");
        for(i=0; i<5; i++){
            printf("Enter roll-%d student name: ", i+1);
            gets(name);
            fputs(name, fp);
            fprintf(fp, "\t%d", i+1);

            printf("Enter students cgpa: ");
            scanf("%f", &cgpa);
            fprintf(fp, "\t%0.2f", cgpa);

            fprintf(fp, "\n");
        }
        printf("File has written successfully.\n");
    }

    return 0;
}

</code>```

I was trying to to make a file of students. That includes students name, roll & cgpa. For the 1st students it was working. But from the second student I can't take student name as input also can't write student name in file. Now, What should I do?

Body:
#include <stdio.h>

int main(){

    FILE *fp;
    char name[25];
    int i;
    float cgpa;

    fp = fopen("FileExercise.txt", "w");

    if(fp==NULL) printf("File doesn't exist.\n");
    else{
        printf("File has opened.\n");
        for(i=0; i<5; i++){
            printf("Enter roll-%d student name: ", i+1);
            gets(name);
            fputs(name, fp);
            fprintf(fp, "\t%d", i+1);

            printf("Enter students cgpa: ");
            scanf("%f", &cgpa);
            fprintf(fp, "\t%0.2f", cgpa);

            fprintf(fp, "\n");
        }
        printf("File has written successfully.\n");
    }

    return 0;
}

I was trying to to make a file of students. That includes students name, roll & cgpa. For the 1st students it was working. But from the second student I can't take student name as input also can't write student name in file. Now, What should I do?


问:
scrapy closes spider with no visible error
There is a code for downloading information from the car website.

```<code>class AutospiderSpider(scrapy.Spider):
    name = 'autospider'

    def start_requests(self):
        keyword_list = ['subaru']
        for keyword in keyword_list:
            auto_search_url = f'https://auto.ru/krasnodarskiy_kray/cars/{keyword}/all/?page=1'
            yield scrapy.Request(url=auto_search_url, callback=self.discover_car_urls, meta={'keyword': keyword, 'page': 1})

    def discover_car_urls(self, response):
        page = response.meta['page']
        keyword = response.meta['keyword']
        #Discover Car URLs
        search_cars = response.css("div.ListingItem")
        for car  in search_cars:
            car_url = car.css("a.Link.OfferThumb::attr(href)").get()
            yield scrapy.Request(url=car_url, callback=self.parse_car_data, meta={'keyword': keyword, 'page': page})

        ## Get All Pages
        if page == 1:
            available_pages = response.css('a.ListingPagination__page::text').getall()

            for page_num in available_pages:
                auto_search_url = f'https://auto.ru/krasnodarskiy_kray/cars/{keyword}/all/?page={page_num}'
                yield scrapy.Request(url=auto_search_url, callback=self.discover_car_urls, meta={'keyword': keyword, 'page': page_num})

    def parse_car_data(self, response):

        price = response.css("span.OfferPriceCaption__price").get("").strip()
        if price != None:
            price = price.replace('\u00a0', '').replace('\u20bd', '').strip()
        yield {
            "brand": response.css("h1.CardHead__title::text").get(),
            "price": price,
             }

</code>```
```<code>2022-12-26 16:49:45 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://proxy.scrapeops.io/v1/?api_key=cf3a2102-2bf1-4ed1-90a5-b9b676b98009&url=https%3A%2F%2Fauto.ru%2Fkrasnodarskiy_kray%2Fcars%2Fsubaru%2Fall%2F%3Fpage%3D1> (referer: None)
2022-12-26 16:49:45 [scrapy.core.engine] INFO: Closing spider (finished)
</code>```

The spider closes automatically after receiving the first link without a visible error. I tried changing selectors, but I see the spelling is correct.
I have seen that some similar questions are related to getting a relative rather than an absolute path. But, in the code right here, getting an absolute path, so that's not the problem.

Similar code works perfectly on several other sites. Please tell me what the problem may be if the problem is not in the selector.

Body:
There is a code for downloading information from the car website.

class AutospiderSpider(scrapy.Spider):
    name = 'autospider'

    def start_requests(self):
        keyword_list = ['subaru']
        for keyword in keyword_list:
            auto_search_url = f'https://auto.ru/krasnodarskiy_kray/cars/{keyword}/all/?page=1'
            yield scrapy.Request(url=auto_search_url, callback=self.discover_car_urls, meta={'keyword': keyword, 'page': 1})

    def discover_car_urls(self, response):
        page = response.meta['page']
        keyword = response.meta['keyword']
        #Discover Car URLs
        search_cars = response.css("div.ListingItem")
        for car  in search_cars:
            car_url = car.css("a.Link.OfferThumb::attr(href)").get()
            yield scrapy.Request(url=car_url, callback=self.parse_car_data, meta={'keyword': keyword, 'page': page})

        ## Get All Pages
        if page == 1:
            available_pages = response.css('a.ListingPagination__page::text').getall()

            for page_num in available_pages:
                auto_search_url = f'https://auto.ru/krasnodarskiy_kray/cars/{keyword}/all/?page={page_num}'
                yield scrapy.Request(url=auto_search_url, callback=self.discover_car_urls, meta={'keyword': keyword, 'page': page_num})

    def parse_car_data(self, response):

        price = response.css("span.OfferPriceCaption__price").get("").strip()
        if price != None:
            price = price.replace('\u00a0', '').replace('\u20bd', '').strip()
        yield {
            "brand": response.css("h1.CardHead__title::text").get(),
            "price": price,
             }

2022-12-26 16:49:45 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://proxy.scrapeops.io/v1/?api_key=cf3a2102-2bf1-4ed1-90a5-b9b676b98009&url=https%3A%2F%2Fauto.ru%2Fkrasnodarskiy_kray%2Fcars%2Fsubaru%2Fall%2F%3Fpage%3D1> (referer: None)
2022-12-26 16:49:45 [scrapy.core.engine] INFO: Closing spider (finished)

The spider closes automatically after receiving the first link without a visible error. I tried changing selectors, but I see the spelling is correct.
I have seen that some similar questions are related to getting a relative rather than an absolute path. But, in the code right here, getting an absolute path, so that's not the problem.

Similar code works perfectly on several other sites. Please tell me what the problem may be if the problem is not in the selector.


问:
I need to insert one form in several peaces at one page by ajax in Drupal 7
I have page with several div with selector '.some-class'. I insert form by function</p>
```<code>$commands[] = ajax_command_html('.some-class', $form);

return array('#type' => 'ajax', '#commands' => $commands);

Forms are being inserted correctly, but when the form is submitted, all except the first one redirect to the technical URL - /system/ajax

I need all forms to be submitted correctly. I was sending each form separately to a separate selector - it works, but this solution doesn't seem right
</code>```

Body:
I have page with several div with selector '.some-class'. I insert form by function

$commands[] = ajax_command_html('.some-class', $form);

return array('#type' => 'ajax', '#commands' => $commands);

Forms are being inserted correctly, but when the form is submitted, all except the first one redirect to the technical URL - /system/ajax

I need all forms to be submitted correctly. I was sending each form separately to a separate selector - it works, but this solution doesn't seem right


问:
await with .then behavior
I'm attempting to update a MongoDB collection and store the updated value in the session. However, the value of "user" stored in the session is the "old" value (i.e. the value to be overwritten, not the new value, as desired). I started off like this:

```<code>const user = await db.findByIdAndUpdate(_id, {key1: value1, key2: value2})

if (user) {
    console.log(`User:${user}`);
    req.session.tempUser = user;
    res.redirect(`/routeA`);

} else {
    console.log(`No Users was found`);
    console.log(`Error:${error}`);
    res.redirect(`/routeB`);
}
</code>```

... then figured that the if-else code was most probably running before the DB had completed its update, which seemed like a reasonable explanation for why I was getting the old value of "user". Then I wrapped the if-else code inside a .then and .catch like this:

```<code>await db.findByIdAndUpdate(_id, {key1: value1, key2: value2})

    .then ((user) => {
        console.log(`User:${user}`);
        req.session.tempUser = user;
        return res.redirect(`/routeA`);
    })

    .catch ((error) => {
        console.log(`No User was found`);
        console.log(`Error:${error}`);
        return res.redirect(`/routeB`);
    });
</code>```

... believing that the code inside the .then would not execute until the DB had completed its operation. However, I'm getting the same result, i.e. the value of user in the session is the old value of user and not the updated (new) value.

Is the code inside the .then waiting for the DB to complete its operation before executing? Perhaps it is, and the behavior I'm experiencing is the expected behavior for Mongoose? (i.e. "user" is always the current value not the updated value, following a "findByIdAndUpdate").

Title: await with .then behavior

Body:
I'm attempting to update a MongoDB collection and store the updated value in the session. However, the value of "user" stored in the session is the "old" value (i.e. the value to be overwritten, not the new value, as desired). I started off like this:

const user = await db.findByIdAndUpdate(_id, {key1: value1, key2: value2})

if (user) {
    console.log(`User:${user}`);
    req.session.tempUser = user;
    res.redirect(`/routeA`);

} else {
    console.log(`No Users was found`);
    console.log(`Error:${error}`);
    res.redirect(`/routeB`);
}

... then figured that the if-else code was most probably running before the DB had completed its update, which seemed like a reasonable explanation for why I was getting the old value of "user". Then I wrapped the if-else code inside a .then and .catch like this:

await db.findByIdAndUpdate(_id, {key1: value1, key2: value2})

    .then ((user) => {
        console.log(`User:${user}`);
        req.session.tempUser = user;
        return res.redirect(`/routeA`);
    })

    .catch ((error) => {
        console.log(`No User was found`);
        console.log(`Error:${error}`);
        return res.redirect(`/routeB`);
    });

... believing that the code inside the .then would not execute until the DB had completed its operation. However, I'm getting the same result, i.e. the value of user in the session is the old value of user and not the updated (new) value.

Is the code inside the .then waiting for the DB to complete its operation before executing? Perhaps it is, and the behavior I'm experiencing is the expected behavior for Mongoose? (i.e. "user" is always the current value not the updated value, following a "findByIdAndUpdate").


问:
Is it possible to interact with PC hardware with Python?
There are some libraries such as CircuitPython that allow programmers to interact with Arduinos but can one control PC hardware such as the keyboard, usb ports, mouse etc using python?

I have explored various websites but they all focus on controlling Arduinos and Pyboards. I have also tried using the Linux Kernel API (kernel_ffi) but it seems impossible to make a cross-platform script with it.


问:
Multi producer multi consumer wait free ring buffer
I came across this statement while I was reading a paper on a queue implementation in C++ :

For a design to be wait-free, a thread must be able to complete its operation in a finite amount of time. If a given thread cannot complete its operation, there is not system-wide progress. Without the progress assurance scheme, our algorithm may encounter a rare condition in which threads starve. With larger ring buffer sizes this possibility can be further reduced. This is because the larger capacity increases the number of operations between a given enqueue or a given dequeue making it less likely for threads to compete for the same buffer index

How come more number of operations between enqueue or dequeue will make less likely for threads to compete for same buffer index?

Link to the  paper: https://www.osti.gov/servlets/purl/1531271

PS. Not sure if this is the right place to ask.


问:
using Gstreamer i am loopback the dmic to speaker the sound is good but when i recorded that mic and play that time sound is not good
i am using gst-launch 1.0

i wanted to record raw file using the gstreamer and also wanted to play raw file using gstreamer.
put the command using which i am testing the dmic. if i recorded file in 1x speed but when i play it plays in 0.25x speed.

using this command i am loopback the dmic to speker

```<code>gst-launch-1.0 alsasrc device=dmic ! audio/x-raw,format=S32LE,rate=48000 !  volume volume=5  !  alsasink device=hdmi_out
</code>```

and i record the dmic using this command

```<code>gst-launch-1.0 alsasrc device=dmic ! audio/x-raw,format=S32LE,rate=48000 !  volume volume=5  !  filesink location=test.raw
</code>```

i don't know how to play raw file using GStreamer so i converted this raw file into wav and then play
using this command i converted raw to wav

```<code>ffmpeg -f s32le -y -ar 48000 -ac 1 -i test.raw -fflags +bitexact -flags:v +bitexact -flags:a +bitexact -ar 48000 -ac 1 -c:a pcm_s32le test.wav
</code>```

and then play file using this command

```<code>gst-launch-1.0 filesrc location=test.wav ! wavparse ! audioconvert ! audioresample ! alsasink device=hdmi_out
</code>```

now the output is coming from the speaker is very slow in bitrate (like recorded file in 1x speed but when i play it plays in 0.25x speed)

Body:
i am using gst-launch 1.0

i wanted to record raw file using the gstreamer and also wanted to play raw file using gstreamer.
put the command using which i am testing the dmic. if i recorded file in 1x speed but when i play it plays in 0.25x speed.

using this command i am loopback the dmic to speker

gst-launch-1.0 alsasrc device=dmic ! audio/x-raw,format=S32LE,rate=48000 !  volume volume=5  !  alsasink device=hdmi_out

and i record the dmic using this command

gst-launch-1.0 alsasrc device=dmic ! audio/x-raw,format=S32LE,rate=48000 !  volume volume=5  !  filesink location=test.raw

i don't know how to play raw file using GStreamer so i converted this raw file into wav and then play
using this command i converted raw to wav

ffmpeg -f s32le -y -ar 48000 -ac 1 -i test.raw -fflags +bitexact -flags:v +bitexact -flags:a +bitexact -ar 48000 -ac 1 -c:a pcm_s32le test.wav

and then play file using this command

gst-launch-1.0 filesrc location=test.wav ! wavparse ! audioconvert ! audioresample ! alsasink device=hdmi_out

now the output is coming from the speaker is very slow in bitrate (like recorded file in 1x speed but when i play it plays in 0.25x speed)


问:
"Error displaying widget: model not found" is shown instead of the plot when opening an existing Python notebook
I use '%matplotlib widget' to make plots and it just works fine on Jupyter lab (Python).
However, when I open the saved notebook, I see 'Loading widget...' then several seconds later, 'Error displaying widget: model not found' is shown instead of every plot.
Please help me solving the problem. Thank you.

The below is code for reproducing the problem.

```<code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib widget

x = np.linspace(-4, 4, 100)
y = np.sin(x)

plt.plot(x,y)
</code>```

I updated jupyter lab, ipympl and ipywidgets, but nothing changed.

The followings are version numbers after update.

jupyterlab                3.5.2

ipympl                    0.9.2

ipywidgets                7.6.5

python                    3.9.13

matplotlib                3.5.3

Body:
I use '%matplotlib widget' to make plots and it just works fine on Jupyter lab (Python).
However, when I open the saved notebook, I see 'Loading widget...' then several seconds later, 'Error displaying widget: model not found' is shown instead of every plot.
Please help me solving the problem. Thank you.

The below is code for reproducing the problem.

import numpy as np
import matplotlib.pyplot as plt
%matplotlib widget

x = np.linspace(-4, 4, 100)
y = np.sin(x)

plt.plot(x,y)

I updated jupyter lab, ipympl and ipywidgets, but nothing changed.

The followings are version numbers after update.

jupyterlab                3.5.2

ipympl                    0.9.2

ipywidgets                7.6.5

python                    3.9.13

matplotlib                3.5.3


问:
Monaco-editor press arrow keys once but the cursor move multiple digits
I create a app similar to postman, and the body part uses monaco-editor, When the method is switched every time, a new monaco-editor will be created, and the content of the new editor is empty, but every time you switch, the cursor will move by one more digit when you press the arrow key.

For example, When I enter the post method page for the first time, the cursor moves normally in the editor, but I switch the patch method and then switch the body method, press the arrow key once and the cursor moves three digits.

Here is create monaco-editor code，This method is called every time the page is switched.

```<code>function createEditor(ele, value, type, showBodyHistory) {
    require(['vs/editor/editor.main'], function () {

        let customTheme = themeType === 'light' ? light_themeData : dark_themeData;
        monaco.editor.defineTheme('customTheme', customTheme);
        monaco.editor.setTheme('customTheme');
        let language = type === 'delete' ? 'text' : 'json';
        let readonly = type === 'delete';

        let editor = monaco.editor.create(ele, {
            value: value,
            language: language,
            automaticLayout: true,
            theme: 'customTheme',
            readOnly: readonly,
            minimap: {
                enabled: false,
            },
            renderLineHighlight: 'none',
            // lineNumbers: 'off',
        });

        if (type === 'body') {
            body_params['body'].currentValue = editor.getValue();
            editor.onDidBlurEditorText(() => {
                body_params['body'].currentValue = editor.getValue();
                body_params['body'].value = editor.getValue();
            });
        }
    });
}

</code>```

method switch image
method image

I tried the dispose method but it didn’t solve it. I don’t know if I have to clear the cursor before creating it every time.

Body:
I create a app similar to postman, and the body part uses monaco-editor, When the method is switched every time, a new monaco-editor will be created, and the content of the new editor is empty, but every time you switch, the cursor will move by one more digit when you press the arrow key.

For example, When I enter the post method page for the first time, the cursor moves normally in the editor, but I switch the patch method and then switch the body method, press the arrow key once and the cursor moves three digits.

Here is create monaco-editor code，This method is called every time the page is switched.

function createEditor(ele, value, type, showBodyHistory) {
    require(['vs/editor/editor.main'], function () {

        let customTheme = themeType === 'light' ? light_themeData : dark_themeData;
        monaco.editor.defineTheme('customTheme', customTheme);
        monaco.editor.setTheme('customTheme');
        let language = type === 'delete' ? 'text' : 'json';
        let readonly = type === 'delete';

        let editor = monaco.editor.create(ele, {
            value: value,
            language: language,
            automaticLayout: true,
            theme: 'customTheme',
            readOnly: readonly,
            minimap: {
                enabled: false,
            },
            renderLineHighlight: 'none',
            // lineNumbers: 'off',
        });

        if (type === 'body') {
            body_params['body'].currentValue = editor.getValue();
            editor.onDidBlurEditorText(() => {
                body_params['body'].currentValue = editor.getValue();
                body_params['body'].value = editor.getValue();
            });
        }
    });
}

method switch image
method image

I tried the dispose method but it didn’t solve it. I don’t know if I have to clear the cursor before creating it every time.


问:
Docker-compose replicated service with different environment variables
Is there a way to start up multiple instances of the same service, but each with a different environment variable?  I have a docker-compose yml with a service that ingests a datastream from a remote source, but I'd like to be able to run this multiple times, but each one pointing to a different host/ip.  I thought something like:

```<code>  the_processor:
    build:
      dockerfile: Dockerfile
      context: ./processing
    container_name: the_processor_${INPUT_HOST}
</code>```

might work, but all that does restart the_processor container with the different variable.

Body:
Is there a way to start up multiple instances of the same service, but each with a different environment variable?  I have a docker-compose yml with a service that ingests a datastream from a remote source, but I'd like to be able to run this multiple times, but each one pointing to a different host/ip.  I thought something like:

  the_processor:
    build:
      dockerfile: Dockerfile
      context: ./processing
    container_name: the_processor_${INPUT_HOST}

might work, but all that does restart the_processor container with the different variable.


问:
getting problem in transposing an 2D array
i have written a code to transpose an aray it works when i took small arrays dimensions like 33 but when i took array size 45 it gives me array out of bound error.i am a beginner.

```<code>import java.util.*;
import java.lang.*;
public class Transpose {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.print("enter rows and cols: ");
        int r = sc.nextInt();
        int c = sc.nextInt();
        long a[][] = new long [r][c];
        long transpose[][] = new long [r][c];

        System.out.print("enter"+" " +r*c+" "+"elements");
        for(int i =0; i < a.length; i++){
            for(int j = 0; j < a[i].length; j++){
                a[i][j] = sc.nextInt();
            }
        }

        for(int i =0; i < a.length; i++){
            for(int j = 0; j < a[i].length; j++){
                System.out.print(" "+a[i][j] + " ");
            }
            System.out.println();
        }

        for(int i = 0; i < a.length ; i++){
            for(int j = 0; j < a[i].length; j++){
                long temp = a[i][j];
                transpose[i][j] = a[j][i];
                a[i][j] = temp;
            }
        }

        System.out.println();
        for(int i =0; i < transpose.length; i++){
            for(int j = 0; j < transpose[i].length; j++){
                System.out.print(" "+transpose[i][j] + " ");
            }
            System.out.println();
        }
    }
}

</code>```

Body:
i have written a code to transpose an aray it works when i took small arrays dimensions like 33 but when i took array size 45 it gives me array out of bound error.i am a beginner.

import java.util.*;
import java.lang.*;
public class Transpose {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.print("enter rows and cols: ");
        int r = sc.nextInt();
        int c = sc.nextInt();
        long a[][] = new long [r][c];
        long transpose[][] = new long [r][c];

        System.out.print("enter"+" " +r*c+" "+"elements");
        for(int i =0; i < a.length; i++){
            for(int j = 0; j < a[i].length; j++){
                a[i][j] = sc.nextInt();
            }
        }

        for(int i =0; i < a.length; i++){
            for(int j = 0; j < a[i].length; j++){
                System.out.print(" "+a[i][j] + " ");
            }
            System.out.println();
        }

        for(int i = 0; i < a.length ; i++){
            for(int j = 0; j < a[i].length; j++){
                long temp = a[i][j];
                transpose[i][j] = a[j][i];
                a[i][j] = temp;
            }
        }

        System.out.println();
        for(int i =0; i < transpose.length; i++){
            for(int j = 0; j < transpose[i].length; j++){
                System.out.print(" "+transpose[i][j] + " ");
            }
            System.out.println();
        }
    }
}


问:
Handle NaN in ksqlDB
Is there any way to handle NaN value in ksqlDB? For example, how can I remove rows whose value are NaN ?

I cannot find any functions related to NaN like isNaN. As far as I know the only way is to create an udf by myself.

Title: Handle NaN in ksqlDB


问:
How to convert dict in list to dict in python?
I have this list below

```<code>my_list =
[
    {
    "id": "841",
    "category": "category1",
    "nutrients": [
        {
        "name": "B12",
        "description": "good"
        },
        {
        "name": "A",
        "description": "eyes"
        }
    ]
    "status": "yes_survey"
    }
]
</code>```

and I want this dictionary below
(I want to remove just outside [ ] sign...)

```<code>my_ dict =
   {
    "id": "841",
    "category": "category1",
    "nutrients": [
        {
        "name": "B12",
        "description": "good"
        },
        {
        "name": "A",
        "description": "eyes"
        }
    ]
    "status": "yes_survey"
    }
</code>```

How can I do it? I tried dict() method but It doesn't work.

Body:
I have this list below

my_list =
[
    {
    "id": "841",
    "category": "category1",
    "nutrients": [
        {
        "name": "B12",
        "description": "good"
        },
        {
        "name": "A",
        "description": "eyes"
        }
    ]
    "status": "yes_survey"
    }
]

and I want this dictionary below
(I want to remove just outside [ ] sign...)

my_ dict =
   {
    "id": "841",
    "category": "category1",
    "nutrients": [
        {
        "name": "B12",
        "description": "good"
        },
        {
        "name": "A",
        "description": "eyes"
        }
    ]
    "status": "yes_survey"
    }

How can I do it? I tried dict() method but It doesn't work.


问:
useSWR is returning undefined when even though correct items print next js
I am trying to run a useSWR hook to fetch my firestore data. When I run it, it runs the fetcher function because the console.log() shows the correct item. When I try to print the data, however, it returns undefined. Is there a way to fix this? I am attaching all the code for the error.

```<code>const fetcher = async (location) => {
    const q = query(collection(db, location));
    const snapshot = await getDocs(q)
    let retArr = []
    snapshot.forEach(doc => {
        console.log(doc.data())
        retArr.push(doc.data())
    })
    return retArr
}

 function getLoc() {
     if (currentUser) {
        return 'users/' + currentUser.uid + '/userInvestments'
     } else {
        return 'users/TestDocumentForDatabase/userInvestments'
     };
 }

 const loc = getLoc();
 console.log(loc)

 const { data, error } = useSWR(
    loc,
    fetcher,
    {
       refreshInterval: 1000,
    }
 );

 console.log(data)
</code>```

getLoc gets the location for the query, and then the fetcher is used to grab and return an array of all of the documents. This is returning undefined. I would appreciate any assistance.

Body:
I am trying to run a useSWR hook to fetch my firestore data. When I run it, it runs the fetcher function because the console.log() shows the correct item. When I try to print the data, however, it returns undefined. Is there a way to fix this? I am attaching all the code for the error.

const fetcher = async (location) => {
    const q = query(collection(db, location));
    const snapshot = await getDocs(q)
    let retArr = []
    snapshot.forEach(doc => {
        console.log(doc.data())
        retArr.push(doc.data())
    })
    return retArr
}

 function getLoc() {
     if (currentUser) {
        return 'users/' + currentUser.uid + '/userInvestments'
     } else {
        return 'users/TestDocumentForDatabase/userInvestments'
     };
 }

 const loc = getLoc();
 console.log(loc)

 const { data, error } = useSWR(
    loc,
    fetcher,
    {
       refreshInterval: 1000,
    }
 );

 console.log(data)

getLoc gets the location for the query, and then the fetcher is used to grab and return an array of all of the documents. This is returning undefined. I would appreciate any assistance.