问:
How to generate large word count file in Spark?
I want to generate 10 million lines’ wordcount file for performance test(each line has the same sentence). But I have no idea about how to code it.

You can give me an example code, and save file in HDFS directly.

答:
You can do it by joining the 2 DFs as below,
Also find the code explanation inline. </p>

```<code>import org.apache.spark.sql.SaveMode

object GenerateTenMils {

  def main(args: Array[String]): Unit = {
    val spark = Constant.getSparkSess
    spark.conf.set("spark.sql.crossJoin.enabled","true") // Enable cross join
    import spark.implicits._

    //Create a DF with your sentence
    val df = List("each line has the same sentence").toDF

    //Create another Dataset with 10000000 records
    spark.range(10000000)
      .join(df)    // Cross Join the dataframes
      .coalesce(1)  // Output to a single file
      .drop("id")       // Drop the extra column
      .write
      .mode(SaveMode.Overwrite)
      .text("src/main/resources/tenMils") // Write as text file
  }

}

</code>```

Body:
You can do it by joining the 2 DFs as below,
Also find the code explanation inline.

import org.apache.spark.sql.SaveMode

object GenerateTenMils {

  def main(args: Array[String]): Unit = {
    val spark = Constant.getSparkSess
    spark.conf.set("spark.sql.crossJoin.enabled","true") // Enable cross join
    import spark.implicits._

    //Create a DF with your sentence
    val df = List("each line has the same sentence").toDF

    //Create another Dataset with 10000000 records
    spark.range(10000000)
      .join(df)    // Cross Join the dataframes
      .coalesce(1)  // Output to a single file
      .drop("id")       // Drop the extra column
      .write
      .mode(SaveMode.Overwrite)
      .text("src/main/resources/tenMils") // Write as text file
  }

}


来源: stackexchange

问:
TouchableOpacity behaves weird
```<code>    <View
        style={{
          flex: 1,
          width: BannerWidth,
          height: (deviceHeight * 25) / 100,
          marginBottom: 40,
          backgroundColor: theme.colors.batiLacivert,
        }}>
         <TouchableOpacity onPress={() => Actions.portfoy()}>
          <View
            style={{
              width: 48,
              height: 60,
              left: 0,
              top: 50,
            }}>
            <Image
              style={{
                width: 48,
                height: 60,
                left: 40,
                bottom: -30,
                position: 'absolute',
              }}
              source={require('../../assets/yuzdeler/0yuzde_yeni.png')}
            />
            <Text
              style={{
                position: 'absolute',
                color: 'black',
                left: 47,
                bottom: 0,
                fontSize: 20,
              }}>
              %{this.state.anasayfaBilgiler.Performans}
            </Text>
          </View>
        </TouchableOpacity>
        </View>
</code>```

I have this code in my project. I use position: absolute to position my shield icon on a View, and I wrapped it into a TouchableOpacity to press it and go to another page. But when I press on the shield, Nothing happens, But when I press the View on the background, It applies the code, it should have done it on the shield...How can I fix this?

Edit: Now it works when the Shield icon on the background View, but when I position it in the bottom, the overflow area of the icon doesnt work just upper half takes the click. I need it to work all over the image

This area -with blue color - doesn't click:

答: Make sure you have imported TouchableOpacity from react-native and not react-native-gesture-handler

ContentLicense: CC BY-SA 4.0

Title: TouchableOpacity behaves weird

Body:
    <View
        style={{
          flex: 1,
          width: BannerWidth,
          height: (deviceHeight * 25) / 100,
          marginBottom: 40,
          backgroundColor: theme.colors.batiLacivert,
        }}>
         <TouchableOpacity onPress={() => Actions.portfoy()}>
          <View
            style={{
              width: 48,
              height: 60,
              left: 0,
              top: 50,
            }}>
            <Image
              style={{
                width: 48,
                height: 60,
                left: 40,
                bottom: -30,
                position: 'absolute',
              }}
              source={require('../../assets/yuzdeler/0yuzde_yeni.png')}
            />
            <Text
              style={{
                position: 'absolute',
                color: 'black',
                left: 47,
                bottom: 0,
                fontSize: 20,
              }}>
              %{this.state.anasayfaBilgiler.Performans}
            </Text>
          </View>
        </TouchableOpacity>
        </View>

I have this code in my project. I use position: absolute to position my shield icon on a View, and I wrapped it into a TouchableOpacity to press it and go to another page. But when I press on the shield, Nothing happens, But when I press the View on the background, It applies the code, it should have done it on the shield...How can I fix this?

Edit: Now it works when the Shield icon on the background View, but when I position it in the bottom, the overflow area of the icon doesnt work just upper half takes the click. I need it to work all over the image

This area -with blue color - doesn't click:


问:
Flutter - MultiProvider (ChangeNotifierProvider) doesn't work
ChangeNotifierProvider doesn't work! I don't know what is the problem.
Could anyone tell me what's wrong with this code?
Thank you

I want to pass the test value  to the next page.

Here is the main function and the providers

```<code>void main() {
runApp(
MultiProvider(
providers:[
ChangeNotifierProvider<ProductsNotifier>(create:(context)=> ProductsNotifier()),
//  second provider...
],
child:MaterialApp( home: MyApp())
)
);
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Provider
return Scaffold(
  appBar: AppBar(
    title: Text('Test'),
  ),
  body: Container(
    child:RaisedButton(
    onPressed: (){
    ProductsNotifier obj = new ProductsNotifier();
    obj.testFun();
      Navigator.push(context,
            MaterialPageRoute(builder: (context) => NextPage()),
        );
      },
      child: Text('GO TO THE NEXT PAGE'),
    )
   ),
  );
 }
}
</code>```

Next Page:

```<code>class NextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
 var txt = Provider.of<ProductsNotifier>(context);

return Scaffold(
  appBar: AppBar(
    title: Text('Next Page'),
  ),
  body: Container(
    child: Text(txt.test.toString()),
  ),
);
}
}
</code>```

Class ProductsNotifier

```<code>class ProductsNotifier with ChangeNotifier{
String _test ;
String get test => _test;

 void testFun()  {
 _test = "DONE!";
  notifyListeners();
 }
}
</code>```

答:
First remove this line:

```<code>ProductsNotifier obj = new ProductsNotifier();
</code>```

It is already created here:

```<code>ChangeNotifierProvider<ProductsNotifier>(create:(context)=> ProductsNotifier()),
</code>```

Then

```<code>class ProductsNotifier with ChangeNotifier{
</code>```

replace with:

```<code>class ProductsNotifier extends ChangeNotifier{
</code>```

Body:
ChangeNotifierProvider doesn't work! I don't know what is the problem.
Could anyone tell me what's wrong with this code?
Thank you

I want to pass the test value  to the next page.

Here is the main function and the providers

void main() {
runApp(
MultiProvider(
providers:[
ChangeNotifierProvider<ProductsNotifier>(create:(context)=> ProductsNotifier()),
//  second provider...
],
child:MaterialApp( home: MyApp())
)
);
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Provider
return Scaffold(
  appBar: AppBar(
    title: Text('Test'),
  ),
  body: Container(
    child:RaisedButton(
    onPressed: (){
    ProductsNotifier obj = new ProductsNotifier();
    obj.testFun();
      Navigator.push(context,
            MaterialPageRoute(builder: (context) => NextPage()),
        );
      },
      child: Text('GO TO THE NEXT PAGE'),
    )
   ),
  );
 }
}

Next Page:

class NextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
 var txt = Provider.of<ProductsNotifier>(context);

return Scaffold(
  appBar: AppBar(
    title: Text('Next Page'),
  ),
  body: Container(
    child: Text(txt.test.toString()),
  ),
);
}
}

Class ProductsNotifier

class ProductsNotifier with ChangeNotifier{
String _test ;
String get test => _test;

 void testFun()  {
 _test = "DONE!";
  notifyListeners();
 }
}

Body:
First remove this line:

ProductsNotifier obj = new ProductsNotifier();

It is already created here:

ChangeNotifierProvider<ProductsNotifier>(create:(context)=> ProductsNotifier()),

Then

