问:
How to select a set of fields from input data as an array of repeated fields in beam SQL
Problem Statement:

I  have  an  input  PCollection  with  following  fields:

```<code>{
   firstname_1,
   lastname_1,
   dob,
   firstname_2,
   lastname_2,
   firstname_3,
   lastname_3,
}
</code>```

then I execute a Beam SQL  operation such that output of resultant  PCollection should be like

```<code> ----------------------------------------------
   name.firstname |  name.lastname | dob
 ----------------------------------------------
      firstname_1 |  lastname_1    | 202009
      firstname_2 |  lastname_2    |
      firstname_3 |  lastname_3    |
-----------------------------------------------
</code>```

To be precise:

```<code>array[
    (firstname_1,lastname_1,dob),
    (firstname_2,lastname_2,dob),
    (firstname_3,lastname_3,dob)
]
</code>```

Here is the code snippet where I execute Beam SQL:

PCollectionTuple tuple=
    PCollectionTuple.of(new TupleTag<>("testPcollection"), testPcollection);

PCollection<Row> result = tuple
    .apply(SqlTransform.query(
        "SELECT array[(firstname_1,lastname_1,dob), (firstname_2,lastname_2,dob), (firstname_3,lastname_3,dob)]"));

```

I am not getting proper results.

Can someone guide  me  how to query an array of repeated field in Beam  SQL?

答: You can take a look at this example on how to access arrays in Beam SQL - https://github.com/apache/beam/blob/d110f6b7610b26edc1eb9a4b698840b21c151847/sdks/java/extensions/sql/src/test/java/org/apache/beam/sdk/extensions/sql/BeamSqlDslNestedRowsTest.java#L234</p>

Body:
Problem Statement:

I  have  an  input  PCollection  with  following  fields:

{
   firstname_1,
   lastname_1,
   dob,
   firstname_2,
   lastname_2,
   firstname_3,
   lastname_3,
}

then I execute a Beam SQL  operation such that output of resultant  PCollection should be like

 ----------------------------------------------
   name.firstname |  name.lastname | dob
 ----------------------------------------------
      firstname_1 |  lastname_1    | 202009
      firstname_2 |  lastname_2    |
      firstname_3 |  lastname_3    |
-----------------------------------------------

To be precise:

array[
    (firstname_1,lastname_1,dob),
    (firstname_2,lastname_2,dob),
    (firstname_3,lastname_3,dob)
]

Here is the code snippet where I execute Beam SQL:

PCollectionTuple tuple=
    PCollectionTuple.of(new TupleTag<>("testPcollection"), testPcollection);

PCollection<Row> result = tuple
    .apply(SqlTransform.query(
        "SELECT array[(firstname_1,lastname_1,dob), (firstname_2,lastname_2,dob), (firstname_3,lastname_3,dob)]"));

I am not getting proper results.

Can someone guide  me  how to query an array of repeated field in Beam  SQL?


来源: stackexchange

问:
Why is the main purpose of ResNet if the vanishing gradient problem is solved using RELU activation function?
I read that ResNet solves the problem of vanishing gradient problem by using skip functions. But are they not already solved using RELU? Is there some other important thing I'm missing about ResNet or does Vanishing gradient problem occur even after using RELU? </p>

答: While the ReLU activation function does solve the problem of vanishing gradients, it does not provide the deeper layers with extra information as in the case of ResNets. The idea of propagating the original input data as deep as possible through the network hence helping the network learn much more complex features is why ResNet architecture was introduced and achieves such high accuracy on a variety of tasks. </p>

ContentLicense: CC BY-SA 4.0


问:
JavaScript GET Request Webpage image in Stream
I have a url that has a new jpeg  on it everytime you visit the page . I would like to use my javascript get constantly send get statements to that page and retrieve the image to display it on my webpage in as "stream" of images in a container one after the other  . Currently I can only get the first image when I run the function. I am new to JavaScript.</p>

```<code>    isLive=true;
    let imageurl = SERVICE_URL;
    var ajaxImage = document.getElementById("liveImg");
      do {

            xhttp.open("GET",imageurl, true);
            xhttp.send();
            ajaxImage.src = imageurl;

          }
          while (isLive);
</code>```

答:
Do not use infinite loops in javascript to do ajax like this because it would send many request without any limit crashing the browser and yes the server as well if there are many clients

What you need instead is a timer that would tick, say every 5 seconds changing the image

```<code>isLive=true;
let imageurl = SERVICE_URL;
var ajaxImage = document.getElementById("liveImg");
var timerKey = 0;

function Imgchanger{
    //incase you want to stop it just assign isLive=false somewhere
    if(!isLive){
        clearInterval(timerKey);
    }

    xhttp.open("GET",imageurl, true);
    xhttp.send();
    ajaxImage.src = imageurl;
}

timerKey  = setInterval(imgchanger, 5000); //5 seconds
</code>```

Body:
I have a url that has a new jpeg  on it everytime you visit the page . I would like to use my javascript get constantly send get statements to that page and retrieve the image to display it on my webpage in as "stream" of images in a container one after the other  . Currently I can only get the first image when I run the function. I am new to JavaScript.

    isLive=true;
    let imageurl = SERVICE_URL;
    var ajaxImage = document.getElementById("liveImg");
      do {

            xhttp.open("GET",imageurl, true);
            xhttp.send();
            ajaxImage.src = imageurl;

          }
          while (isLive);

Body:
Do not use infinite loops in javascript to do ajax like this because it would send many request without any limit crashing the browser and yes the server as well if there are many clients

What you need instead is a timer that would tick, say every 5 seconds changing the image

isLive=true;
let imageurl = SERVICE_URL;
var ajaxImage = document.getElementById("liveImg");
var timerKey = 0;

function Imgchanger{
    //incase you want to stop it just assign isLive=false somewhere
    if(!isLive){
        clearInterval(timerKey);
    }

    xhttp.open("GET",imageurl, true);
    xhttp.send();
    ajaxImage.src = imageurl;
}

timerKey  = setInterval(imgchanger, 5000); //5 seconds


问:
Eager loading in many to many in laravel eloquent relationship (Retrieve all Posts with their assigned tags)
My blog laravel project has many Posts and each Post belongs to many tags.
Now I want to retrieve all blogs and their tags and echo each tag.

Here is the code I have written. Is there any better way?

```<code>$posts = Post::with('tags')->get();

    foreach ($posts as $post) {
        foreach ($post->tags as $tag) {
            echo "``` $tag->name ```";
        }
    }
    die();
</code>```

答:
You can get all tags with Eager loading as you do in your code.

Take a look at https://laravel.com/docs/7.x/eloquent-relationships#eager-loading

$posts = App\Post::with('tags:name')->get();

foreach ($posts as $post) {
    foreach ($post->tags as $tag) {
        echo "``` $tag->name ```";
    }
}
```

<p>It is the correct solution.</p>

<p>You can even do it with <code>DB</code> queries to get it faster but probably your way is just enough.</p>

<pre class="lang-php prettyprint-override"><code>$posts = App\Post::all()->pluck('id');

return DB::select('SELECT name FROM tags WHERE id in (' . implode(',', $posts) . ')');
</code>```

Final tip: Do not merge HTML view with the logic.

Body:
My blog laravel project has many Posts and each Post belongs to many tags.
Now I want to retrieve all blogs and their tags and echo each tag.

Here is the code I have written. Is there any better way?

$posts = Post::with('tags')->get();

    foreach ($posts as $post) {
        foreach ($post->tags as $tag) {
            echo "
 $tag->name
";
        }
    }
    die();

Body:
You can get all tags with Eager loading as you do in your code.

Take a look at https://laravel.com/docs/7.x/eloquent-relationships#eager-loading

$posts = App\Post::with('tags:name')->get();

foreach ($posts as $post) {
    foreach ($post->tags as $tag) {
        echo "<pre> $tag->name </pre>";
    }
}

It is the correct solution.

You can even do it with DB queries to get it faster but probably your way is just enough.

$posts = App\Post::all()->pluck('id');

return DB::select('SELECT name FROM tags WHERE id in (' . implode(',', $posts) . ')');

Final tip: Do not merge HTML view with the logic.


问:
Androidx AppCompatButton looks different from Button even on high API Level device
According to the documentation

A Button which supports compatible features on older versions of the
  platform, including:

Allows dynamic tint of its background via the background tint methods
  in ViewCompat. Allows setting of the background tint using
  R.attr.backgroundTint and R.attr.backgroundTintMode. This will
  automatically be used when you use Button in your layouts and the
  top-level activity / dialog is provided by appcompat. You should only
  need to manually use this class when writing custom views.

Now, this makes me assume that the following two buttons would look exactly the same on high level devices.

```<code><androidx.appcompat.widget.AppCompatButton
        android:text="AppCompatButton"
        android:id="@+id/appcompatbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

<Button
        android:layout_below="@id/appcompatbutton"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:text="Button"
        android:layout_height="wrap_content" />
</code>```

However, here is how it actually looks:

I ran this on the following emulator:
Galaxy Nexus, API:28 (720 x 1280 xhdpi)

And when I apply buttonStyle in my appTheme like this:

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="buttonStyle">@style/Widget.MaterialComponents.Button</item>
</style>
</code>```

It changes the AppCompatButton but not the normal button like this:
(Note the slight difference in the rounded edges)

I also tried to create a custom button that both inherited from android.widget.Button and also androidx.appcompat.widget.AppCompatButton, both of these buttons show the same behaviour as using AppCompatButton in xml does. So it feels like the only outlier is Button in XML.

Question 1:

This all seems incredibly confusing according to me. Can someone clarify this as either a bug or feature?

EDIT 1

Doing debugging I found that the Button actually gets transformed into a MaterialButton, see the following:

Question 2:

Why is this transformation happening?

EDIT 2

Question 2 answer:

The transformation of Button to MaterialButton is due to the parent theme I was using.

Question 3:

How do you implement a custom button which works just like Button in xml would?

As a side note and personal opinion, also a slight repetition, this system is not only confusing but its hard to get it right and foolproof for future changes. In addition to this, the documentation is very poor. I would appreciate if an answer to this would be included as well, or at least a discussion regarding it, how to deal with it for example.

答:
I changed the <Button> to <ImageButton>

Quick and short way.

Don't forget to check & change references in java/kotlin files. Compiler will alert you any way.

Body:
According to the documentation

A Button which supports compatible features on older versions of the
  platform, including:

Allows dynamic tint of its background via the background tint methods
  in ViewCompat. Allows setting of the background tint using
  R.attr.backgroundTint and R.attr.backgroundTintMode. This will
  automatically be used when you use Button in your layouts and the
  top-level activity / dialog is provided by appcompat. You should only
  need to manually use this class when writing custom views.

Now, this makes me assume that the following two buttons would look exactly the same on high level devices.

<androidx.appcompat.widget.AppCompatButton
        android:text="AppCompatButton"
        android:id="@+id/appcompatbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

<Button
        android:layout_below="@id/appcompatbutton"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:text="Button"
        android:layout_height="wrap_content" />

However, here is how it actually looks:

I ran this on the following emulator:
Galaxy Nexus, API:28 (720 x 1280 xhdpi)

And when I apply buttonStyle in my appTheme like this:

It changes the AppCompatButton but not the normal button like this:
(Note the slight difference in the rounded edges)

I also tried to create a custom button that both inherited from android.widget.Button and also androidx.appcompat.widget.AppCompatButton, both of these buttons show the same behaviour as using AppCompatButton in xml does. So it feels like the only outlier is Button in XML.

Question 1:

This all seems incredibly confusing according to me. Can someone clarify this as either a bug or feature?

EDIT 1

Doing debugging I found that the Button actually gets transformed into a MaterialButton, see the following:

Question 2:

Why is this transformation happening?

EDIT 2

Question 2 answer:

The transformation of Button to MaterialButton is due to the parent theme I was using.

Question 3:

How do you implement a custom button which works just like Button in xml would?

As a side note and personal opinion, also a slight repetition, this system is not only confusing but its hard to get it right and foolproof for future changes. In addition to this, the documentation is very poor. I would appreciate if an answer to this would be included as well, or at least a discussion regarding it, how to deal with it for example.


问:
Is there a reason '\0' is not supported in F#?
When I try to use '\0' as a character in F# it doesn't work.  Here is what I see:

I have read elsewhere that Char.MinValue will accomplish the same thing though.

Is there any reason why '\0' is not supported?

答:
It is supported.
Character literals in F# are either a unicode character or the 16-bit unicode number. It's just that the backslash means it's a short or long escape sequence.

```<code>let A = '\u0041' // Capital letter A
</code>```

The ASCII version of this is '\nnn'. So

```<code>let A = '\065' // Capital letter A
</code>```

And so \0 becomes \000.

```<code>assert('\000' = Char.MinValue) // true
</code>```

Please note that the unicode specifier is in hex, while the short sequence is in decimal.

DEC(65) = HEX(41)

Body:
It is supported.
Character literals in F# are either a unicode character or the 16-bit unicode number. It's just that the backslash means it's a short or long escape sequence.

let A = '\u0041' // Capital letter A

The ASCII version of this is '\nnn'. So

let A = '\065' // Capital letter A

And so \0 becomes \000.

assert('\000' = Char.MinValue) // true

Please note that the unicode specifier is in hex, while the short sequence is in decimal.

DEC(65) = HEX(41)


问:
I have used all my spare neurons trying to figure out why this CSS is not working on this test site of mine

#faleConnosco a {
  letter-spacing: 0.3em;
  border-radius: 30px;
  color: #000;
  border: 1px solid rgba(0, 0, 0, 0.63);
  font-size: 1.3em;
  padding-top: 5px;
  padding-bottom: 5px;
  padding-left: 15px;
  padding-right: 15px;
  text-decoration: none;
  transition: all 0.9s ease-in-out;
}

#faleConnosco a:hover {
  background-color: #f00;
  color: #fff;
  padding-left: 35px;
  padding-right: 35px;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Page title</title>
  <link rel="stylesheet" href="myCSS.css">
</head>

<body>

  <table>
    <tbody>
      <tr>
        <td>
          <div id="faleConnosco">FALE CONNOSCO</div>
        </td>
      </tr>
    </tbody>
  </table>

</body>

</html></code>```

this works perfectly. You mouse over the words and a red oval appears and the text turns white

but when I add this code to this site I am testing, it doesn't.

Hover on FALA CONNOSCO... it will not turn red.

I have used all my spare neurons trying to figure out why. Not even the cursor changes to a pointer.

答:
There's a div, "twentyseventeen-panel", with a negative margin covering the button. This CSS should fix it.

```<code>#post-98.twentyseventeen-panel {
margin-bottom: -30px;
}
</code>```

This was discovered by using the dev tool in the Chrome browser. You can use it by hovering over the item in question and righ-click to select "inspect". This will then open the developer tool and have an HTML element highlighted and opened. This is where you can drill down by opening each HTML element within the first one until you find the button. Upon selecting each element you will be able to see CSS properties. The one that stuck out most was the negative margin of -100px on .twentyseventeen-panel  because typically that can cause issues. Trial and error helps by toggling the CSS property checkboxes to see how each effects the HTML. Hope that helps.

Body:
#faleConnosco a {
  letter-spacing: 0.3em;
  border-radius: 30px;
  color: #000;
  border: 1px solid rgba(0, 0, 0, 0.63);
  font-size: 1.3em;
  padding-top: 5px;
  padding-bottom: 5px;
  padding-left: 15px;
  padding-right: 15px;
  text-decoration: none;
  transition: all 0.9s ease-in-out;
}

#faleConnosco a:hover {
  background-color: #f00;
  color: #fff;
  padding-left: 35px;
  padding-right: 35px;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Page title</title>
  <link rel="stylesheet" href="myCSS.css">

FALE CONNOSCO

this works perfectly. You mouse over the words and a red oval appears and the text turns white

but when I add this code to this site I am testing, it doesn't.

Hover on FALA CONNOSCO... it will not turn red.

I have used all my spare neurons trying to figure out why. Not even the cursor changes to a pointer.

Body:
There's a div, "twentyseventeen-panel", with a negative margin covering the button. This CSS should fix it.

#post-98.twentyseventeen-panel {
margin-bottom: -30px;
}

This was discovered by using the dev tool in the Chrome browser. You can use it by hovering over the item in question and righ-click to select "inspect". This will then open the developer tool and have an HTML element highlighted and opened. This is where you can drill down by opening each HTML element within the first one until you find the button. Upon selecting each element you will be able to see CSS properties. The one that stuck out most was the negative margin of -100px on .twentyseventeen-panel  because typically that can cause issues. Trial and error helps by toggling the CSS property checkboxes to see how each effects the HTML. Hope that helps.


问:
What are the semantics of assume for Isabelle/Isar?
I found a surprising behaviour (for me) when using Isar.
I try to use assume and sometimes Isar complains it cannot resolve pending goals, for example my most typical example is having a an assumption and not being able to assume it:

```<code>lemma
  assumes "A"
  shows "A"
proof -
  assume "A"
  from this show "A" by (simp)
qed
</code>```

though the following does work:

```<code>lemma
  shows "A⟹A"
proof -
  assume "A"
  from this show "A" by simp
qed
</code>```

which is not terribly surprising.

But the next one is surprising to me that it works given that my first example failed:

```<code>lemma
  assumes "A"
  shows "A"
proof -
  have "A" by (simp add: assms)
  from this show "A" by (simp)
qed
</code>```

why is the first one different from the second one?

Error msg:

```<code>Failed to refine any pending goal
Local statement fails to refine any pending goal
Failed attempt to solve goal by exported rule:
  (A) ⟹ A
</code>```

答:
You can find an answer in "Chapter 6: Proofs" of the document Isar-ref. Ideally, you wish to read through the introduction to the chapter, as well as sections 6.1 and 6.2 to fully resolve your concerns. Below, I present the most relevant passages:

The logical proof context consists of fixed variables and assumptions.

...

Similarly, introducing some assumption χ has two effects. On the one
  hand, a local theorem is created that may be used as a fact in
  subsequent proof steps. On the other hand, any result χ ⊢ φ exported
  from the context becomes conditional wrt. the assumption: ⊢ χ ==> φ.
  Thus, solving an enclosing goal using such a result would basically
  introduce a new subgoal stemming from the assumption. How this
  situation is handled depends on the version of assumption command
  used: while assume insists on solving the subgoal by unification with
  some premise of the goal, presume leaves the subgoal unchanged in
  order to be proved later by the user.

Let us look at your first example:

```<code>lemma
  assumes "A"
  shows "A"
proof -
  assume "A"
  from this show "A" by (simp)
qed
</code>```

There is only one subgoal with no premises: A. Given that there are no premises, 'unification with premises' is inapplicable.

In the second example,

```<code>lemma
  shows "A⟹A"
proof -
  assume "A"
  from this show "A" by simp
qed
</code>```

the subgoal is A⟹A with the premise A. Thus, you can use assume: unification can be performed.

Lastly,

```<code>lemma
  assumes "A"
  shows "A"
proof -
  have "A" by (simp add: assms)
  from this show "A" by (simp)
qed
</code>```

is different from the previous cases, because you do not introduce any assumptions. Therefore, you can use show to discharge the subgoal. It should be noted that from this show "A" by (simp) is identical to from assms show "A" by simp or, better yet, from this show "A".:

```<code>lemma
  assumes "A"
  shows "A"
proof -
  from assms show "A".