class ProductsNotifier with ChangeNotifier{

replace with:

class ProductsNotifier extends ChangeNotifier{


问:
Sequelize – order by values presence
I have a model that includes fields like price_from, price_to and created_at.

Right now I'm querying it like this:

```<code>Model.findAll({ order: [['created_at', 'DESC']] });
</code>```

I would like to add another order query, so records that do not have both price_from and price_to would be returned at the end, but without sorting by those prices.

Is there a way it can be achieved in Sequelize?

答:
You can do a CASE WHEN statement using sequelize.literal, as the following:

```<code>Model.findAll({ order: [
    ['created_at', 'DESC'],
    [sequelize.literal('CASE WHEN price_from IS NULL AND price_to IS NULL THEN 1 ELSE 0 END'), 'DESC']
] });
</code>```

May your fields are 0 or empty so, you may adapt the CASE comparison.

Title: Sequelize – order by values presence

Body:
I have a model that includes fields like price_from, price_to and created_at.

Right now I'm querying it like this:

Model.findAll({ order: [['created_at', 'DESC']] });

I would like to add another order query, so records that do not have both price_from and price_to would be returned at the end, but without sorting by those prices.

Is there a way it can be achieved in Sequelize?

Body:
You can do a CASE WHEN statement using sequelize.literal, as the following:

Model.findAll({ order: [
    ['created_at', 'DESC'],
    [sequelize.literal('CASE WHEN price_from IS NULL AND price_to IS NULL THEN 1 ELSE 0 END'), 'DESC']
] });

May your fields are 0 or empty so, you may adapt the CASE comparison.


问:
How do I print out an error message when the user enters a floating number or characters in C language?
I'm new to programming.I wanted to create a game such that the user guesses a number between 0 and 10.However,I want to print an error message when the user enters a floating number such as 7.5 or a character or a number out of range such as 11 or -5.How do I do that ?</p>

```<code>int main()
{
    int answer,randomNumber;
    int correct = 0;
    int tries = 0;
    char again ;
    srand(time(NULL));
    do{
           randomNumber = rand() % 10;
           printf("Guess a number between 0 and 10:\n");
           while(correct ==0){
                while(scanf(" %d",&answer)!=1){
                    printf("Wrong input.\n");
                    scanf(" %d",&answer);
            }
            if(answer<0 || answer>10){
                printf("Invalid input.Enter a number between 0 and 10.\n");
                continue;
            }
            if(answer==randomNumber){
                printf("Congratulations..%d is the correct number.\n",answer);
                tries ++;
                correct = 1;
            }else if(answer > randomNumber){
                printf("Choose a lower number.\n");
                tries++;
            }else if (answer<randomNumber){
                printf("Choose a bigger number.\n");
                tries ++;
            }else{
                printf("Wrong input.Try again..\n");
            }
        }printf("Do you want to play again ? (Y/N):\n");
        scanf(" %c",&again);
        again = toupper(again);
        while(again!='N' && again!='Y'){
            printf("Invalid input.Please type Y or N.\n");
            scanf(" %c",&again);
            again = toupper(again);
        }
    }while(again != 'N');

    return 0;
    }
</code>```

答:
Consider using fgets to capture input.

strtol can be used to parse input. If last does not point to the newline at the end of input, there are unprocessed characters.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>

int main ( void) {
    char input[100] = "";
    int answer,randomNumber;
    int good = 0;
    int correct = 0;
    int tries = 0;
    char again ;
    srand ( time ( NULL));
    do{
        randomNumber = rand() % 10;
        printf ( "Guess a number between 0 and 10:\n");
        while ( correct == 0) {
            do {
                good = 1;
                char *last = NULL;
                if ( fgets ( input, sizeof input, stdin)) {
                    answer = strtol ( input, &last, 10);
                    if ( '\n' != *last || last == input) {
                        printf ( "Wrong input.\n");
                            good = 0;
                    }
                    else {
                        if ( answer < 0 || answer > 10){
                            printf ( "Invalid input.Enter a number between 0 and 10.\n");
                            good = 0;
                        }
                    }
                }
                else {
                    fprintf ( stderr, "fgets EOF\n");
                    exit ( EXIT_FAILURE);
                }
            } while( ! good);
            if (answer == randomNumber) {
                printf ( "Congratulations..%d is the correct number.\n",answer);
                tries ++;
                correct = 1;
            } else if ( answer > randomNumber) {
                printf ( "Choose a lower number.\n");
                tries++;
            } else if ( answer < randomNumber) {
                printf ( "Choose a bigger number.\n");
                tries ++;
            } else{
                printf ( "Wrong input.Try again..\n");
            }
        }
        correct = 0;
        printf ( "Do you want to play again ? (Y/N):\n");
        do {
            if ( fgets ( input, sizeof input, stdin)) {
            }
            again = toupper ( (unsigned char)input[0]);
            if ( again != 'N' && again != 'Y') {
                printf ( "Invalid input.Please type Y or N.\n");
            }
        } while ( again != 'N' && again != 'Y');
    } while ( again != 'N');

    return 0;
}
</code>```

Body:
I'm new to programming.I wanted to create a game such that the user guesses a number between 0 and 10.However,I want to print an error message when the user enters a floating number such as 7.5 or a character or a number out of range such as 11 or -5.How do I do that ?

int main()
{
    int answer,randomNumber;
    int correct = 0;
    int tries = 0;
    char again ;
    srand(time(NULL));
    do{
           randomNumber = rand() % 10;
           printf("Guess a number between 0 and 10:\n");
           while(correct ==0){
                while(scanf(" %d",&answer)!=1){
                    printf("Wrong input.\n");
                    scanf(" %d",&answer);
            }
            if(answer<0 || answer>10){
                printf("Invalid input.Enter a number between 0 and 10.\n");
                continue;
            }
            if(answer==randomNumber){
                printf("Congratulations..%d is the correct number.\n",answer);
                tries ++;
                correct = 1;
            }else if(answer > randomNumber){
                printf("Choose a lower number.\n");
                tries++;
            }else if (answer<randomNumber){
                printf("Choose a bigger number.\n");
                tries ++;
            }else{
                printf("Wrong input.Try again..\n");
            }
        }printf("Do you want to play again ? (Y/N):\n");
        scanf(" %c",&again);
        again = toupper(again);
        while(again!='N' && again!='Y'){
            printf("Invalid input.Please type Y or N.\n");
            scanf(" %c",&again);
            again = toupper(again);
        }
    }while(again != 'N');

    return 0;
    }

Body:
Consider using fgets to capture input.

strtol can be used to parse input. If last does not point to the newline at the end of input, there are unprocessed characters.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>

int main ( void) {
    char input[100] = "";
    int answer,randomNumber;
    int good = 0;
    int correct = 0;
    int tries = 0;
    char again ;
    srand ( time ( NULL));
    do{
        randomNumber = rand() % 10;
        printf ( "Guess a number between 0 and 10:\n");
        while ( correct == 0) {
            do {
                good = 1;
                char *last = NULL;
                if ( fgets ( input, sizeof input, stdin)) {
                    answer = strtol ( input, &last, 10);
                    if ( '\n' != *last || last == input) {
                        printf ( "Wrong input.\n");
                            good = 0;
                    }
                    else {
                        if ( answer < 0 || answer > 10){
                            printf ( "Invalid input.Enter a number between 0 and 10.\n");
                            good = 0;
                        }
                    }
                }
                else {
                    fprintf ( stderr, "fgets EOF\n");
                    exit ( EXIT_FAILURE);
                }
            } while( ! good);
            if (answer == randomNumber) {
                printf ( "Congratulations..%d is the correct number.\n",answer);
                tries ++;
                correct = 1;
            } else if ( answer > randomNumber) {
                printf ( "Choose a lower number.\n");
                tries++;
            } else if ( answer < randomNumber) {
                printf ( "Choose a bigger number.\n");
                tries ++;
            } else{
                printf ( "Wrong input.Try again..\n");
            }
        }
        correct = 0;
        printf ( "Do you want to play again ? (Y/N):\n");
        do {
            if ( fgets ( input, sizeof input, stdin)) {
            }
            again = toupper ( (unsigned char)input[0]);
            if ( again != 'N' && again != 'Y') {
                printf ( "Invalid input.Please type Y or N.\n");
            }
        } while ( again != 'N' && again != 'Y');
    } while ( again != 'N');

    return 0;
}


问:
Does dividing float by int always give float? C++
I been programming on C and C++ for some time, and was always sure that double dividing int gives double, or double dividing int also give double (only int by int gives int) and same with adding. I was doing my assignment and was sure that 1 + (f*f + 10) / k, where f is double and k is int would always return double.
I was using g++ -std=gnu++11 command on mac (so it's clang compiler probably) and I got tests passed (I indeed got float number as a result), but my teacher says that it not for sure that it will be float (he is using windows). Is that behavior platform specific? Is there any C++ standard that describes double on int division? Thank you!
My code:

```<code>#include <iostream>
using namespace std;

int main() {
    int  N;
    double f, P = 0;
    cin >> N >> f;
    for (double k = 1; k <= N; k++){
      P += 1 + (f*f + 10) / k;
    }
    cout << P;
    return 0;
}
</code>```

答:
As you can read here:

[...] if either operand is double, the other operand is converted to double

[...] if either operand is float, the other operand is converted to float

so it's guaranteed by the standard that that operation will gives you back a float

Body:
I been programming on C and C++ for some time, and was always sure that double dividing int gives double, or double dividing int also give double (only int by int gives int) and same with adding. I was doing my assignment and was sure that 1 + (f*f + 10) / k, where f is double and k is int would always return double.
I was using g++ -std=gnu++11 command on mac (so it's clang compiler probably) and I got tests passed (I indeed got float number as a result), but my teacher says that it not for sure that it will be float (he is using windows). Is that behavior platform specific? Is there any C++ standard that describes double on int division? Thank you!
My code:

#include <iostream>
using namespace std;

int main() {
    int  N;
    double f, P = 0;
    cin >> N >> f;
    for (double k = 1; k <= N; k++){
      P += 1 + (f*f + 10) / k;
    }
    cout << P;
    return 0;
}


问:
How Can I fix a header of a specified height in the top without adding top property to the sibling section to make it visible?
I have a small problem, I am working on a project, in this project everything is separated literally, I am working only on a header section without touching anything else, I can how the header is displayed in all the project after deploying the header only, meaning ? I don't have access to touch the body, only the heeader.

I have to set the Header to fixed, I was doing this before already but they were my personnal projects, I give the header a height and then the section next to it I positionate it relatively and add top property to it so the header and section can be both visible, the header does not have to cover the sectiion or part of it.

let's put some code :

```<code><body>

    <header></header>
    <section class="first_section"></section>
    <section></section>

</body>
</code>```

and the css like that :

```<code>header {  position :fixed; height: 40px; }
section { position : relative; }
.first_section { top: 40px }
</code>```

Now, I can't do that, I can't touch the section or add style to them, why ? because they are very dynamic, the header can be included in multiple sites, that means that it is not proper to touch all sections or cover them one by one.

So to fix this, I tried this in html :

```<code><body>

    <header>
       <div class="header"></div>
    </header>
    <section class="first_section"></section>
    <section></section>

</body>
</code>```

Now, I have passed all the css properties from header to the div with header classname, and header now is like this :

```<code>header {  position :relative; width: 100%; height: 40px; }
.header { position: fixed; // many others properties }
section { position : relative; }
.first_section { top: 40px }
</code>```

But it is not working ? why ? I don't know, but when inspecting the height property in the header, it is not set, the header have width and height properties in css file, but when I Inspect I see that the height is 0, I think because it has a fixed child, but I don't know how to fix it.

Any help would be much appreciated.

答:
One solution could be to create 2 divs in your header : a fixed one with the real header, and another just to keep the space so nothing will be covered:

```<code><header>
  <div class="header trueHeader"></div>
  <div class="header"></div>
</header>
</code>```

and

```<code>.header {
  height: 50px;
  width: 100vw;
}

.trueHeader {
  position: fixed;
  background-color: #f00;
}
</code>```

Example: https://jsfiddle.net/jhsLngr4/1/

Body:
I have a small problem, I am working on a project, in this project everything is separated literally, I am working only on a header section without touching anything else, I can how the header is displayed in all the project after deploying the header only, meaning ? I don't have access to touch the body, only the heeader.

I have to set the Header to fixed, I was doing this before already but they were my personnal projects, I give the header a height and then the section next to it I positionate it relatively and add top property to it so the header and section can be both visible, the header does not have to cover the sectiion or part of it.

let's put some code :

and the css like that :

header {  position :fixed; height: 40px; }
section { position : relative; }
.first_section { top: 40px }

Now, I can't do that, I can't touch the section or add style to them, why ? because they are very dynamic, the header can be included in multiple sites, that means that it is not proper to touch all sections or cover them one by one.

So to fix this, I tried this in html :

Now, I have passed all the css properties from header to the div with header classname, and header now is like this :

header {  position :relative; width: 100%; height: 40px; }
.header { position: fixed; // many others properties }
section { position : relative; }
.first_section { top: 40px }

But it is not working ? why ? I don't know, but when inspecting the height property in the header, it is not set, the header have width and height properties in css file, but when I Inspect I see that the height is 0, I think because it has a fixed child, but I don't know how to fix it.

Any help would be much appreciated.

Body:
One solution could be to create 2 divs in your header : a fixed one with the real header, and another just to keep the space so nothing will be covered:

<header>
  <div class="header trueHeader"></div>
  <div class="header"></div>
</header>

and

.header {
  height: 50px;
  width: 100vw;
}

.trueHeader {
  position: fixed;
  background-color: #f00;
}

Example: https://jsfiddle.net/jhsLngr4/1/


问:
How to get this values form this data
```<code>envelope:'{"to":["reply-to-501-4455@email.ashishbhangade.com"],"from":"Tway"}'
</code>```

<p>here my object data and i want find values only 501 and 4455 (every time this values are dynamic not static values) so how to get please give me suggestion. </p>

答:
Perhaps with string.includes?

const envelope = {"to":["reply-to-501-4455@email.ashishbhangade.com"],"from":"Tway"}

console.log(
envelope.to.some(pr => pr.includes("501")),
envelope.to.some(pr => pr.includes("4455"))
)```

Title: How to get this values form this data

Body:
envelope:'{"to":["reply-to-501-4455@email.ashishbhangade.com"],"from":"Tway"}'

here my object data and i want find values only 501 and 4455 (every time this values are dynamic not static values) so how to get please give me suggestion.


问:
Using .remove in a loop in Python
I tried the following code:

```<code>arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for x in arr:
  if x > 3:
    arr.remove(x)

print(arr)
</code>```

It gives the following output:

```<code>[1, 2, 3, 5, 7, 9]
</code>```

While instead i thought it would remove from the array every element bigger than 3. Why is that? And how can i make it remove every element bigger than a certain amount?

答:
Modifying a list that you're in the process of iterating over will frequently yield unexpected results.  A better option is to create a new list:</p>

```<code>arr = [x for x in arr if x <= 3]
</code>```

Title: Using .remove in a loop in Python

Body:
I tried the following code:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for x in arr:
  if x > 3:
    arr.remove(x)

print(arr)

It gives the following output:

[1, 2, 3, 5, 7, 9]

While instead i thought it would remove from the array every element bigger than 3. Why is that? And how can i make it remove every element bigger than a certain amount?

Body:
Modifying a list that you're in the process of iterating over will frequently yield unexpected results.  A better option is to create a new list:

arr = [x for x in arr if x <= 3]


问:
API-Platform - How to update and embedded relation and persist it's id's
I have two entities,

Quote and QuoteProduct with a OneToMany Relation between.

When I perform a PUT request to update the embedded QuoteProduct relation, it always remove all items and add them, which result to generate new id's.

According to the official doc, https://api-platform.com/docs/core/serialization/#denormalization
I should be able to update a specific item by passing his id

Quote Entity

```<code><?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Ramsey\Uuid\Uuid;
use ApiPlatform\Core\Annotation\ApiResource;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ApiResource(
 *     normalizationContext={"groups"={"quote.read"}},
 *     denormalizationContext={"groups"={"quote.write"}},
 *     collectionOperations={
 *         "get"={"access_control"="is_granted('ROLE_USER')", "access_control_message"="You do not have the permission to get"},
 *         "post"={"access_control"="is_granted('ROLE_COMMERCIAL')", "access_control_message"="You do not have the permission to add"}
 *     },
 *     itemOperations={
 *         "get",
 *         "put"={"access_control"="is_granted('ROLE_COMMERCIAL')", "access_control_message"="You do not have the permission to update"},
 *         "delete"={"access_control"="is_granted('ROLE_COMMERCIAL')", "access_control_message"="You do not have the permission to delete."}
 *     },
 *     attributes={"force_eager"=false}
 * )
 * @ORM\Entity
 * @ORM\Table(name="`quotes`")
 */
class Quote
{

    public function __construct()
    {
        $this->id = Uuid::uuid4();
        $this->products = new ArrayCollection();
    }

    /**
     *
     * @ORM\Id
     * @ORM\Column(type="uuid", unique=true)
     */
    private $id;

    /**
     * @var Collection|QuoteProduct[]
     *
     * @Groups({"quote.read", "quote.write"})
     * @ORM\OneToMany(targetEntity="App\Entity\QuoteProduct", mappedBy="quote", cascade={"persist"}, orphanRemoval=true)
     * @ORM\OrderBy({"code" = "ASC"})
     */
    private $products;

    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ----------------------------------------GETTER AND SETTER------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */

    public function getId()
    {
        return $this->id;
    }

    /**
     * @return Collection|QuoteProduct[]
     */
    public function getProducts(): Collection
    {
        return $this->products;
    }

    /**
     * @param QuoteProduct $product
     * @return Quote
     */
    public function addProduct(QuoteProduct $product): self
    {
        if(false === $this->products->contains($product))
        {
            $product->setQuote($this);
            $this->products->add($product);
        }
        return $this;
    }

    /**
     * @param QuoteProduct $product
     * @return Quote
     */
    public function removeProduct(QuoteProduct $product)
    {
        if(!$this->products->contains($product))
        {
            return;
        }
        $this->products->removeElement($product);
        $product->setQuote(null);
    }

}

?>
</code>```

QuoteProduct Entity

```<code><?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Ramsey\Uuid\Uuid;
use ApiPlatform\Core\Annotation\ApiResource;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ApiResource(
 *     normalizationContext={"groups"={"quote-product.read"},"enable_max_depth"=true},
 *     denormalizationContext={"groups"={"quote-product.write"},"enable_max_depth"=true},
 *     attributes={"force_eager"=false}
 * )
 * @ORM\Entity
 * @ORM\Table(name="`quote_products`")
 */
class QuoteProduct
{

    /**
     *
     * @ORM\Id
     * @ORM\Column(type="uuid", unique=true)
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Groups({"quote-product.read", "quote-product.write", "quote.read", "quote.write"})
     *
     */
    private $code;

    /**
     * @ORM\ManyToOne(targetEntity="Quote", cascade={"persist"}, inversedBy="products")
     * @Assert\Valid
     * @Groups({"quote-product.read", "quote-product.write", "quote.read", "quote.write"})
     */
    private $quote;

    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ----------------------------------------GETTER AND SETTER------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */

    public function __construct()
    {
        $this->id = Uuid::uuid4();
    }

    public function getId()
    {
        return $this->id;
    }

    public function getQuote(): ?Quote
    {
        return $this->quote;
    }

    public function setQuote(?Quote $quote)
    {
        $this->quote = $quote;

        return $this;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function setCode(?string $code): self
    {
        $this->code = $code;

        return $this;
    }

}
</code>```

Get request to quotes/fbe01952-2a23-4882-bb9f-970e8598f979

Result:

```<code>{
  "@context": "\/contexts\/Quote",
  "@id": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979",
  "@type": "Quote",
  "products": [
    {
      "@id": "\/quote_products\/15216edd-dd5c-49d5-bf3f-39d389d804d6",
      "@type": "QuoteProduct",
      "code": "Code 1",
      "quote": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979"
    }
  ]
}
</code>```

Put request to quotes/fbe01952-2a23-4882-bb9f-970e8598f979
with JSON params (please note that I changed the value of QuoteProduct code property)

```<code>{
  "@context": "\/contexts\/Quote",
  "@id": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979",
  "@type": "Quote",
  "products": [
    {
      "@id": "\/quote_products\/15216edd-dd5c-49d5-bf3f-39d389d804d6",
      "@type": "QuoteProduct",
      "code": "A new code",
      "quote": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979"
    }
  ]
}
</code>```

Resulting to :

```<code>{
  "@context": "\/contexts\/Quote",
  "@id": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979",
  "@type": "Quote",
  "products": [
    {
      "@id": "\/quote_products\/865da321-dd74-4a39-82a3-e0e935555262",
      "@type": "QuoteProduct",
      "code": "A new code",
      "quote": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979"
    }
  ]
}
</code>```

The code has changed has expected but it generated a new @id.

答:
After hours and hours i manage to find the answer , i was posting my request with params :

Content-Type : application/json;charset=UTF-8

When i use Content-Type : application/ld+json it is working as expected

According to API platform doc , https://api-platform.com/docs/core/content-negotiation/ this is making sense : Using the raw JSON or raw XML formats is discouraged, prefer using JSON-LD instead, which provides more feature and is as easy to use.

Body:
I have two entities,

Quote and QuoteProduct with a OneToMany Relation between.

When I perform a PUT request to update the embedded QuoteProduct relation, it always remove all items and add them, which result to generate new id's.

According to the official doc, https://api-platform.com/docs/core/serialization/#denormalization
I should be able to update a specific item by passing his id

Quote Entity

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Ramsey\Uuid\Uuid;
use ApiPlatform\Core\Annotation\ApiResource;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ApiResource(
 *     normalizationContext={"groups"={"quote.read"}},
 *     denormalizationContext={"groups"={"quote.write"}},
 *     collectionOperations={
 *         "get"={"access_control"="is_granted('ROLE_USER')", "access_control_message"="You do not have the permission to get"},
 *         "post"={"access_control"="is_granted('ROLE_COMMERCIAL')", "access_control_message"="You do not have the permission to add"}
 *     },
 *     itemOperations={
 *         "get",
 *         "put"={"access_control"="is_granted('ROLE_COMMERCIAL')", "access_control_message"="You do not have the permission to update"},
 *         "delete"={"access_control"="is_granted('ROLE_COMMERCIAL')", "access_control_message"="You do not have the permission to delete."}
 *     },
 *     attributes={"force_eager"=false}
 * )
 * @ORM\Entity
 * @ORM\Table(name="`quotes`")
 */
class Quote
{

    public function __construct()
    {
        $this->id = Uuid::uuid4();
        $this->products = new ArrayCollection();
    }

    /**
     *
     * @ORM\Id
     * @ORM\Column(type="uuid", unique=true)
     */
    private $id;

    /**
     * @var Collection|QuoteProduct[]
     *
     * @Groups({"quote.read", "quote.write"})
     * @ORM\OneToMany(targetEntity="App\Entity\QuoteProduct", mappedBy="quote", cascade={"persist"}, orphanRemoval=true)
     * @ORM\OrderBy({"code" = "ASC"})
     */
    private $products;

    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ----------------------------------------GETTER AND SETTER------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */

    public function getId()
    {
        return $this->id;
    }

    /**
     * @return Collection|QuoteProduct[]
     */
    public function getProducts(): Collection
    {
        return $this->products;
    }

    /**
     * @param QuoteProduct $product
     * @return Quote
     */
    public function addProduct(QuoteProduct $product): self
    {
        if(false === $this->products->contains($product))
        {
            $product->setQuote($this);
            $this->products->add($product);
        }
        return $this;
    }

    /**
     * @param QuoteProduct $product
     * @return Quote
     */
    public function removeProduct(QuoteProduct $product)
    {
        if(!$this->products->contains($product))
        {
            return;
        }
        $this->products->removeElement($product);
        $product->setQuote(null);
    }

}

?>

QuoteProduct Entity

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Ramsey\Uuid\Uuid;
use ApiPlatform\Core\Annotation\ApiResource;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ApiResource(
 *     normalizationContext={"groups"={"quote-product.read"},"enable_max_depth"=true},
 *     denormalizationContext={"groups"={"quote-product.write"},"enable_max_depth"=true},
 *     attributes={"force_eager"=false}
 * )
 * @ORM\Entity
 * @ORM\Table(name="`quote_products`")
 */
class QuoteProduct
{

    /**
     *
     * @ORM\Id
     * @ORM\Column(type="uuid", unique=true)
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Groups({"quote-product.read", "quote-product.write", "quote.read", "quote.write"})
     *
     */
    private $code;

    /**
     * @ORM\ManyToOne(targetEntity="Quote", cascade={"persist"}, inversedBy="products")
     * @Assert\Valid
     * @Groups({"quote-product.read", "quote-product.write", "quote.read", "quote.write"})
     */
    private $quote;

    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ----------------------------------------GETTER AND SETTER------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------------------------------- */

    public function __construct()
    {
        $this->id = Uuid::uuid4();
    }

    public function getId()
    {
        return $this->id;
    }

    public function getQuote(): ?Quote
    {
        return $this->quote;
    }

    public function setQuote(?Quote $quote)
    {
        $this->quote = $quote;

        return $this;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function setCode(?string $code): self
    {
        $this->code = $code;

        return $this;
    }

}

Get request to quotes/fbe01952-2a23-4882-bb9f-970e8598f979

Result:

{
  "@context": "\/contexts\/Quote",
  "@id": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979",
  "@type": "Quote",
  "products": [
    {
      "@id": "\/quote_products\/15216edd-dd5c-49d5-bf3f-39d389d804d6",
      "@type": "QuoteProduct",
      "code": "Code 1",
      "quote": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979"
    }
  ]
}

Put request to quotes/fbe01952-2a23-4882-bb9f-970e8598f979
with JSON params (please note that I changed the value of QuoteProduct code property)

{
  "@context": "\/contexts\/Quote",
  "@id": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979",
  "@type": "Quote",
  "products": [
    {
      "@id": "\/quote_products\/15216edd-dd5c-49d5-bf3f-39d389d804d6",
      "@type": "QuoteProduct",
      "code": "A new code",
      "quote": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979"
    }
  ]
}

Resulting to :

{
  "@context": "\/contexts\/Quote",
  "@id": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979",
  "@type": "Quote",
  "products": [
    {
      "@id": "\/quote_products\/865da321-dd74-4a39-82a3-e0e935555262",
      "@type": "QuoteProduct",
      "code": "A new code",
      "quote": "\/quotes\/fbe01952-2a23-4882-bb9f-970e8598f979"
    }
  ]
}

The code has changed has expected but it generated a new @id.


问:
Angular Firestore query with where returns all docs in collection
I have an angular app that is using Firestore. Whenever I query for docs in collection that meet a specific condition, the array that is returned contains every document in the collection. I do not understand why this is happening as I am following the documentation.

On call to the collection in the component

```<code>this.FirebaseService.getDocsByParam( 'versions', 'projectId', this.projectData.uid )
    .then((snapshot) => {
        var tempArray = [];
        var docData;
        snapshot.forEach((doc) => {
            docData=doc.data();
            docData.uid=doc.id;
            tempArray.push(docData);
        });
        this.versionList = tempArray;
        this.versionData = this.versionList[this.versionList.length-1];
        this.initializeAll();
    })
    .catch((err) => {
      console.log('Error getting documents', err);
});
</code>```

Firebase service making the call

```<code>getDocsByParam( collection, getParam:string, paramValue:string ) {
    var docRef = this.afs.collection(collection, ref => ref.where(getParam, '==', paramValue));
    return docRef.ref.get();
}
</code>```

Below is a screen shot of the versions collection. It shows one of the returned docs, which does not even have the required field.

答:
When you call docRef.ref on a AngularFirestoreCollection it returns the underlying collection, not the query. So your return docRef.ref.get() is indeed getting the entire collection.

I think you can use docRef.query to get the query, but I don't even thing there's any reason to use an AngularFire call at all here. Since your code is already using the plain JavaScript API to process the documents, you might as well stick to that SDK in your getDocsByParam too:

```<code>getDocsByParam( collection, getParam:string, paramValue:string ) {
    var docRef = this.afs.collection(collection).ref;
    return docRef.where(getParam, '==', paramValue).get();
}
</code>```

Body:
I have an angular app that is using Firestore. Whenever I query for docs in collection that meet a specific condition, the array that is returned contains every document in the collection. I do not understand why this is happening as I am following the documentation.

On call to the collection in the component

this.FirebaseService.getDocsByParam( 'versions', 'projectId', this.projectData.uid )
    .then((snapshot) => {
        var tempArray = [];
        var docData;
        snapshot.forEach((doc) => {
            docData=doc.data();
            docData.uid=doc.id;
            tempArray.push(docData);
        });
        this.versionList = tempArray;
        this.versionData = this.versionList[this.versionList.length-1];
        this.initializeAll();
    })
    .catch((err) => {
      console.log('Error getting documents', err);
});

Firebase service making the call

getDocsByParam( collection, getParam:string, paramValue:string ) {
    var docRef = this.afs.collection(collection, ref => ref.where(getParam, '==', paramValue));
    return docRef.ref.get();
}

Below is a screen shot of the versions collection. It shows one of the returned docs, which does not even have the required field.

Body:
When you call docRef.ref on a AngularFirestoreCollection it returns the underlying collection, not the query. So your return docRef.ref.get() is indeed getting the entire collection.

I think you can use docRef.query to get the query, but I don't even thing there's any reason to use an AngularFire call at all here. Since your code is already using the plain JavaScript API to process the documents, you might as well stick to that SDK in your getDocsByParam too:

getDocsByParam( collection, getParam:string, paramValue:string ) {
    var docRef = this.afs.collection(collection).ref;
    return docRef.where(getParam, '==', paramValue).get();
}


问:
Redux changing value of deep nested array
I have an initial state like so:

```<code>const initState = {
    posts: data
}
</code>```

now posts is something like :

```<code>[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": []
  },

//some more here
]

</code>```

So what I want to do is, when dispatch is fired I want to add new comments to that specific comments array. This is how I do it:

```<code> if (action.type === "ADD_COMMENT") {
        let findPost = state.posts.find(post => post.slug === action.payload.comment.postSlug);
        let index = state.posts.indexOf(findPost);
        console.log(findPost);

        return {
            ...state,
            posts: [...state.posts,
            state.posts[index].comments = [action.payload.comment, ...state.posts[index].comments]]
        }
    }

</code>```

Even though my app works completely fine I have a problem with the redux state. Because everytime action is happened it adds new comments in to that specific array along with a new array in to state.

So in case of firing new action I do get something like this:

```<code>[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": ["comment here"]
  },
[
  {
    "comments": ["comment here"]
  },

//some more here
]

]
</code>```

In each click it creates a new entry in to my state which I don't want at all. How can I make it possible that it only adds the comments in to that specific array but not as separate entry?

答:
Pass the index of comments array in  your payload.</p>

```<code>if (action.type === 'ADD_COMMENT') {
  // get the index of the item from the payload
  const index = action.payload.index;
  // create a copy
  const posts = [...state.posts];
  // add comment to comments array
  posts[index].comments.push(action.payload.comment);

  console.log(posts[index]);

  return {
    ...state,
    posts: posts,
  };
}
</code>```

Body:
I have an initial state like so:

const initState = {
    posts: data
}

now posts is something like :

[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": []
  },

//some more here
]

So what I want to do is, when dispatch is fired I want to add new comments to that specific comments array. This is how I do it:

 if (action.type === "ADD_COMMENT") {
        let findPost = state.posts.find(post => post.slug === action.payload.comment.postSlug);
        let index = state.posts.indexOf(findPost);
        console.log(findPost);

        return {
            ...state,
            posts: [...state.posts,
            state.posts[index].comments = [action.payload.comment, ...state.posts[index].comments]]
        }
    }

Even though my app works completely fine I have a problem with the redux state. Because everytime action is happened it adds new comments in to that specific array along with a new array in to state.

So in case of firing new action I do get something like this:

[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": ["comment here"]
  },
[
  {
    "comments": ["comment here"]
  },

//some more here
]

]

In each click it creates a new entry in to my state which I don't want at all. How can I make it possible that it only adds the comments in to that specific array but not as separate entry?

Body:
Pass the index of comments array in  your payload.

if (action.type === 'ADD_COMMENT') {
  // get the index of the item from the payload
  const index = action.payload.index;
  // create a copy
  const posts = [...state.posts];
  // add comment to comments array
  posts[index].comments.push(action.payload.comment);

  console.log(posts[index]);

  return {
    ...state,
    posts: posts,
  };
}


问:
No converter found capable of converting from type to type

I am getting the following stacktrace:

```<code>org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [referencedata.ABDeadlineType] to type [referencedata.DeadlineType]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:324)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:206)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:187)
    at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:256)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter$1.convert(ResultProcessor.java:201)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:212)
    at org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:149)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:121)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy143.findAllSummarizedBy(Unknown Source)
    at
</code>```

My classes are the following

DeadlineType

```<code>@Data
public class DeadlineType extends DefaultIdAndText {
    @Value("#{target.id}")
    String id;

    @Value("#{target.code}")
    String text;

    @Value("#{target.id}")
    public String getId() {
        return id;
    }

    @Value("#{target.code}")
    public String getText() {
        return text;
    }

}
</code>```

ABDeadlineType

```<code>@Data
@Entity
@Table(name = "deadline_type")
@AllArgsConstructor
@NoArgsConstructor
public class ABDeadlineType {

    private @Id
    String id;
    private String code;
}
</code>```

DefaultIdAndText

```<code>@Data @AllArgsConstructor
@NoArgsConstructor
public class DefaultIdAndText implements IdAndText {

    public DefaultIdAndText(IdAndText idAndText){
        this.id = idAndText.getId();
        this.text = idAndText.getText();
    }

    @NotEmpty String id;
    String text;
}
</code>```

DeadlineTypeRepository

```<code>public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<DeadlineType> findAllSummarizedBy();
}
</code>```

Update

Could it be an issue that the projection/mapping using @Value("#{target.id}") format, does not work correctly because these have been done on a class and not on an interface???

答:
Turns out, when the table name is different than the model name, you have to change the annotations to:

```<code>@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
    ...
</code>```

Instead of simply using the @Entity annotation.

What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.

ContentLicense: CC BY-SA 3.0

Body:
I am getting the following stacktrace:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [referencedata.ABDeadlineType] to type [referencedata.DeadlineType]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:324)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:206)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:187)
    at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:256)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter$1.convert(ResultProcessor.java:201)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:212)
    at org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:149)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:121)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy143.findAllSummarizedBy(Unknown Source)
    at