qed
</code>```

Body:
I found a surprising behaviour (for me) when using Isar.
I try to use assume and sometimes Isar complains it cannot resolve pending goals, for example my most typical example is having a an assumption and not being able to assume it:

lemma
  assumes "A"
  shows "A"
proof -
  assume "A"
  from this show "A" by (simp)
qed

though the following does work:

lemma
  shows "A⟹A"
proof -
  assume "A"
  from this show "A" by simp
qed

which is not terribly surprising.

But the next one is surprising to me that it works given that my first example failed:

lemma
  assumes "A"
  shows "A"
proof -
  have "A" by (simp add: assms)
  from this show "A" by (simp)
qed

why is the first one different from the second one?

Error msg:

Failed to refine any pending goal
Local statement fails to refine any pending goal
Failed attempt to solve goal by exported rule:
  (A) ⟹ A

Body:
You can find an answer in "Chapter 6: Proofs" of the document Isar-ref. Ideally, you wish to read through the introduction to the chapter, as well as sections 6.1 and 6.2 to fully resolve your concerns. Below, I present the most relevant passages:

The logical proof context consists of fixed variables and assumptions.

...

Similarly, introducing some assumption χ has two effects. On the one
  hand, a local theorem is created that may be used as a fact in
  subsequent proof steps. On the other hand, any result χ ⊢ φ exported
  from the context becomes conditional wrt. the assumption: ⊢ χ ==> φ.
  Thus, solving an enclosing goal using such a result would basically
  introduce a new subgoal stemming from the assumption. How this
  situation is handled depends on the version of assumption command
  used: while assume insists on solving the subgoal by unification with
  some premise of the goal, presume leaves the subgoal unchanged in
  order to be proved later by the user.

Let us look at your first example:

lemma
  assumes "A"
  shows "A"
proof -
  assume "A"
  from this show "A" by (simp)
qed

There is only one subgoal with no premises: A. Given that there are no premises, 'unification with premises' is inapplicable.

In the second example,

lemma
  shows "A⟹A"
proof -
  assume "A"
  from this show "A" by simp
qed

the subgoal is A⟹A with the premise A. Thus, you can use assume: unification can be performed.

Lastly,

lemma
  assumes "A"
  shows "A"
proof -
  have "A" by (simp add: assms)
  from this show "A" by (simp)
qed

is different from the previous cases, because you do not introduce any assumptions. Therefore, you can use show to discharge the subgoal. It should be noted that from this show "A" by (simp) is identical to from assms show "A" by simp or, better yet, from this show "A".:

lemma
  assumes "A"
  shows "A"
proof -
  from assms show "A".
qed


问:
Kotlin adding a val field to subclass with multiple constructors
I am creating a custom view in Android and I want to add a val field to the constructor, however View contains multiple constructors.

class CustomView : View {

    // I want a `val field: CustomField` in my constructor

    constructor(
        context: Context
    ) : super(context)

    constructor(
        context: Context,
        attrs: AttributeSet? = null
    ) : super(context, attrs)

    constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0
    ) : super(context, attrs, defStyle)

    ...
}
```

<p>Kotlin doesn't allow val fields in secondary constructors so I cannot do something like this:</p>

<pre class="lang-kotlin prettyprint-override"><code>class CustomView : View {

    constructor(
        val field: CustomField,
        context: Context
    ) : super(context)

    constructor(
        val field: CustomField,
        context: Context,
        attrs: AttributeSet? = null
    ) : super(context, attrs)

    constructor(
        val field: CustomField,
        context: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0
    ) : super(context, attrs, defStyle)

    ...
</code>```

How can I add a val field to the constructors but still extend the multiple constructors of the parent class?

I've tried adding the val to the secondary constructors, but Kotlin doesn't allow a val on a secondary constructor.

I've tried creating one primary constructor (the one I'm planning to explicitly use) and ignoring the others. Then Android Studio gives me a Lint warning that I'm missing constructors. (and I would like to know if there's a way to implement them all anyways)

I've tried adding the field I want as another parameter in the secondary constructor (not a val) and setting it in the secondary constructor body. This leads to the compiler complaining that the val is not initialized if I try to access in an init block and then the Linter still complains I am not implementing the super's constructors

class CustomView : View {

    val field: CustomField

    constructor(
        field: CustomField,
        context: Context
    ) : super(context) { this.field = field }

    ...
```

If the val I want is a primitive type I could pass it as part of the View's attribute set, however in this case it is not. Also I am hoping for a general Kotlin solution, if it exists.

答:
You can do it in this way.

You will get error Property must be initialized or be abstract because field myCustomField must be initialized in every constructor of your class.

Also you cannot use keyword val in parameters

```<code>    class CustomView : View {

        val myCustomField : CustomField

        constructor(customField : CustomField, context: Context?) : super(context){
            this.myCustomField = customField
        }

        constructor(customField : CustomField ,context: Context?, attrs: AttributeSet?) : super(context, attrs){
            this.myCustomField = customField

        }
        constructor(customField : CustomField, context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
            context,
            attrs,
            defStyleAttr
        ){
            this.myCustomField = customField
        }

        constructor(
            customField : CustomField,
            context: Context?,
            attrs: AttributeSet?,
            defStyleAttr: Int,
            defStyleRes: Int
        ) : super(context, attrs, defStyleAttr, defStyleRes){
            this.myCustomField = customField
        }
    }
</code>```

Body:
I am creating a custom view in Android and I want to add a val field to the constructor, however View contains multiple constructors.

class CustomView : View {

    // I want a `val field: CustomField` in my constructor

    constructor(
        context: Context
    ) : super(context)

    constructor(
        context: Context,
        attrs: AttributeSet? = null
    ) : super(context, attrs)

    constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0
    ) : super(context, attrs, defStyle)

    ...
}

Kotlin doesn't allow val fields in secondary constructors so I cannot do something like this:

class CustomView : View {

    constructor(
        val field: CustomField,
        context: Context
    ) : super(context)

    constructor(
        val field: CustomField,
        context: Context,
        attrs: AttributeSet? = null
    ) : super(context, attrs)

    constructor(
        val field: CustomField,
        context: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0
    ) : super(context, attrs, defStyle)

    ...

How can I add a val field to the constructors but still extend the multiple constructors of the parent class?

I've tried adding the val to the secondary constructors, but Kotlin doesn't allow a val on a secondary constructor.

I've tried creating one primary constructor (the one I'm planning to explicitly use) and ignoring the others. Then Android Studio gives me a Lint warning that I'm missing constructors. (and I would like to know if there's a way to implement them all anyways)

I've tried adding the field I want as another parameter in the secondary constructor (not a val) and setting it in the secondary constructor body. This leads to the compiler complaining that the val is not initialized if I try to access in an init block and then the Linter still complains I am not implementing the super's constructors

class CustomView : View {

    val field: CustomField

    constructor(
        field: CustomField,
        context: Context
    ) : super(context) { this.field = field }

    ...

If the val I want is a primitive type I could pass it as part of the View's attribute set, however in this case it is not. Also I am hoping for a general Kotlin solution, if it exists.

Body:
You can do it in this way.

You will get error Property must be initialized or be abstract because field myCustomField must be initialized in every constructor of your class.

Also you cannot use keyword val in parameters

    class CustomView : View {

        val myCustomField : CustomField

        constructor(customField : CustomField, context: Context?) : super(context){
            this.myCustomField = customField
        }

        constructor(customField : CustomField ,context: Context?, attrs: AttributeSet?) : super(context, attrs){
            this.myCustomField = customField

        }
        constructor(customField : CustomField, context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
            context,
            attrs,
            defStyleAttr
        ){
            this.myCustomField = customField
        }