My classes are the following

DeadlineType

@Data
public class DeadlineType extends DefaultIdAndText {
    @Value("#{target.id}")
    String id;

    @Value("#{target.code}")
    String text;

    @Value("#{target.id}")
    public String getId() {
        return id;
    }

    @Value("#{target.code}")
    public String getText() {
        return text;
    }

}

ABDeadlineType

@Data
@Entity
@Table(name = "deadline_type")
@AllArgsConstructor
@NoArgsConstructor
public class ABDeadlineType {

    private @Id
    String id;
    private String code;
}

DefaultIdAndText

@Data @AllArgsConstructor
@NoArgsConstructor
public class DefaultIdAndText implements IdAndText {

    public DefaultIdAndText(IdAndText idAndText){
        this.id = idAndText.getId();
        this.text = idAndText.getText();
    }

    @NotEmpty String id;
    String text;
}

DeadlineTypeRepository

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<DeadlineType> findAllSummarizedBy();
}

Update

Could it be an issue that the projection/mapping using @Value("#{target.id}") format, does not work correctly because these have been done on a class and not on an interface???

Body:
Turns out, when the table name is different than the model name, you have to change the annotations to:

@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
    ...

Instead of simply using the @Entity annotation.

What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.


问:
import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database'
I'm following a tutorial that was made a year ago and as i follow, i come across a couple of code that seems to be outdated. I 've searched a found a couple of solutions but it sadly doesn't solve mine.
Is there therefore a newer way of writing the following code?

```<code>import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import { AngularFireAuth } from "angularfire2/auth";
import { Observable } from "rxjs/Observable";
</code>```

this is the error it is printing out.

ERROR in node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'.
  src/app/chat-form/chat-form.component.ts(16,15): error TS2339: Property 'sendMessage' does not exist on type 'ChatService'.
  src/app/services/chat.service.ts(2,30): error TS2305: Module '"C:/Users/Gabriel/stack/School/HVA/JAAR 2/YOUTUBE TYPESCRIPT TUTORIAL/MyAngularApplication/We-chat/node_modules/angularfire2/database/index"' has no exported member 'FirebaseListObservable'.
  src/app/services/chat.service.ts(4,10): error TS2305: Module '"C:/Users/Gabriel/stack/School/HVA/JAAR 2/YOUTUBE TYPESCRIPT TUTORIAL/MyAngularApplication/We-chat/node_modules/rxjs/Observable"' has no exported member 'Observable'.

答:
yes u are probably using angular 5 ,it is being removed and replaced with AngularFireList
try replacing FirebaseListObservable with AngularFireList.</p>

Body:
I'm following a tutorial that was made a year ago and as i follow, i come across a couple of code that seems to be outdated. I 've searched a found a couple of solutions but it sadly doesn't solve mine.
Is there therefore a newer way of writing the following code?