        constructor(
            customField : CustomField,
            context: Context?,
            attrs: AttributeSet?,
            defStyleAttr: Int,
            defStyleRes: Int
        ) : super(context, attrs, defStyleAttr, defStyleRes){
            this.myCustomField = customField
        }
    }


问:
Protractor testing: How to set the value of text elements in a login form?
I am writing tests in Protractor for an Angular app. I want to fill out a login form and submit it. </p>

<p>How can I do this? I have got this far, but I don't know how to set the value of the email and password fields. </p>

```<code>describe('The dashboard', function() {
  ptor = protractor.getInstance();

  beforeEach(function() {
    ptor.get('#/dashboard');
    var email = ptor.findElement(protractor.By.model('email'));
    var password = ptor.findElement(protractor.By.model('password'));
    var submit = ptor.findElement(protractor.By.tagName('button'));
    // Fill out the form?
    submit.click();
  });

  it('has a heading', function() {
    heading = ptor.findElement(protractor.By.tagName('h1'));
    expect(heading.getText()).toEqual('My Dashboard');
  });
});
</code>```

答:
How about xpath?

I create a button like bellow:

```<code><ion-input [(ngModel)]="model.password" name="password" type="text" #passcode="ngModel" required>
</ion-input>
</code>```

And set the value using

```<code>element(by.xpath('//*[@name="password"]/input')).sendKeys('PASSWORD')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing tests in Protractor for an Angular app. I want to fill out a login form and submit it.

How can I do this? I have got this far, but I don't know how to set the value of the email and password fields.

describe('The dashboard', function() {
  ptor = protractor.getInstance();

  beforeEach(function() {
    ptor.get('#/dashboard');
    var email = ptor.findElement(protractor.By.model('email'));
    var password = ptor.findElement(protractor.By.model('password'));
    var submit = ptor.findElement(protractor.By.tagName('button'));
    // Fill out the form?
    submit.click();
  });

  it('has a heading', function() {
    heading = ptor.findElement(protractor.By.tagName('h1'));
    expect(heading.getText()).toEqual('My Dashboard');
  });
});

Body:
How about xpath?

I create a button like bellow:

<ion-input [(ngModel)]="model.password" name="password" type="text" #passcode="ngModel" required>
</ion-input>

And set the value using

element(by.xpath('//*[@name="password"]/input')).sendKeys('PASSWORD')


问:
PayPal Smart Button Debit or Credit Card Functionality- Display Amount
We recently added PayPals Smart Buttons to our website and hid or deactivated the PayPal Credit button so that only the blue PayPal and the black Debit or Credit Card remain. When a user pays by clicking on the PayPal button, the user can log onto PayPal or select Pay with Debit or Credit Card (as a Guest Checkout). In both situations, PayPal displays the amount being charged in the upper righthand corner of a new window.

When a user clicks on the black Debit or Credit Card, rather than open into a new window, PayPal expands embedded fields right in the website itself (which is pretty cool).  However, on our configuration it doesn't display the amount being charged.  While we display the amount charged in other places in our website, depending on the size of the users' screens, they often have to scroll up to view such amount.

I'm trying to figure out how to display the amount PayPal will charge if a user clicks on the black Debit or Credit Card (similar to how PayPal displays such amount when the blue PayPal button is selected). PayPal has this information which we display after payment with a pop-up message (and via a follow-up receipt sent by email), but it would give a customer confidence to see something official from PayPal contemporaneously as they click "Pay Now" (especially if the price we've listed isn't viewable because of screen size).

Thanks,

答:
The black "Debit or Credit" card button expands inline with the rest of your web page, rather than opening a new window. Since it expands credit card fields inline on your page, it is designed to use minimal space on your page.

There is no option for PayPal to display the amount being charged. Since all this is happening on your page, you can display the amount yourself -- right there, wherever you want to show it. It's your page and you have full control over it.


问:
Customization of the Height of a Pivot Item Link Line in Fluent UI
I'm trying to increase the height of the line on the selected Pivot item link in Microsoft's Fluent UI using React.

Here's a screenshot for the purposes of clarification:

The orange arrow is pointing to the blue line of which I would like to increase the height.

I have tried setting the styles attribute of the Pivot component but thus far have been unsuccessful.  Here's some code

```<code>const pivotStyles: Partial<IStyleSet<IPivotStyles>> = {
    link: { ? },
    linkContent: { ? }
};

<Pivot styles={pivotStyles} linkSize={PivotLinkSize.large}>
    <PivotItem headerText="Zane"></PivotItem>
    <PivotItem headerText="Kai"></PivotItem>
    <PivotItem headerText="Jay"></PivotItem>
</Pivot>
</code>```

I have experimented with different attributes of both link and linkContent but haven't found a way yet.  I believe what I'm trying to do is manipulate the IStyle interface but I can't find details of the attributes of it.  The link there is very vague.  For example, what are all the available attributes of link, linkContent, etc.?

Any thoughts on this would be most appreciated!

Thank you.

答:
Turns out I was on the right track and just needed the exact fields.  Here's what ended up working:

```<code>const pivotStyles = {
  linkIsSelected: {
    selectors: {
      ':before': {
        height: '6px',   // was previously defaulted at 2px
      }
    }
  }
};
</code>```

I scoured about 4.24 million sites to find this answer but here are some of the most helpful in case they are of interest:

the actual source code of Pivot.styles.ts

the Microsoft Fluent UI Pivot Documentation

A deep examination of the classes using Chrome Dev Tools also helped.  ;)

Here's a picture of the end result:

Body:
I'm trying to increase the height of the line on the selected Pivot item link in Microsoft's Fluent UI using React.

Here's a screenshot for the purposes of clarification:

The orange arrow is pointing to the blue line of which I would like to increase the height.

I have tried setting the styles attribute of the Pivot component but thus far have been unsuccessful.  Here's some code

const pivotStyles: Partial<IStyleSet<IPivotStyles>> = {
    link: { ? },
    linkContent: { ? }
};

<Pivot styles={pivotStyles} linkSize={PivotLinkSize.large}>
    <PivotItem headerText="Zane"></PivotItem>
    <PivotItem headerText="Kai"></PivotItem>
    <PivotItem headerText="Jay"></PivotItem>
</Pivot>

I have experimented with different attributes of both link and linkContent but haven't found a way yet.  I believe what I'm trying to do is manipulate the IStyle interface but I can't find details of the attributes of it.  The link there is very vague.  For example, what are all the available attributes of link, linkContent, etc.?

Any thoughts on this would be most appreciated!

Thank you.

Body:
Turns out I was on the right track and just needed the exact fields.  Here's what ended up working:

const pivotStyles = {
  linkIsSelected: {
    selectors: {
      ':before': {
        height: '6px',   // was previously defaulted at 2px
      }
    }
  }
};

I scoured about 4.24 million sites to find this answer but here are some of the most helpful in case they are of interest:

the actual source code of Pivot.styles.ts

the Microsoft Fluent UI Pivot Documentation

A deep examination of the classes using Chrome Dev Tools also helped.  ;)

Here's a picture of the end result:


问:
How do I suppress the huge stack trace after a rake TestTask failure?
I'm setting up a rakefile for a project, and I've defined some rake TestTasks. I ran a simple sanity test that does an assert_equal(1, 2) just to check the output, and, in addition to the usual failure output, I get this mess:

```<code>rake aborted!
Command failed with status (1): [/usr/bin/ruby -w -I"lib:." "/usr/lib/ruby/...]
/usr/lib/ruby/1.9.1/rake.rb:993:in `block in sh'
/usr/lib/ruby/1.9.1/rake.rb:1008:in `call'
/usr/lib/ruby/1.9.1/rake.rb:1008:in `sh'
/usr/lib/ruby/1.9.1/rake.rb:1092:in `sh'
/usr/lib/ruby/1.9.1/rake.rb:1027:in `ruby'
/usr/lib/ruby/1.9.1/rake.rb:1092:in `ruby'
/usr/lib/ruby/1.9.1/rake/testtask.rb:115:in `block (2 levels) in define'
/usr/lib/ruby/1.9.1/rake.rb:1110:in `verbose'
/usr/lib/ruby/1.9.1/rake/testtask.rb:100:in `block in define'
/usr/lib/ruby/1.9.1/rake.rb:634:in `call'
/usr/lib/ruby/1.9.1/rake.rb:634:in `block in execute'
/usr/lib/ruby/1.9.1/rake.rb:629:in `each'
/usr/lib/ruby/1.9.1/rake.rb:629:in `execute'
/usr/lib/ruby/1.9.1/rake.rb:595:in `block in invoke_with_call_chain'
/usr/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/usr/lib/ruby/1.9.1/rake.rb:588:in `invoke_with_call_chain'
/usr/lib/ruby/1.9.1/rake.rb:605:in `block in invoke_prerequisites'
/usr/lib/ruby/1.9.1/rake.rb:602:in `each'
/usr/lib/ruby/1.9.1/rake.rb:602:in `invoke_prerequisites'
/usr/lib/ruby/1.9.1/rake.rb:594:in `block in invoke_with_call_chain'
/usr/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/usr/lib/ruby/1.9.1/rake.rb:588:in `invoke_with_call_chain'
/usr/lib/ruby/1.9.1/rake.rb:581:in `invoke'
/usr/lib/ruby/1.9.1/rake.rb:2041:in `invoke_task'
/usr/lib/ruby/1.9.1/rake.rb:2019:in `block (2 levels) in top_level'
/usr/lib/ruby/1.9.1/rake.rb:2019:in `each'
/usr/lib/ruby/1.9.1/rake.rb:2019:in `block in top_level'
/usr/lib/ruby/1.9.1/rake.rb:2058:in `standard_exception_handling'
/usr/lib/ruby/1.9.1/rake.rb:2013:in `top_level'
/usr/lib/ruby/1.9.1/rake.rb:1992:in `run'
/usr/bin/rake:31:in `<main>'
</code>```

How do I get rid of it? I don't want to have to scroll up past 20 lines of junk to see my test failures.

答: Rake shouldn't be returning a backtrace in this situation -- the error is with the external command, not rake's internals.  I've sent a email to Jim Weirich regarding the following patch: https://gist.github.com/1003628 </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm setting up a rakefile for a project, and I've defined some rake TestTasks. I ran a simple sanity test that does an assert_equal(1, 2) just to check the output, and, in addition to the usual failure output, I get this mess:

rake aborted!
Command failed with status (1): [/usr/bin/ruby -w -I"lib:." "/usr/lib/ruby/...]
/usr/lib/ruby/1.9.1/rake.rb:993:in `block in sh'
/usr/lib/ruby/1.9.1/rake.rb:1008:in `call'
/usr/lib/ruby/1.9.1/rake.rb:1008:in `sh'
/usr/lib/ruby/1.9.1/rake.rb:1092:in `sh'
/usr/lib/ruby/1.9.1/rake.rb:1027:in `ruby'
/usr/lib/ruby/1.9.1/rake.rb:1092:in `ruby'
/usr/lib/ruby/1.9.1/rake/testtask.rb:115:in `block (2 levels) in define'
/usr/lib/ruby/1.9.1/rake.rb:1110:in `verbose'
/usr/lib/ruby/1.9.1/rake/testtask.rb:100:in `block in define'
/usr/lib/ruby/1.9.1/rake.rb:634:in `call'
/usr/lib/ruby/1.9.1/rake.rb:634:in `block in execute'
/usr/lib/ruby/1.9.1/rake.rb:629:in `each'
/usr/lib/ruby/1.9.1/rake.rb:629:in `execute'
/usr/lib/ruby/1.9.1/rake.rb:595:in `block in invoke_with_call_chain'
/usr/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/usr/lib/ruby/1.9.1/rake.rb:588:in `invoke_with_call_chain'
/usr/lib/ruby/1.9.1/rake.rb:605:in `block in invoke_prerequisites'
/usr/lib/ruby/1.9.1/rake.rb:602:in `each'
/usr/lib/ruby/1.9.1/rake.rb:602:in `invoke_prerequisites'
/usr/lib/ruby/1.9.1/rake.rb:594:in `block in invoke_with_call_chain'
/usr/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/usr/lib/ruby/1.9.1/rake.rb:588:in `invoke_with_call_chain'
/usr/lib/ruby/1.9.1/rake.rb:581:in `invoke'
/usr/lib/ruby/1.9.1/rake.rb:2041:in `invoke_task'
/usr/lib/ruby/1.9.1/rake.rb:2019:in `block (2 levels) in top_level'
/usr/lib/ruby/1.9.1/rake.rb:2019:in `each'
/usr/lib/ruby/1.9.1/rake.rb:2019:in `block in top_level'
/usr/lib/ruby/1.9.1/rake.rb:2058:in `standard_exception_handling'
/usr/lib/ruby/1.9.1/rake.rb:2013:in `top_level'
/usr/lib/ruby/1.9.1/rake.rb:1992:in `run'
/usr/bin/rake:31:in `'

How do I get rid of it? I don't want to have to scroll up past 20 lines of junk to see my test failures.


问:
Catalyst: How to open settings on Mac?
In the original IOS version of my app, the following code successfully opens settings:

```<code>[[UIApplication sharedApplication] openURL:[NSURL  URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success)
{
    ...
}];
</code>```

But after building for Catalyst the command does nothing on the mac. The command does execute, the completion handler fires, and success is set to TRUE. But it does not open the settings window.

How do I programmatically open the settings on Mac Catalyst?

答:
Do you want to open your app’s settings or the macOS System Preferences?

The URL you’re using above opens the iOS Settings app To show your app’s settings, as specified in your Settings.bundle. On macOS, Catalyst apps will automatically create an in-app Preferences window for you from the Settings.bundle. Read more here: https://developer.apple.com/documentation/uikit/mac_catalyst/displaying_a_preferences_window

If you want to open System Preferences, you may be able to do it via openURL using one of these URLs: https://www.mbsplugins.de/archive/2020-04-05/MacOS_System_Preference_Links

Title: Catalyst: How to open settings on Mac?

Body:
In the original IOS version of my app, the following code successfully opens settings:

[[UIApplication sharedApplication] openURL:[NSURL  URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success)
{
    ...
}];

But after building for Catalyst the command does nothing on the mac. The command does execute, the completion handler fires, and success is set to TRUE. But it does not open the settings window.

How do I programmatically open the settings on Mac Catalyst?


问:
JSX template literals for an inline style
I'm trying to add an inline style on an element which includes variables.

Hard-coding the values works:

```<code><circle style={{ strokeDasharray: "75, 25" }} ></circle>
</code>```

But I need a way for both of the numbers in this style to pull from variables.

I've tried a variety of curly braces and backticks - I think I need template literals, but am not sure how the syntax works for them inside of the double curly braces that this inline style seems to require.

This one

```<code><circle style={`{strokeDasharray: "${ percent }, 25"}`} ></circle>
</code>```

fails with message: The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.

This one

```<code><circle style={{`strokeDasharray: "${ percent }, 25"`}} ></circle>
</code>```

causes the build to fail completely.

This one

```<code><circle style={{strokeDasharray: "`${ percent }`, 25"}} ></circle>
</code>```

builds, but no inline style is added at all.

In addition to using the percent variable for the first numeric value, I need to calculate the second numeric value - it will always be 100 minus the percent variable.

答:
```<code>style={{strokeDasharray: `${percent},${100 - percent}`}}
</code>```

Body:
I'm trying to add an inline style on an element which includes variables.

Hard-coding the values works:

<circle style={{ strokeDasharray: "75, 25" }} ></circle>

But I need a way for both of the numbers in this style to pull from variables.

I've tried a variety of curly braces and backticks - I think I need template literals, but am not sure how the syntax works for them inside of the double curly braces that this inline style seems to require.

This one

<circle style={`{strokeDasharray: "${ percent }, 25"}`} ></circle>

fails with message: The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.

This one

<circle style={{`strokeDasharray: "${ percent }, 25"`}} ></circle>

causes the build to fail completely.

This one

<circle style={{strokeDasharray: "`${ percent }`, 25"}} ></circle>

builds, but no inline style is added at all.

In addition to using the percent variable for the first numeric value, I need to calculate the second numeric value - it will always be 100 minus the percent variable.


问:
Angular - How to get data from subscribed service few times and not overwrite previous results
I have a service which has following method:

room-service.ts

@Injectable()
export class RoomService {
  private readonly _equipment: BehaviorSubject<EquipmentDto[]> = new BehaviorSubject([]);
  public equipment$ = this._equipment.asObservable();

  getEquipmentForRoom(roomId: number) {
    this.restService.getEquipmentForRoom(roomId).subscribe(res => {
      this._equipment.next(res);
    });
  }
```

<p>room-component.ts:</p>

<pre class="lang-js prettyprint-override"><code>@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable < EquipmentDto[] > ;
  equipmentList: Array < EquipmentDto > ;

  constructor(private equipmentService: EquipmentService) {}

  ngOnInit() {
      this.equipment$ = this.equipmentService.equipment$;
      this.equipmentService.getEquipmentForRoom(this.room.id);

      this.equipment$.subscribe(items => {
        this.equipmentList = items;
      });
</code>```

room-component.html

```

Now I have a parent component which contains multiple Room Components (those are added programmatically based on the amount of rooms). Anyway, list of equipment is the same for each of the rooms. It looks like once subscribed, the data in first components is overwritten by the component created as the last one.

My question is, how can I get a proper data for each of the rooms using the observable from my service?

答:
try to build pipes instead of subscriptions

@Injectable()
export class RoomService {
      // return an observable.
      getEquipmentForRoom$(roomId: number) {
        return this.restService.getEquipmentForRoom(roomId);
      }
```

<pre class="lang-js prettyprint-override"><code>@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable<EquipmentDto[]>;

  constructor(private equipmentService: EquipmentService){}

  ngOnInit() {
    // simply share observable.
    this.equipment$ = this.equipmentService.getEquipmentForRoom$(this.room.id);
  });
</code>```

```

Body:
I have a service which has following method:

room-service.ts

@Injectable()
export class RoomService {
  private readonly _equipment: BehaviorSubject<EquipmentDto[]> = new BehaviorSubject([]);
  public equipment$ = this._equipment.asObservable();

  getEquipmentForRoom(roomId: number) {
    this.restService.getEquipmentForRoom(roomId).subscribe(res => {
      this._equipment.next(res);
    });
  }

room-component.ts:

@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable < EquipmentDto[] > ;
  equipmentList: Array < EquipmentDto > ;

  constructor(private equipmentService: EquipmentService) {}

  ngOnInit() {
      this.equipment$ = this.equipmentService.equipment$;
      this.equipmentService.getEquipmentForRoom(this.room.id);

      this.equipment$.subscribe(items => {
        this.equipmentList = items;
      });

room-component.html

Now I have a parent component which contains multiple Room Components (those are added programmatically based on the amount of rooms). Anyway, list of equipment is the same for each of the rooms. It looks like once subscribed, the data in first components is overwritten by the component created as the last one.

My question is, how can I get a proper data for each of the rooms using the observable from my service?

Body:
try to build pipes instead of subscriptions

@Injectable()
export class RoomService {
      // return an observable.
      getEquipmentForRoom$(roomId: number) {
        return this.restService.getEquipmentForRoom(roomId);
      }

@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable<EquipmentDto[]>;

  constructor(private equipmentService: EquipmentService){}

  ngOnInit() {
    // simply share observable.
    this.equipment$ = this.equipmentService.getEquipmentForRoom$(this.room.id);
  });

  <div *ngFor="let eq of equipment$ | async"> <!-- add async here -->
      <!-- list my equipment here -->
  </div>


问:
Swift crash in swift_getSingletonMetadata, "type metadata accessor"
I've been getting some weird crash logs from my Mac app. Here's the crashed thread:

```<code>OS Version:      Mac OS X 10.14.6 (18G103)
Report Version:  104

Exception Type:  SIGSEGV
Exception Codes: SEGV_MAPERR at 0x0
Crashed Thread:  8

Thread 8 Crashed:
0   ???                                  0x0000000000000000 0x0 + 0
1   libswiftCore.dylib                   0x00007fff79a743f3 swift_getSingletonMetadata + 578
2   PowerPhotos                          0x000000010323f30d type metadata accessor for PowerPhotos.IPAssetCollectionUpdate (<compiler-generated>:0)
3   libswiftCore.dylib                   0x00007fff79a8c94c swift::TargetProtocolConformanceDescriptor<swift::InProcess>::getCanonicalTypeMetadata() const + 171
4   libswiftCore.dylib                   0x00007fff79a8da24 swift_conformsToSwiftProtocolImpl(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, llvm::StringRef) + 291
5   libswiftCore.dylib                   0x00007fff79a8d884 swift_conformsToProtocolImpl(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*) + 99
6   PowerPhotos                          0x000000010339e7a9 swift::swift50override_conformsToProtocol(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, swift::TargetWitnessTable<swift::InProcess> const* (*)(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*)) + 56
7   libswiftCore.dylib                   0x00007fff79a6215a swift::_conformsToProtocol(swift::OpaqueValue const*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptorRef<swift::InProcess>, swift::TargetWitnessTable<swift::InProcess> const**) + 41
8   libswiftCore.dylib                   0x00007fff79a65f97 _conformsToProtocols(swift::OpaqueValue const*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetExistentialTypeMetadata<swift::InProcess> const*, swift::TargetWitnessTable<swift::InProcess> const**) + 230
9   libswiftCore.dylib                   0x00007fff79a65369 _dynamicCastToExistential(swift::OpaqueValue*, swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetExistentialTypeMetadata<swift::InProcess> const*, swift::DynamicCastFlags) + 488
10  libswiftCore.dylib                   0x00007fff79836517 Swift._print_unlocked<A, B where B: Swift.TextOutputStream>(A, inout B) -> () + 550
11  PowerPhotos                          0x00000001031e2483 PowerPhotos.IPArchiveUpdateOperation.(loadFromReplay in _C3BCBD43848FA0F2A85DA8591115A6A7)() -> PowerPhotos.IPArchiveLoadResult (<compiler-generated>:0)
12  PowerPhotos                          0x00000001031e1700 PowerPhotos.IPArchiveUpdateOperation.(loadFromPreferredDatabase in _C3BCBD43848FA0F2A85DA8591115A6A7)() -> (PowerPhotos.IPArchiveLoadResult, Swift.Error?) (IPArchiveUpdateOperation.swift:430)
13  PowerPhotos                          0x00000001031e08fa PowerPhotos.IPArchiveUpdateOperation.perform() throws -> Any (IPArchiveUpdateOperation.swift:218)
14  PowerPhotos                          0x00000001031e179c @objc PowerPhotos.IPArchiveUpdateOperation.perform() throws -> Any (<compiler-generated>:0)
15  BWFoundation                         0x00000001036c8173 -[BWOperation main] (BWOperation.m:124)
16  PowerPhotosKit                       0x0000000103898e71 -[IPOperation main] (IPOperation.m:287)
17  Foundation                           0x00007fff502f5ced -[__NSOperationInternal _start:] + 684
18  Foundation                           0x00007fff5031fca7 __NSOQSchedule_f + 226
19  libdispatch.dylib                    0x00007fff7a0055f8 _dispatch_call_block_and_release + 11
20  libdispatch.dylib                    0x00007fff7a00663d _dispatch_client_callout + 7
21  libdispatch.dylib                    0x00007fff7a008de6 _dispatch_continuation_pop + 413
22  libdispatch.dylib                    0x00007fff7a0084a3 _dispatch_async_redirect_invoke + 702
23  libdispatch.dylib                    0x00007fff7a0143bc _dispatch_root_queue_drain + 323
24  libdispatch.dylib                    0x00007fff7a014b46 _dispatch_worker_thread2 + 89
25  libsystem_pthread.dylib              0x00007fff7a2466b3 _pthread_wqthread + 582
26  libsystem_pthread.dylib              0x00007fff7a2463fd start_wqthread + 12
27  ???                                  0x0000000054485244 0x0 + 0
</code>```

Frame 11 is the last time my own code is seen, that line of code looks like this:

```<code>return IPArchiveLoadResult(error: NSError(description: "Replay did not complete \(replayDatabase.replayState.debugDescription)"))
</code>```

So it looks like the call to debugDescription is what's generating the rest of the stack trace, to create that interpolated string. This ultimately ends up in frame 3 which references 'type metadata accessor for PowerPhotos.IPAssetCollectionUpdate'.

But here's the weird thing: IPAssetCollectionUpdate has absolutely nothing to do with the code that's calling this stuff. It's in an entirely different part of the application. So I think it's mostly coincidental that this is triggering whatever metadata loading Swift is doing here.

Looking at IPAssetCollectionUpdate, I think I see what's probably tripping it up:

```<code>@available(OSX 10.15, *)
struct IPAssetCollectionUpdate {
    let assetCollection: PHAssetCollection
    let diff: CollectionDifference<PHAsset>
}
</code>```

Notice that IPAssetCollectionUpdate is marked as available only on macOS 10.15, and the crashes are all occurring on macOS 10.14. PHAssetCollection and PHAsset do exist on macOS 10.14, but CollectionDifference does not. This isn't a problem in the rest of the app, since everything's protected by the @available directive, but it seems that the Swift runtime is still trying to dig into this struct and generate some internal metadata and blowing up when it can't handle CollectionDifference. Or something like that?

Anyway, that's the setup, so my questions are:

Should this be considered a Swift bug? It seems like with everything properly annotated with availability directives, I should be able to ship this on macOS 10.14 and not have things crash, since I'm never actually using this struct at all on 10.14.

Regardless of whose fault it is, is there any way I can change this code so that it doesn't blow up on 10.14? The best I can think of is to break it out into a loadable bundle in my app and load the bundle manually when running on 10.15. That seems like a lot of work for this silly problem though, and I'd like to know if there's some other simpler way to handle this.

I'm compiling this using Xcode 11.5 and Swift 5.

答:
OK, Stack Overflow was a good rubber duck for me here, I was able to avoid the crash by doing the following:

```<code>struct IPAssetCollectionUpdate {
    let assetCollection: PHAssetCollection
    let typeErasedDiff: Any

    var diff: CollectionDifference<PHAsset> {
        return self.typeErasedDiff as! CollectionDifference<PHAsset>
    }
}
</code>```

It's terrible, but it works. But my question about whether this should be considered a Swift bug remains, and whether there's a more sanctioned way to write this type of code.

Body:
I've been getting some weird crash logs from my Mac app. Here's the crashed thread:

OS Version:      Mac OS X 10.14.6 (18G103)
Report Version:  104

Exception Type:  SIGSEGV
Exception Codes: SEGV_MAPERR at 0x0
Crashed Thread:  8

Thread 8 Crashed:
0   ???                                  0x0000000000000000 0x0 + 0
1   libswiftCore.dylib                   0x00007fff79a743f3 swift_getSingletonMetadata + 578
2   PowerPhotos                          0x000000010323f30d type metadata accessor for PowerPhotos.IPAssetCollectionUpdate (<compiler-generated>:0)
3   libswiftCore.dylib                   0x00007fff79a8c94c swift::TargetProtocolConformanceDescriptor<swift::InProcess>::getCanonicalTypeMetadata() const + 171
4   libswiftCore.dylib                   0x00007fff79a8da24 swift_conformsToSwiftProtocolImpl(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, llvm::StringRef) + 291
5   libswiftCore.dylib                   0x00007fff79a8d884 swift_conformsToProtocolImpl(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*) + 99
6   PowerPhotos                          0x000000010339e7a9 swift::swift50override_conformsToProtocol(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, swift::TargetWitnessTable<swift::InProcess> const* (*)(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*)) + 56
7   libswiftCore.dylib                   0x00007fff79a6215a swift::_conformsToProtocol(swift::OpaqueValue const*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptorRef<swift::InProcess>, swift::TargetWitnessTable<swift::InProcess> const**) + 41
8   libswiftCore.dylib                   0x00007fff79a65f97 _conformsToProtocols(swift::OpaqueValue const*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetExistentialTypeMetadata<swift::InProcess> const*, swift::TargetWitnessTable<swift::InProcess> const**) + 230
9   libswiftCore.dylib                   0x00007fff79a65369 _dynamicCastToExistential(swift::OpaqueValue*, swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetExistentialTypeMetadata<swift::InProcess> const*, swift::DynamicCastFlags) + 488
10  libswiftCore.dylib                   0x00007fff79836517 Swift._print_unlocked(A, inout B) -> () + 550
11  PowerPhotos                          0x00000001031e2483 PowerPhotos.IPArchiveUpdateOperation.(loadFromReplay in _C3BCBD43848FA0F2A85DA8591115A6A7)() -> PowerPhotos.IPArchiveLoadResult (<compiler-generated>:0)
12  PowerPhotos                          0x00000001031e1700 PowerPhotos.IPArchiveUpdateOperation.(loadFromPreferredDatabase in _C3BCBD43848FA0F2A85DA8591115A6A7)() -> (PowerPhotos.IPArchiveLoadResult, Swift.Error?) (IPArchiveUpdateOperation.swift:430)
13  PowerPhotos                          0x00000001031e08fa PowerPhotos.IPArchiveUpdateOperation.perform() throws -> Any (IPArchiveUpdateOperation.swift:218)
14  PowerPhotos                          0x00000001031e179c @objc PowerPhotos.IPArchiveUpdateOperation.perform() throws -> Any (<compiler-generated>:0)
15  BWFoundation                         0x00000001036c8173 -[BWOperation main] (BWOperation.m:124)
16  PowerPhotosKit                       0x0000000103898e71 -[IPOperation main] (IPOperation.m:287)
17  Foundation                           0x00007fff502f5ced -[__NSOperationInternal _start:] + 684
18  Foundation                           0x00007fff5031fca7 __NSOQSchedule_f + 226
19  libdispatch.dylib                    0x00007fff7a0055f8 _dispatch_call_block_and_release + 11
20  libdispatch.dylib                    0x00007fff7a00663d _dispatch_client_callout + 7
21  libdispatch.dylib                    0x00007fff7a008de6 _dispatch_continuation_pop + 413
22  libdispatch.dylib                    0x00007fff7a0084a3 _dispatch_async_redirect_invoke + 702
23  libdispatch.dylib                    0x00007fff7a0143bc _dispatch_root_queue_drain + 323
24  libdispatch.dylib                    0x00007fff7a014b46 _dispatch_worker_thread2 + 89
25  libsystem_pthread.dylib              0x00007fff7a2466b3 _pthread_wqthread + 582
26  libsystem_pthread.dylib              0x00007fff7a2463fd start_wqthread + 12
27  ???                                  0x0000000054485244 0x0 + 0

Frame 11 is the last time my own code is seen, that line of code looks like this:

return IPArchiveLoadResult(error: NSError(description: "Replay did not complete \(replayDatabase.replayState.debugDescription)"))

So it looks like the call to debugDescription is what's generating the rest of the stack trace, to create that interpolated string. This ultimately ends up in frame 3 which references 'type metadata accessor for PowerPhotos.IPAssetCollectionUpdate'.

But here's the weird thing: IPAssetCollectionUpdate has absolutely nothing to do with the code that's calling this stuff. It's in an entirely different part of the application. So I think it's mostly coincidental that this is triggering whatever metadata loading Swift is doing here.

Looking at IPAssetCollectionUpdate, I think I see what's probably tripping it up:

@available(OSX 10.15, *)
struct IPAssetCollectionUpdate {
    let assetCollection: PHAssetCollection
    let diff: CollectionDifference<PHAsset>
}

Notice that IPAssetCollectionUpdate is marked as available only on macOS 10.15, and the crashes are all occurring on macOS 10.14. PHAssetCollection and PHAsset do exist on macOS 10.14, but CollectionDifference does not. This isn't a problem in the rest of the app, since everything's protected by the @available directive, but it seems that the Swift runtime is still trying to dig into this struct and generate some internal metadata and blowing up when it can't handle CollectionDifference. Or something like that?

Anyway, that's the setup, so my questions are:

Should this be considered a Swift bug? It seems like with everything properly annotated with availability directives, I should be able to ship this on macOS 10.14 and not have things crash, since I'm never actually using this struct at all on 10.14.

Regardless of whose fault it is, is there any way I can change this code so that it doesn't blow up on 10.14? The best I can think of is to break it out into a loadable bundle in my app and load the bundle manually when running on 10.15. That seems like a lot of work for this silly problem though, and I'd like to know if there's some other simpler way to handle this.

I'm compiling this using Xcode 11.5 and Swift 5.

Body:
OK, Stack Overflow was a good rubber duck for me here, I was able to avoid the crash by doing the following:

struct IPAssetCollectionUpdate {
    let assetCollection: PHAssetCollection
    let typeErasedDiff: Any

    var diff: CollectionDifference<PHAsset> {
        return self.typeErasedDiff as! CollectionDifference<PHAsset>
    }
}

It's terrible, but it works. But my question about whether this should be considered a Swift bug remains, and whether there's a more sanctioned way to write this type of code.


问:
Problem with Login control of ASP.NET
I set up a website to use SqlMembershipProvider as written on this page.

I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with.

I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in.

I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists.

I already tried to handle the events by myself and check, what is happening in them, but no success.

I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome.

Any ideas?

Resolution: After some mailing with Rob we have the ideal solution, which is now the accepted answer.

答:
RE: The Accepted Answer

I do not like the hack given.

I have a site that uses a login form called "login.aspx" and all works fine. I think we should actually find the answer rather than hack. Since all the [presumably] tested sites work. Do you not think we should actually use StackOverflow to find the ACTUAL problem? (making it much more useful than anywhere else?)

In the LoginCtl_Authenticate event are you setting the EventArgs.Authenticated property to true?

e.g.

```<code>protected void LoginCtl_Authenticate(object sender, AuthenticateEventArgs e)
{
   // Check the Credentials against DB
   bool authed = DAL.Authenticate(user, pass);
   e.Authenticated = authed;
}
</code>```

OwnerDisplayName: Biri

Title: Problem with Login control of ASP.NET

LastEditorDisplayName: Biri

Body:
RE: The Accepted Answer

I do not like the hack given.

I have a site that uses a login form called "login.aspx" and all works fine. I think we should actually find the answer rather than hack. Since all the [presumably] tested sites work. Do you not think we should actually use StackOverflow to find the ACTUAL problem? (making it much more useful than anywhere else?)

In the LoginCtl_Authenticate event are you setting the EventArgs.Authenticated property to true?

e.g.

protected void LoginCtl_Authenticate(object sender, AuthenticateEventArgs e)
{
   // Check the Credentials against DB
   bool authed = DAL.Authenticate(user, pass);
   e.Authenticated = authed;
}

OwnerDisplayName: Rob Cooper


问:
Mock abstract class default behaviour with Rhino
I'm pretty new to mocking so this might be something I'm just not picking up on yet, but I can't find a good example anywhere.

I'm trying to assert that by default, any class that inherits from my abstract class will instantiate a collection in the constructor.  Here's the abstract class:

```<code>public abstract class DataCollectionWorkflow : SequentialWorkflowActivity
{
        private readonly DataSet _output = new DataSet();
        private List<DataCollectionParameter> _params = null;

        public DataCollectionWorkflow()
        {
            _params = new List<DataCollectionParameter>();
        }

        public virtual IList<DataCollectionParameter> Parameters
        {
            get { return _params; }
            set { _params = (List<DataCollectionParameter>)value; }
        }
}
</code>```

How do I mock this with Rhino?  If I do a GenerateMock<DataCollectionWorkflow> (or a stub), the constructor runs and the mock's private field "_params" gets initialized, but the mock's "Parameters" property is simply null.

Obviously the generated mock subclass is overriding the property implementation.  Is there some way of excluding the Parameters property from being re-implemented?

Thanks.

答: Try making _params virtual</p>

OwnerDisplayName: womp

Body:
I'm pretty new to mocking so this might be something I'm just not picking up on yet, but I can't find a good example anywhere.

I'm trying to assert that by default, any class that inherits from my abstract class will instantiate a collection in the constructor.  Here's the abstract class:

public abstract class DataCollectionWorkflow : SequentialWorkflowActivity
{
        private readonly DataSet _output = new DataSet();
        private List<DataCollectionParameter> _params = null;

        public DataCollectionWorkflow()
        {
            _params = new List<DataCollectionParameter>();
        }

        public virtual IList<DataCollectionParameter> Parameters
        {
            get { return _params; }
            set { _params = (List<DataCollectionParameter>)value; }
        }
}

How do I mock this with Rhino?  If I do a GenerateMock<DataCollectionWorkflow> (or a stub), the constructor runs and the mock's private field "_params" gets initialized, but the mock's "Parameters" property is simply null.

Obviously the generated mock subclass is overriding the property implementation.  Is there some way of excluding the Parameters property from being re-implemented?

Thanks.

Body: Try making _params virtual

OwnerDisplayName: Chance


问:
Should we learn Window Form before WPF?
Is there a learning curve? I want to pick up Windows Form but when reading many threads about WF vs WPF, I was totally persuaded by WPF. What should I do? </p>

答:
Nope!
WPF is the latest trend. Winforms is not quite dead yet though...

If somebody wants to learn window application development. Starting from WPF will take him to the latest trend. Of course, Winform previous experience can be an advantage.

Title: Should we learn Window Form before WPF?


问:
Unable to get bar-code bounding box in right position on overlay Surfaceview
I'm using my CameraX with Firebase MLKit bar-code reader to detect barcode code. Application Identifies the bar-code without a problem. But I'm trying to add bounding box which shows the area of the barcode in CameraX preview in real-time. The Bounding box information is retrieved from the bar-code detector function. But It doesn't have nither right position nor size as you can see below.

This is my layout of the activity.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/camera_capture_button"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginBottom="50dp"
        android:scaleType="fitCenter"
        android:text="Take Photo"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:elevation="2dp" />

    <SurfaceView
        android:id="@+id/overlayView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <androidx.camera.view.PreviewView
        android:id="@+id/previewView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

SurfaceView is used to draw this rectangle shape.

Barcode detection happens in the BarcodeAnalyzer class which implements ImageAnalysis.Analyzer. inside overwritten analyze function I retrieve the barcode data like below.

```<code>@SuppressLint("UnsafeExperimentalUsageError")
    override fun analyze(imageProxy: ImageProxy) {

        val mediaImage = imageProxy.image

        val rotationDegrees = degreesToFirebaseRotation(imageProxy.imageInfo.rotationDegrees)

        if (mediaImage != null) {

            val analyzedImageHeight = mediaImage.height
            val analyzedImageWidth = mediaImage.width

            val image = FirebaseVisionImage
                .fromMediaImage(mediaImage,rotationDegrees)

            detector.detectInImage(image)
                .addOnSuccessListener { barcodes ->

                    for (barcode in barcodes) {
                        val bounds = barcode.boundingBox
                        val corners = barcode.cornerPoints
                        val rawValue = barcode.rawValue

                        if(::barcodeDetectListener.isInitialized && rawValue != null && bounds != null){
                            barcodeDetectListener.onBarcodeDetect(
                                rawValue,
                                bounds,
                                analyzedImageWidth,
                                analyzedImageHeight
                            )
                        }
                    }

                    imageProxy.close()

                }
                .addOnFailureListener {
                    Log.e(tag,"Barcode Reading Exception: ${it.localizedMessage}")
                    imageProxy.close()
                }
                .addOnCanceledListener {
                    Log.e(tag,"Barcode Reading Canceled")
                    imageProxy.close()
                }

        }
    }
</code>```

barcodeDetectListener is a reference to an interface I create to communicate this data back into my activity.

```<code>interface BarcodeDetectListener {
    fun onBarcodeDetect(code: String, codeBound: Rect, imageWidth: Int, imageHeight: Int)
}
</code>```

In my main activity, I send these data to OverlaySurfaceHolder which implements the SurfaceHolder.Callback. This class is responsible for drawing a bounding box on overlayed SurfaceView.

```<code>override fun onBarcodeDetect(code: String, codeBound: Rect, analyzedImageWidth: Int,
                                 analyzedImageHeight: Int) {

        Log.i(TAG,"barcode : $code")
        overlaySurfaceHolder.repositionBound(codeBound,previewView.width,previewView.height,
            analyzedImageWidth,analyzedImageHeight)
        overlayView.invalidate()

    }
</code>```

As you can see here I'm sending overlayed SurfaceView width and height for the calculation in OverlaySurfaceHolder class.

OverlaySurfaceHolder.kt

```<code>class OverlaySurfaceHolder: SurfaceHolder.Callback {

    var previewViewWidth: Int = 0
    var previewViewHeight: Int = 0
    var analyzedImageWidth: Int = 0
    var analyzedImageHeight: Int = 0

    private lateinit var drawingThread: DrawingThread
    private lateinit var barcodeBound :Rect

    private  val tag = OverlaySurfaceHolder::class.java.simpleName

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {

        var retry = true
        drawingThread.running = false

        while (retry){
            try {
                drawingThread.join()
                retry = false
            } catch (e: InterruptedException) {
            }
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        drawingThread = DrawingThread(holder)
        drawingThread.running = true
        drawingThread.start()
    }

    fun repositionBound(codeBound: Rect, previewViewWidth: Int, previewViewHeight: Int,
                        analyzedImageWidth: Int, analyzedImageHeight: Int){

        this.barcodeBound = codeBound
        this.previewViewWidth = previewViewWidth
        this.previewViewHeight = previewViewHeight
        this.analyzedImageWidth = analyzedImageWidth
        this.analyzedImageHeight = analyzedImageHeight
    }

    inner class DrawingThread(private val holder: SurfaceHolder?): Thread() {

        var running = false

        private fun adjustXCoordinates(valueX: Int): Float{

            return if(previewViewWidth != 0){
                (valueX / analyzedImageWidth.toFloat()) * previewViewWidth.toFloat()
            }else{
                valueX.toFloat()
            }
        }

        private fun adjustYCoordinates(valueY: Int): Float{

            return if(previewViewHeight != 0){
                (valueY / analyzedImageHeight.toFloat()) * previewViewHeight.toFloat()
            }else{
                valueY.toFloat()
            }
        }

        override fun run() {

            while(running){

                if(::barcodeBound.isInitialized){

                    val canvas = holder!!.lockCanvas()

                    if (canvas != null) {

                        synchronized(holder) {

                            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

                            val myPaint = Paint()
                            myPaint.color = Color.rgb(20, 100, 50)
                            myPaint.strokeWidth = 6f
                            myPaint.style = Paint.Style.STROKE

                            val refinedRect = RectF()
                            refinedRect.left = adjustXCoordinates(barcodeBound.left)
                            refinedRect.right = adjustXCoordinates(barcodeBound.right)
                            refinedRect.top = adjustYCoordinates(barcodeBound.top)
                            refinedRect.bottom = adjustYCoordinates(barcodeBound.bottom)

                            canvas.drawRect(refinedRect,myPaint)
                        }

                        holder.unlockCanvasAndPost(canvas)

                    }else{
                        Log.e(tag, "Cannot draw onto the canvas as it's null")
                    }

                    try {
                        sleep(30)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }

                }
            }
        }

    }
}
</code>```

Please can anyone point me out what am I doing wrong?

答:
I don't have a very clear clue, but here are something you could try:

When you adjustXCoordinates, if previewWidth is 0, you return valueX.toFloat() directly. Could you add something logging to see it it actually falls into this case?  Also adding some logs to print the analysis and preview dimension could be helpful as well.

Another thing worth noting is that the image you sent to the detector could have different aspect ratio from the preview View area. For example, if your camera takes a 4:3 photo, it will send it to detector. However, if your View area is 1:1, it will crop some part of the photos to display it there. In that case, you need to take this into consideration as well when adjust coordinates. Base on my testing, the image will fit into the View area based on CENTER_CROP. If you want to be really careful, probably worth checking if this is documented in the camera dev site.

Hope it helps, more or less.

Body:
I'm using my CameraX with Firebase MLKit bar-code reader to detect barcode code. Application Identifies the bar-code without a problem. But I'm trying to add bounding box which shows the area of the barcode in CameraX preview in real-time. The Bounding box information is retrieved from the bar-code detector function. But It doesn't have nither right position nor size as you can see below.

This is my layout of the activity.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/camera_capture_button"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginBottom="50dp"
        android:scaleType="fitCenter"
        android:text="Take Photo"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:elevation="2dp" />

    <SurfaceView
        android:id="@+id/overlayView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <androidx.camera.view.PreviewView
        android:id="@+id/previewView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

SurfaceView is used to draw this rectangle shape.

Barcode detection happens in the BarcodeAnalyzer class which implements ImageAnalysis.Analyzer. inside overwritten analyze function I retrieve the barcode data like below.

@SuppressLint("UnsafeExperimentalUsageError")
    override fun analyze(imageProxy: ImageProxy) {

        val mediaImage = imageProxy.image

        val rotationDegrees = degreesToFirebaseRotation(imageProxy.imageInfo.rotationDegrees)

        if (mediaImage != null) {

            val analyzedImageHeight = mediaImage.height
            val analyzedImageWidth = mediaImage.width

            val image = FirebaseVisionImage
                .fromMediaImage(mediaImage,rotationDegrees)

            detector.detectInImage(image)
                .addOnSuccessListener { barcodes ->

                    for (barcode in barcodes) {
                        val bounds = barcode.boundingBox
                        val corners = barcode.cornerPoints
                        val rawValue = barcode.rawValue

                        if(::barcodeDetectListener.isInitialized && rawValue != null && bounds != null){
                            barcodeDetectListener.onBarcodeDetect(
                                rawValue,
                                bounds,
                                analyzedImageWidth,
                                analyzedImageHeight
                            )
                        }
                    }

                    imageProxy.close()

                }
                .addOnFailureListener {
                    Log.e(tag,"Barcode Reading Exception: ${it.localizedMessage}")
                    imageProxy.close()
                }
                .addOnCanceledListener {
                    Log.e(tag,"Barcode Reading Canceled")
                    imageProxy.close()
                }

        }
    }

barcodeDetectListener is a reference to an interface I create to communicate this data back into my activity.

interface BarcodeDetectListener {
    fun onBarcodeDetect(code: String, codeBound: Rect, imageWidth: Int, imageHeight: Int)
}

In my main activity, I send these data to OverlaySurfaceHolder which implements the SurfaceHolder.Callback. This class is responsible for drawing a bounding box on overlayed SurfaceView.

override fun onBarcodeDetect(code: String, codeBound: Rect, analyzedImageWidth: Int,
                                 analyzedImageHeight: Int) {

        Log.i(TAG,"barcode : $code")
        overlaySurfaceHolder.repositionBound(codeBound,previewView.width,previewView.height,
            analyzedImageWidth,analyzedImageHeight)
        overlayView.invalidate()

    }

As you can see here I'm sending overlayed SurfaceView width and height for the calculation in OverlaySurfaceHolder class.

OverlaySurfaceHolder.kt

class OverlaySurfaceHolder: SurfaceHolder.Callback {

    var previewViewWidth: Int = 0
    var previewViewHeight: Int = 0
    var analyzedImageWidth: Int = 0
    var analyzedImageHeight: Int = 0

    private lateinit var drawingThread: DrawingThread
    private lateinit var barcodeBound :Rect

    private  val tag = OverlaySurfaceHolder::class.java.simpleName

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {

        var retry = true
        drawingThread.running = false

        while (retry){
            try {
                drawingThread.join()
                retry = false
            } catch (e: InterruptedException) {
            }
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        drawingThread = DrawingThread(holder)
        drawingThread.running = true
        drawingThread.start()
    }

    fun repositionBound(codeBound: Rect, previewViewWidth: Int, previewViewHeight: Int,
                        analyzedImageWidth: Int, analyzedImageHeight: Int){

        this.barcodeBound = codeBound
        this.previewViewWidth = previewViewWidth
        this.previewViewHeight = previewViewHeight
        this.analyzedImageWidth = analyzedImageWidth
        this.analyzedImageHeight = analyzedImageHeight
    }

    inner class DrawingThread(private val holder: SurfaceHolder?): Thread() {

        var running = false

        private fun adjustXCoordinates(valueX: Int): Float{

            return if(previewViewWidth != 0){
                (valueX / analyzedImageWidth.toFloat()) * previewViewWidth.toFloat()
            }else{
                valueX.toFloat()
            }
        }

        private fun adjustYCoordinates(valueY: Int): Float{

            return if(previewViewHeight != 0){
                (valueY / analyzedImageHeight.toFloat()) * previewViewHeight.toFloat()
            }else{
                valueY.toFloat()
            }
        }

        override fun run() {

            while(running){

                if(::barcodeBound.isInitialized){

                    val canvas = holder!!.lockCanvas()

                    if (canvas != null) {

                        synchronized(holder) {

                            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

                            val myPaint = Paint()
                            myPaint.color = Color.rgb(20, 100, 50)
                            myPaint.strokeWidth = 6f
                            myPaint.style = Paint.Style.STROKE

                            val refinedRect = RectF()
                            refinedRect.left = adjustXCoordinates(barcodeBound.left)
                            refinedRect.right = adjustXCoordinates(barcodeBound.right)
                            refinedRect.top = adjustYCoordinates(barcodeBound.top)
                            refinedRect.bottom = adjustYCoordinates(barcodeBound.bottom)

                            canvas.drawRect(refinedRect,myPaint)
                        }

                        holder.unlockCanvasAndPost(canvas)

                    }else{
                        Log.e(tag, "Cannot draw onto the canvas as it's null")
                    }

                    try {
                        sleep(30)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }

                }
            }
        }

    }
}

Please can anyone point me out what am I doing wrong?


问:
Mssql_query can return values after db close, while sqlsrv_query cannot
I am new to backend developer, so this might be dumb if i am wrong in the begining.I found out that sqlsrv and mssql ways of handling db are different. For example, mssql_query can return data after db close, but sqlsrv_query cannot.
For example:

```<code>$query = "select branchname, id from Branch";
$rs = $this->db->query($query);
$this->db->close();
Return $rs;
</code>```

This code can pass values to the controllers in mssql_driver ,but cannot pass to controllers in sqlsrv_driver. After i remove the db close function, it works in sqlsrv.So i think that these 2 are different.Or am i wrong? Please teach me

答:
You are right, can be read here -> SQLSRV->Close and here -> MSSQL->Close

The SQLSRV close method releases resourses associated with the connection and MSSQL does not.

Body:
I am new to backend developer, so this might be dumb if i am wrong in the begining.I found out that sqlsrv and mssql ways of handling db are different. For example, mssql_query can return data after db close, but sqlsrv_query cannot.
For example:

$query = "select branchname, id from Branch";
$rs = $this->db->query($query);
$this->db->close();
Return $rs;

This code can pass values to the controllers in mssql_driver ,but cannot pass to controllers in sqlsrv_driver. After i remove the db close function, it works in sqlsrv.So i think that these 2 are different.Or am i wrong? Please teach me


问:
Insering cell break line in AG-GRID Angular
Im displaying 2 data in one cell with ag-grid but i want the data to be with break line not like this :
Data without break line

i tried to use "\n" "\r" "\br" but didnt work. here is my code :

```<code>    import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Grid, GridApi } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';
import { DealsService } from './services/deals.service';
import * as moment from 'moment';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'app';

columnDefs = [
{headerName: 'Class', cellRenderer: function(params){ return params.data.DEALCAT + params.data.DEALID},width:150, filter: true} ,

];

rowData : any;
constructor(private service:DealsService) {

}
dateFormatter(params){
return moment(params.value).format('DD/MM/YYYY');
}

ngOnInit() {
this.service.getDealsList().subscribe(data => {
this.rowData = data;
}); }

}
</code>```

and here is the code html :

```<code><ag-grid-angular class="ag-theme-balham" ng-grid="gridOptions"
style="width: 1350px; height: 630px;"
class="ag-theme-alpine"
[rowData]="rowData"
[columnDefs]="columnDefs"

[animateRows]="true"
[paginationPageSize]="10"
[pagination]="true"
>
</ag-grid-angular>
</code>```

答:
Try like this </p>

```<code>cellRenderer: function(param){
    return param.data.DEALCAT + '<br/>' + param.data.DEALID;
  }
</code>```

Body:
Im displaying 2 data in one cell with ag-grid but i want the data to be with break line not like this :
Data without break line

i tried to use "\n" "\r" "\br" but didnt work. here is my code :

    import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Grid, GridApi } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';
import { DealsService } from './services/deals.service';
import * as moment from 'moment';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'app';

columnDefs = [
{headerName: 'Class', cellRenderer: function(params){ return params.data.DEALCAT + params.data.DEALID},width:150, filter: true} ,

];

rowData : any;
constructor(private service:DealsService) {

}
dateFormatter(params){
return moment(params.value).format('DD/MM/YYYY');
}

ngOnInit() {
this.service.getDealsList().subscribe(data => {
this.rowData = data;
}); }

}

and here is the code html :

<ag-grid-angular class="ag-theme-balham" ng-grid="gridOptions"
style="width: 1350px; height: 630px;"
class="ag-theme-alpine"
[rowData]="rowData"
[columnDefs]="columnDefs"

[animateRows]="true"
[paginationPageSize]="10"
[pagination]="true"
>
</ag-grid-angular>

Body:
Try like this

cellRenderer: function(param){
    return param.data.DEALCAT + '<br/>' + param.data.DEALID;
  }


问:
Is NotNull needed on Kotlin?
I have a class:

```<code>class User(

    var name: String

)
</code>```

And a mapped post request:

```<code>@PostMapping("/user")
fun test(@Valid @RequestBody user: User) {
    //...
}
</code>```

What if a client will send a JSON of a user with name: null? Will it be rejected by the MVC Validator or an exception will be throwed? Should I annotate name with @NotNull? Unfortunately, I cannot check that because only can write tests (it is not available to create User(null)).

答:
My workarround for now (place the file anywhere):

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
class ExceptionHandler {

    @ResponseStatus(BAD_REQUEST)
    @ResponseBody
    @ExceptionHandler(MissingKotlinParameterException::class)
    fun missingKotlinParameterException(ex: MissingKotlinParameterException): Error? {
        return createMissingKotlinParameterViolation(ex)
    }

    private fun createMissingKotlinParameterViolation(ex: MissingKotlinParameterException): Error{
        val error = Error(BAD_REQUEST.value(), "validation error")
        val errorFieldRegex = Regex("\\.([^.]*)\\[\\\"(.*)\"\\]\$")
        val errorMatch = errorFieldRegex.find(ex.path[0].description)!!
        val (objectName, field) = errorMatch.destructured
        error.addFieldError(objectName.decapitalize(), field, "must not be null")
        return error
    }

    data class Error(val status: Int, val message: String, val fieldErrors: MutableList<CustomFieldError> = mutableListOf()) {
        fun addFieldError(objectName: String, field: String, message: String) {
            val error = CustomFieldError(objectName, field, message)
            fieldErrors.add(error)
        }
    }

    data class CustomFieldError(val objectName: String, val field: String, val message: String)
```

Title: Is NotNull needed on Kotlin?

Body:
I have a class:

class User(

    var name: String

)

And a mapped post request:

@PostMapping("/user")
fun test(@Valid @RequestBody user: User) {
    //...
}

What if a client will send a JSON of a user with name: null? Will it be rejected by the MVC Validator or an exception will be throwed? Should I annotate name with @NotNull? Unfortunately, I cannot check that because only can write tests (it is not available to create User(null)).