import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import { AngularFireAuth } from "angularfire2/auth";
import { Observable } from "rxjs/Observable";

this is the error it is printing out.

ERROR in node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'.
  src/app/chat-form/chat-form.component.ts(16,15): error TS2339: Property 'sendMessage' does not exist on type 'ChatService'.
  src/app/services/chat.service.ts(2,30): error TS2305: Module '"C:/Users/Gabriel/stack/School/HVA/JAAR 2/YOUTUBE TYPESCRIPT TUTORIAL/MyAngularApplication/We-chat/node_modules/angularfire2/database/index"' has no exported member 'FirebaseListObservable'.
  src/app/services/chat.service.ts(4,10): error TS2305: Module '"C:/Users/Gabriel/stack/School/HVA/JAAR 2/YOUTUBE TYPESCRIPT TUTORIAL/MyAngularApplication/We-chat/node_modules/rxjs/Observable"' has no exported member 'Observable'.


问:
"Ctrl + click to follow link" in VSCode terminal does not jump to source file but opens new browser tab
I'm using Visual Studio Code (version 1.40.1) to work on my Angular 8 project and run Karma/Jasmine tests from its terminal through the command ng test. When a test failed, I was always able to jump to the related source file through Ctrl + click on a terminal link, embedded in a stack-trace. Since a few days, this doesn't work anymore but a new Chrome browser tab is opened instead.

I thought the problem could be related to any recent updated npm package. Therefore I created a brand-new Angular 8 project (ng new), made a small change in app.component.spec.ts and started ng test. Unfortunately the same problem appears there as well. Completely uninstalling and reinstalling VSCode didn't help either.

Any idea on how I can get the original functionality (jump to source) back?

package.json

```<code>{
  "name": "app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~8.2.13",
    "@angular/common": "~8.2.13",
    "@angular/compiler": "~8.2.13",
    "@angular/core": "~8.2.13",
    "@angular/forms": "~8.2.13",
    "@angular/platform-browser": "~8.2.13",
    "@angular/platform-browser-dynamic": "~8.2.13",
    "@angular/router": "~8.2.13",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.18",
    "@angular/cli": "~8.3.18",
    "@angular/compiler-cli": "~8.2.13",
    "@angular/language-service": "~8.2.13",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  }
}
</code>```

karma.config.js

```<code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, './coverage/app'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true
  });
};
</code>```

答:
In my case, I was getting crazy, it stopped working from one day to another. Researching, I realized that VS had applied an automatic update, and disabled some Angular extensions, I do not know why? (In my case, it happened developing an angular 8 application).

So the working solution for me was going to extensions, filter by "@disabled" and enable the angular -or whatever in your case- extension

Body:
I'm using Visual Studio Code (version 1.40.1) to work on my Angular 8 project and run Karma/Jasmine tests from its terminal through the command ng test. When a test failed, I was always able to jump to the related source file through Ctrl + click on a terminal link, embedded in a stack-trace. Since a few days, this doesn't work anymore but a new Chrome browser tab is opened instead.

I thought the problem could be related to any recent updated npm package. Therefore I created a brand-new Angular 8 project (ng new), made a small change in app.component.spec.ts and started ng test. Unfortunately the same problem appears there as well. Completely uninstalling and reinstalling VSCode didn't help either.

Any idea on how I can get the original functionality (jump to source) back?

package.json

{
  "name": "app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~8.2.13",
    "@angular/common": "~8.2.13",
    "@angular/compiler": "~8.2.13",
    "@angular/core": "~8.2.13",
    "@angular/forms": "~8.2.13",
    "@angular/platform-browser": "~8.2.13",
    "@angular/platform-browser-dynamic": "~8.2.13",
    "@angular/router": "~8.2.13",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.18",
    "@angular/cli": "~8.3.18",
    "@angular/compiler-cli": "~8.2.13",
    "@angular/language-service": "~8.2.13",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  }
}

karma.config.js

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, './coverage/app'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true
  });
};


问:
describe_replication_tasks filter on 'cdc' migration-type
I'm trying to use boto3 to filter replication tasks by cdc migration-type.  However, I cannot seem to find or guess correctly the different possible string Values.  Does anyone know what they are or where I can find them?

```<code>migration_type_filter = { 'Name': 'migration-type', 'Values': 'cdc' }
tasks = boto3.client('dms').describe_replication_tasks(Filters=[migration_type_filter])
</code>```

Error:  "errorMessage": "Parameter validation failed:\nInvalid type for parameter Filters[0].Values, value: cdc, type: , valid types: , "

答:
'cdc' works.  I had the wrong syntax for the filter.

wrong:  migration_type_filter = { 'Name': 'migration-type', 'Values': 'cdc' }

correct: migration_type_filter = { 'Name': 'migration-type', 'Values': ['cdc'] }

Body:
I'm trying to use boto3 to filter replication tasks by cdc migration-type.  However, I cannot seem to find or guess correctly the different possible string Values.  Does anyone know what they are or where I can find them?

migration_type_filter = { 'Name': 'migration-type', 'Values': 'cdc' }
tasks = boto3.client('dms').describe_replication_tasks(Filters=[migration_type_filter])

Error:  "errorMessage": "Parameter validation failed:\nInvalid type for parameter Filters[0].Values, value: cdc, type: , valid types: , "


答:
The idea is to fix style (height, width, position: 'absolute', top, left) only to TouchableOpacity component. Because if you set for example top: 50 to a child component this child will be under the touchableOpacity component by 50 and your onPress function will be fired only if you press the top of your component by 50. You just need position absolute on Text component because it should be on the Image.

```<code><View
  style={{
    flex: 1,
    width: BannerWidth,
    height: (deviceHeight * 25) / 100,
    marginBottom: 40,
    backgroundColor: theme.colors.batiLacivert,
  }}
>
  <TouchableOpacity style={{ position: 'absolute', top: 50, left: 40 }} onPress={() => Actions.portfoy()}>
    <View
      style={{
        width: 48,
        height: 60,
      }}
    >
      <Image
        style={{
          width: 48,
          height: 60,
        }}
        source={require('../../assets/yuzdeler/0yuzde_yeni.png')}
      />
      <Text
        style={{
          position: 'absolute',
          color: 'black',
          fontSize: 20,
        }}
      >
          %
        {this.state.anasayfaBilgiler.Performans}
      </Text>
    </View>
  </TouchableOpacity>
</View>
</code>```

Hope I was clear.

Title: TouchableOpacity behaves weird

Body:
    <View
        style={{
          flex: 1,
          width: BannerWidth,
          height: (deviceHeight * 25) / 100,
          marginBottom: 40,
          backgroundColor: theme.colors.batiLacivert,
        }}>
         <TouchableOpacity onPress={() => Actions.portfoy()}>
          <View
            style={{
              width: 48,
              height: 60,
              left: 0,
              top: 50,
            }}>
            <Image
              style={{
                width: 48,
                height: 60,
                left: 40,
                bottom: -30,
                position: 'absolute',
              }}
              source={require('../../assets/yuzdeler/0yuzde_yeni.png')}
            />
            <Text
              style={{
                position: 'absolute',
                color: 'black',
                left: 47,
                bottom: 0,
                fontSize: 20,
              }}>
              %{this.state.anasayfaBilgiler.Performans}
            </Text>
          </View>
        </TouchableOpacity>
        </View>

I have this code in my project. I use position: absolute to position my shield icon on a View, and I wrapped it into a TouchableOpacity to press it and go to another page. But when I press on the shield, Nothing happens, But when I press the View on the background, It applies the code, it should have done it on the shield...How can I fix this?

Edit: Now it works when the Shield icon on the background View, but when I position it in the bottom, the overflow area of the icon doesnt work just upper half takes the click. I need it to work all over the image

This area -with blue color - doesn't click:

Body:
The idea is to fix style (height, width, position: 'absolute', top, left) only to TouchableOpacity component. Because if you set for example top: 50 to a child component this child will be under the touchableOpacity component by 50 and your onPress function will be fired only if you press the top of your component by 50. You just need position absolute on Text component because it should be on the Image.

<View
  style={{
    flex: 1,
    width: BannerWidth,
    height: (deviceHeight * 25) / 100,
    marginBottom: 40,
    backgroundColor: theme.colors.batiLacivert,
  }}
>
  <TouchableOpacity style={{ position: 'absolute', top: 50, left: 40 }} onPress={() => Actions.portfoy()}>
    <View
      style={{
        width: 48,
        height: 60,
      }}
    >
      <Image
        style={{
          width: 48,
          height: 60,
        }}
        source={require('../../assets/yuzdeler/0yuzde_yeni.png')}
      />
      <Text
        style={{
          position: 'absolute',
          color: 'black',
          fontSize: 20,
        }}
      >
          %
        {this.state.anasayfaBilgiler.Performans}
      </Text>
    </View>
  </TouchableOpacity>
</View>

Hope I was clear.


问:
SignalR in ASP.NET empty website not working
I am very new to the term SignalR . I was try to configure the signalR into my empty website and Added following code.

In App_Code

```<code>  using Microsoft.Owin;
  using Owin;

  [assembly: OwinStartup(typeof(Super.App_Code.Startup))]

  namespace Super.App_Code
  {
     public class Startup
     {
         public static void Configuration(IAppBuilder app)
         {
             app.MapSignalR();

         }
     }
  }
</code>```

and the hub class Inside App_Code

```<code>namespace Super.App_Code
{
[HubName("toastHub")]
 public class ToastHub : Hub
{
    public void BroadcastToast(string type ,string msg)
    {
        Clients.All.sendToast(type , msg);
    }
}
}
</code>```

and in Default.aspx

```<code><head runat="server">
<title></title>
<link rel="stylesheet" href="content/toastr.min.css" />

<script src="Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-2.4.1.js" type="text/javascript"></script>
<script src="Scripts/toastr.min.js" type="text/javascript"></script>
<script src="signalr/hubs" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("#SuccessLink").click(function () {
            console.log("Success Click");
            $.connection.toastHub.client.broadcastToast('success', 'you have done');
        });

        $("#ErrorLink").click(function () {
            console.log("Error Click");
            $.connection.toastHub.client.broadcastToast("error", "you have not done");
        });

        $.connection.hub.start().done(function () {
            console.log('SignalR connected');
        })
        .fail(function (data) {
            console.log('SignalR failed to connect: ' + data);
        });

        $.connection.toastHub.client.sendToast = function (type, msg) {
            console.log("sendToast Called");
            toastr[type](msg);
        };
    });
 </script>
 </head>
 <body>
 <form id="form1" runat="server">
    <div>
        <a id="SuccessLink" style="color: lightgreen">Success Toast</a><br />
        <a id="ErrorLink" style="color: red">Error Toast</a>
    </div>

  </form>
  </body>
  </html>
</code>```

but when i run my website the javascript console says this when click on one of the  tag

```<code>  SignalR connected
  Default.aspx:20 Success Click
  Default.aspx:21 Uncaught TypeError: $.connection.toastHub.client.broadcastToast is not a function
      at HTMLAnchorElement.<anonymous> (Default.aspx:21)
      at HTMLAnchorElement.handle (jquery-1.6.4.js:3001)
      at HTMLAnchorElement.eventHandle (jquery-1.6.4.js:2635)
</code>```

Am i doing anything wrong please help me any help would be greatful .i am totally new to SignalR .

signalr/hub

```<code>if (typeof ($.signalR) !== "function") {
    throw new Error("SignalR: SignalR is not loaded. Please ensure         jquery.signalR-x.js is referenced before ~/signalr/js.");
}

var signalR = $.signalR;

function makeProxyCallback(hub, callback) {
    return function () {
        // Call the client hub method
        callback.apply(hub, $.makeArray(arguments));
    };
}

function registerHubProxies(instance, shouldSubscribe) {
    var key, hub, memberKey, memberValue, subscriptionMethod;

    for (key in instance) {
        if (instance.hasOwnProperty(key)) {
            hub = instance[key];

            if (!(hub.hubName)) {
                // Not a client hub
                continue;
            }

            if (shouldSubscribe) {
                // We want to subscribe to the hub events
                subscriptionMethod = hub.on;
            } else {
                // We want to unsubscribe from the hub events
                subscriptionMethod = hub.off;
            }

            // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
            for (memberKey in hub.client) {
                if (hub.client.hasOwnProperty(memberKey)) {
                    memberValue = hub.client[memberKey];

                    if (!$.isFunction(memberValue)) {
                        // Not a client hub function
                        continue;
                    }

                    // Use the actual user-provided callback as the "identity" value for the registration.
                    subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue), memberValue);
                }
            }
        }
    }
}

$.hubConnection.prototype.createHubProxies = function () {
    var proxies = {};
    this.starting(function () {
        // Register the hub proxies as subscribed
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, true);

        this._registerSubscribedHubs();
    }).disconnected(function () {
        // Unsubscribe all hub proxies when we "disconnect".  This is to ensure that we do not re-add functional call backs.
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, false);
    });

    proxies['toastHub'] = this.createHubProxy('toastHub');
    proxies['toastHub'].client = { };
    proxies['toastHub'].server = {
    };

    return proxies;
};

signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
$.extend(signalR, signalR.hub.createHubProxies());

}(window.jQuery, window));
</code>```

答:
Something is not correctly initialized with your SignalR project, I guess accessing a hubContext should have a Dependency Injector in your startup.cs. But doing context injection with DI for SignalR is an advanced level problem.

However, please try this minimal sample, if it's working for you: https://github.com/bezzad/MVC-SignalR-2

Body:
I am very new to the term SignalR . I was try to configure the signalR into my empty website and Added following code.

In App_Code

  using Microsoft.Owin;
  using Owin;

  [assembly: OwinStartup(typeof(Super.App_Code.Startup))]

  namespace Super.App_Code
  {
     public class Startup
     {
         public static void Configuration(IAppBuilder app)
         {
             app.MapSignalR();

         }
     }
  }

and the hub class Inside App_Code

namespace Super.App_Code
{
[HubName("toastHub")]
 public class ToastHub : Hub
{
    public void BroadcastToast(string type ,string msg)
    {
        Clients.All.sendToast(type , msg);
    }
}
}

and in Default.aspx

<title></title>
<link rel="stylesheet" href="content/toastr.min.css" />

 <form id="form1" runat="server">

        Success Toast

        Error Toast

  </form>

but when i run my website the javascript console says this when click on one of the  tag

  SignalR connected
  Default.aspx:20 Success Click
  Default.aspx:21 Uncaught TypeError: $.connection.toastHub.client.broadcastToast is not a function
      at HTMLAnchorElement.<anonymous> (Default.aspx:21)
      at HTMLAnchorElement.handle (jquery-1.6.4.js:3001)
      at HTMLAnchorElement.eventHandle (jquery-1.6.4.js:2635)

Am i doing anything wrong please help me any help would be greatful .i am totally new to SignalR .

signalr/hub

if (typeof ($.signalR) !== "function") {
    throw new Error("SignalR: SignalR is not loaded. Please ensure         jquery.signalR-x.js is referenced before ~/signalr/js.");
}

var signalR = $.signalR;

function makeProxyCallback(hub, callback) {
    return function () {
        // Call the client hub method
        callback.apply(hub, $.makeArray(arguments));
    };
}

function registerHubProxies(instance, shouldSubscribe) {
    var key, hub, memberKey, memberValue, subscriptionMethod;

    for (key in instance) {
        if (instance.hasOwnProperty(key)) {
            hub = instance[key];

            if (!(hub.hubName)) {
                // Not a client hub
                continue;
            }

            if (shouldSubscribe) {
                // We want to subscribe to the hub events
                subscriptionMethod = hub.on;
            } else {
                // We want to unsubscribe from the hub events
                subscriptionMethod = hub.off;
            }

            // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
            for (memberKey in hub.client) {
                if (hub.client.hasOwnProperty(memberKey)) {
                    memberValue = hub.client[memberKey];

                    if (!$.isFunction(memberValue)) {
                        // Not a client hub function
                        continue;
                    }

                    // Use the actual user-provided callback as the "identity" value for the registration.
                    subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue), memberValue);
                }
            }
        }
    }
}

$.hubConnection.prototype.createHubProxies = function () {
    var proxies = {};
    this.starting(function () {
        // Register the hub proxies as subscribed
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, true);

        this._registerSubscribedHubs();
    }).disconnected(function () {
        // Unsubscribe all hub proxies when we "disconnect".  This is to ensure that we do not re-add functional call backs.
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, false);
    });

    proxies['toastHub'] = this.createHubProxy('toastHub');
    proxies['toastHub'].client = { };
    proxies['toastHub'].server = {
    };

    return proxies;
};

signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
$.extend(signalR, signalR.hub.createHubProxies());

}(window.jQuery, window));


问:
In App Update API always returns 1 (UPDATE_NOT_AVAILABLE)
I am using In-App Update API in the application for Update Application while the new version is available in play store.

module gradle

```<code>defaultConfig {
        applicationId "xxx.xxxxx"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode rootProject.ext.vCode
        versionName rootProject.ext.vName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
</code>```

Last upload version(Live in Playstore)

```<code>vCode = 5
vName = "1.0.4"
</code>```

project gradle (downgrade it for the testing)

```<code>vCode = 4
vName = "1.0.3"
</code>```

Downgrade this version for the testing update available or not.

MainActivity.kt

```<code>class MainActivity : AppCompatActivity() {
    private var appUpdateManager: AppUpdateManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        appUpdateManager = AppUpdateManagerFactory.create(this)
    }

    override fun onResume() {
        super.onResume()
            checkForVersionUpdate()
    }

    private fun checkForVersionUpdate() {
            appUpdateManager?.appUpdateInfo?.addOnSuccessListener { appUpdateInfo ->
                if ((appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS)) {
                    // If an in-app update is already running, resume the update.
                    startUpdateFlow(appUpdateInfo)
                } else if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
                        && appUpdateInfo.isUpdateTypeAllowed(IMMEDIATE)) {
                    startUpdateFlow(appUpdateInfo)
                }
            }
    }

    private fun startUpdateFlow(appUpdateInfo: AppUpdateInfo) {
        try {
            appUpdateManager?.startUpdateFlowForResult(
                    appUpdateInfo,
                    IMMEDIATE,
                    this,
                    123)
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        } catch (e: IntentSender.SendIntentException) {
            e.printStackTrace()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 123) {
            if (resultCode != RESULT_OK) {
                Log.i("Update failed code:", resultCode.toString())
                // If the update is cancelled or fails,
                // you can request to start the update again.
            } else if(resultCode == RESULT_CANCELED)
                checkForVersionUpdate()
        }
    }
}
</code>```

I last uploaded build in play store with App Bundle(.aab) and Open Beta.

Tried following ways.

Sign apk with the same package name.

Clear Playstore apk cache and storage.

Download apk from playstore and uninstall it from device. then after downgrade version code and sign apk and install it in device. Still not showing update app dialog.

答:
What is helping me during testing is opening Google play store app and open "My apps & games" position from drawer menu.

Make sure on "Updates" tab your tested application appears in "Updates Pending".

That library in my opinion does not check on some google api is there any update available, but is checking some kind of google play store app cache

hope it helps
cheers
Wojtek

Body:
I am using In-App Update API in the application for Update Application while the new version is available in play store.

module gradle

defaultConfig {
        applicationId "xxx.xxxxx"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode rootProject.ext.vCode
        versionName rootProject.ext.vName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

Last upload version(Live in Playstore)

vCode = 5
vName = "1.0.4"

project gradle (downgrade it for the testing)

vCode = 4
vName = "1.0.3"

Downgrade this version for the testing update available or not.

MainActivity.kt

class MainActivity : AppCompatActivity() {
    private var appUpdateManager: AppUpdateManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        appUpdateManager = AppUpdateManagerFactory.create(this)
    }

    override fun onResume() {
        super.onResume()
            checkForVersionUpdate()
    }

    private fun checkForVersionUpdate() {
            appUpdateManager?.appUpdateInfo?.addOnSuccessListener { appUpdateInfo ->
                if ((appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS)) {
                    // If an in-app update is already running, resume the update.
                    startUpdateFlow(appUpdateInfo)
                } else if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
                        && appUpdateInfo.isUpdateTypeAllowed(IMMEDIATE)) {
                    startUpdateFlow(appUpdateInfo)
                }
            }
    }

    private fun startUpdateFlow(appUpdateInfo: AppUpdateInfo) {
        try {
            appUpdateManager?.startUpdateFlowForResult(
                    appUpdateInfo,
                    IMMEDIATE,
                    this,
                    123)
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        } catch (e: IntentSender.SendIntentException) {
            e.printStackTrace()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 123) {
            if (resultCode != RESULT_OK) {
                Log.i("Update failed code:", resultCode.toString())
                // If the update is cancelled or fails,
                // you can request to start the update again.
            } else if(resultCode == RESULT_CANCELED)
                checkForVersionUpdate()
        }
    }
}

I last uploaded build in play store with App Bundle(.aab) and Open Beta.

Tried following ways.

Sign apk with the same package name.

Clear Playstore apk cache and storage.

Download apk from playstore and uninstall it from device. then after downgrade version code and sign apk and install it in device. Still not showing update app dialog.


问:
Getting length of video
I am having trouble finding a simple example of how to get the video length of a file programmatically. Many people say, oh use this library/wrapper or whatever, but do not say how. I have downloaded ffmpeg, but have no clue how to actually use it and there does not seem to be any example of how to use it to get the video duration. I see how you can use it to convert videos, but I simply just want to know the duration of a video. All of the other information does not matter.

Is there any way of doing this simply, whether it be in C#, python, java, whatever, that will just return a string that indicates the length of a video file.

Please provide examples if possible. Thanks in advance!

Assume standard file formats, such as wmv, avi, mp4, mpeg. Stuff that has metadata.

答:
you can get all sorts of information about many types of video formats including their duration with ffmpeg by using the -i flag:

```<code>ffmpeg -i videofile.whatever
</code>```

If you want a nice library that can wrap ffmpef for you in C# then you can use MediaHandlerPro

Title: Getting length of video

Body:
you can get all sorts of information about many types of video formats including their duration with ffmpeg by using the -i flag:

ffmpeg -i videofile.whatever

If you want a nice library that can wrap ffmpef for you in C# then you can use MediaHandlerPro


问:
Filter a pandas dataframe using values from a dict
I need to filter a data frame with a dict, constructed with the key being the column name and the value being the value that I want to filter:

```<code>filter_v = {'A':1, 'B':0, 'C':'This is right'}
# this would be the normal approach
df[(df['A'] == 1) & (df['B'] ==0)& (df['C'] == 'This is right')]
</code>```

But I want to do something on the lines

```<code>for column, value in filter_v.items():
    df[df[column] == value]
</code>```

but this will filter the data frame several times, one value at a time, and not apply all filters at the same time. Is there a way to do it programmatically?

EDIT: an example:

```<code>df1 = pd.DataFrame({'A':[1,0,1,1, np.nan], 'B':[1,1,1,0,1], 'C':['right','right','wrong','right', 'right'],'D':[1,2,2,3,4]})
filter_v = {'A':1, 'B':0, 'C':'right'}
df1.loc[df1[filter_v.keys()].isin(filter_v.values()).all(axis=1), :]
</code>```

gives

```<code>    A   B   C   D
0   1   1   right   1
1   0   1   right   2
3   1   0   right   3
</code>```

but the expected result was

```<code>    A   B   C   D
3   1   0   right   3
</code>```

only the last one should be selected.

答:
I had an issue due to my dictionary having multiple values for the same key.

I was able to change DSM's query to:

```<code>df1.loc[df1[list(filter_v)].isin(filter_v).all(axis=1), :]
</code>```

Body:
I need to filter a data frame with a dict, constructed with the key being the column name and the value being the value that I want to filter:

filter_v = {'A':1, 'B':0, 'C':'This is right'}
# this would be the normal approach
df[(df['A'] == 1) & (df['B'] ==0)& (df['C'] == 'This is right')]

But I want to do something on the lines

for column, value in filter_v.items():
    df[df[column] == value]

but this will filter the data frame several times, one value at a time, and not apply all filters at the same time. Is there a way to do it programmatically?

EDIT: an example:

df1 = pd.DataFrame({'A':[1,0,1,1, np.nan], 'B':[1,1,1,0,1], 'C':['right','right','wrong','right', 'right'],'D':[1,2,2,3,4]})
filter_v = {'A':1, 'B':0, 'C':'right'}
df1.loc[df1[filter_v.keys()].isin(filter_v.values()).all(axis=1), :]

gives

    A   B   C   D
0   1   1   right   1
1   0   1   right   2
3   1   0   right   3

but the expected result was

    A   B   C   D
3   1   0   right   3

only the last one should be selected.

Body:
I had an issue due to my dictionary having multiple values for the same key.

I was able to change DSM's query to:

df1.loc[df1[list(filter_v)].isin(filter_v).all(axis=1), :]


问:
Issuer and Audience in JWT .net core
Hi everyone I'm trying to do JWT in .net core api and I have a question while configuring JWT in file startup.cs
Specifically I want to ask "ValidIssuer" and "ValidAudience" to do, what does it mean for JWT?
Somebody can help me please, thanks all.

This is my code :

```<code>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
            {
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    // what to validate
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true,
                    // set up validate data
                    ValidIssuer = "smesk.in",
                    ValidAudience = "reader",
                    IssuerSigningKey = symmetricSecurityKey

                };

            });
</code>```

答:
It is basically used to whom you want to allow your requests. You can refer this document.

https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.tokenvalidationparameters.validaudience?view=azure-dotnet

And you can set it like this.

```<code>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {

            ValidateIssuer = true,
            ValidateAudience = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Audience"]

        };
    });
</code>```

Appsettings.json

```<code>  "Jwt": {
    "Issuer": "test.com",
    "Audience": "abc.com"
  }
</code>```

Title: Issuer and Audience in JWT .net core

Body:
Hi everyone I'm trying to do JWT in .net core api and I have a question while configuring JWT in file startup.cs
Specifically I want to ask "ValidIssuer" and "ValidAudience" to do, what does it mean for JWT?
Somebody can help me please, thanks all.

This is my code :

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
            {
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    // what to validate
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true,
                    // set up validate data
                    ValidIssuer = "smesk.in",
                    ValidAudience = "reader",
                    IssuerSigningKey = symmetricSecurityKey

                };

            });

Body:
It is basically used to whom you want to allow your requests. You can refer this document.

https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.tokenvalidationparameters.validaudience?view=azure-dotnet

And you can set it like this.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {

            ValidateIssuer = true,
            ValidateAudience = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Audience"]

        };
    });

Appsettings.json

  "Jwt": {
    "Issuer": "test.com",
    "Audience": "abc.com"
  }