问:
My input is not proceeding to the next page
I have created a form where the user will enter some information and the email will have to be validated before the user can proceed to the next page (thankyou.html) however when i input every thing correctly into the form the email gets validated but i cannot get to the next page...i cant figure out what im doing wrong. Any help would be appreciated and thank you in advance.</p>

```<code><script type = "text/javascript">

    function validate()
        {
            var text = document.getElementById("text1").value;
            var regx = /^([a-zA-Z0-9\.-]+)@([a-zA-Z0-9-]+)\.([a-z]{3})$/;
            var uname = document.getElementById("name");
            var title = document.getElementById("title1");
            var comment = document.getElementById("cmt");

        if(regx.test(text))
            {
            document.getElementById("lbltext").innerHTML="you may proceed";
            document.getElementById("lbltext").style.visibility="visible";
            document.getElementById("lbltext").style.color="green";
            }
        else{
            document.getElementById("lbltext").innerHTML="invalid email";
            document.getElementById("lbltext").style.visibility="visible";
            document.getElementById("lbltext").style.color="black";
            }

        }

</script>
</head>

<body>
<form onsubmit = "return validate()" action = "thankyou.html" class = "input"><br><br>
    <p style = "text-decoration: underline; color: white;">comment :</p><br>
    <input id= "name" placeholder= "Name" type= "text" style = "height: 25px; width:250px;"/><br><br>
    <input id = "text1" placeholder = "Email" type= "text" style = "height: 25px; width: 250px;"/><p style = "font-size: 25px; color: red; display: inline-block;">*</p><label id= "lbltext" style = "color: black;visibility: hidden"></label><br><br>
    <input id= "title1" placeholder= "title" type= "text" style = "height: 25px; width: 500px;"/><br><br>
    <textarea id= "cmt" placeholder= "Comment" type= "text" style = "height: 250px; width: 500px;"></textarea><br><br>
    <button onClick="validate()" type="button" style = "color: white; font-weight: bold; background-color:  #9933ff; width: 75px; height: 30px;float: right; margin-right: 90px; border:thick; border-color: black;">Submit</button>
    </form>
</body>
</code>```

答:
Since you are using return validate(), The onSubmit is expecting a boolean return value from validate(). So, If you want to submit the form you should return true, If not return false.

NOTE

If you want to access the form data in next page, You should set name property for your input fields.

Since you are using onSubmit, You don't need to put onClick to the button. And the button type should be submit not button.

    function validate()
        {
            var text = document.getElementById("text1").value;
            var regx = /^([a-zA-Z0-9\.-]+)@([a-zA-Z0-9-]+)\.([a-z]{3})$/;
            var uname = document.getElementById("name");
            var title = document.getElementById("title1");
            var comment = document.getElementById("cmt");

        if(regx.test(text))
            {
            document.getElementById("lbltext").innerHTML="you may proceed";
            document.getElementById("lbltext").style.visibility="visible";
            document.getElementById("lbltext").style.color="green";
            return true;
            }
        else{
            document.getElementById("lbltext").innerHTML="invalid email";
            document.getElementById("lbltext").style.visibility="visible";
            document.getElementById("lbltext").style.color="black";
            return false;
            }

        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<form onsubmit = "return validate()" action = "thankyou.html" class = "input"><br><br>
    <p style = "text-decoration: underline; color: white;">comment :</p><br>
    <input id= "name" placeholder= "Name" type= "text" style = "height: 25px; width:250px;"/><br><br>
    <input id = "text1" placeholder = "Email" type= "text" style = "height: 25px; width: 250px;"/><p style = "font-size: 25px; color: red; display: inline-block;">*</p><label id= "lbltext" style = "color: black;visibility: hidden"></label><br><br>
    <input id= "title1" placeholder= "title" type= "text" style = "height: 25px; width: 500px;"/><br><br>
    <textarea id= "cmt" placeholder= "Comment" type= "text" style = "height: 250px; width: 500px;"></textarea><br><br>
    <button type="submit" style = "color: white; font-weight: bold; background-color:  #9933ff; width: 75px; height: 30px;float: right; margin-right: 90px; border:thick; border-color: black;">Submit</button>
    </form>
</body></code>```

Body:
I have created a form where the user will enter some information and the email will have to be validated before the user can proceed to the next page (thankyou.html) however when i input every thing correctly into the form the email gets validated but i cannot get to the next page...i cant figure out what im doing wrong. Any help would be appreciated and thank you in advance.

<form onsubmit = "return validate()" action = "thankyou.html" class = "input">

comment :

    <input id= "name" placeholder= "Name" type= "text" style = "height: 25px; width:250px;"/>

    <input id = "text1" placeholder = "Email" type= "text" style = "height: 25px; width: 250px;"/>
*

    <input id= "title1" placeholder= "title" type= "text" style = "height: 25px; width: 500px;"/>

    <textarea id= "cmt" placeholder= "Comment" type= "text" style = "height: 250px; width: 500px;"></textarea>

    <button onClick="validate()" type="button" style = "color: white; font-weight: bold; background-color:  #9933ff; width: 75px; height: 30px;float: right; margin-right: 90px; border:thick; border-color: black;">Submit</button>
    </form>

Body:
Since you are using return validate(), The onSubmit is expecting a boolean return value from validate(). So, If you want to submit the form you should return true, If not return false.

NOTE

If you want to access the form data in next page, You should set name property for your input fields.

Since you are using onSubmit, You don't need to put onClick to the button. And the button type should be submit not button.

    function validate()
        {
            var text = document.getElementById("text1").value;
            var regx = /^([a-zA-Z0-9\.-]+)@([a-zA-Z0-9-]+)\.([a-z]{3})$/;
            var uname = document.getElementById("name");
            var title = document.getElementById("title1");
            var comment = document.getElementById("cmt");

        if(regx.test(text))
            {
            document.getElementById("lbltext").innerHTML="you may proceed";
            document.getElementById("lbltext").style.visibility="visible";
            document.getElementById("lbltext").style.color="green";
            return true;
            }
        else{
            document.getElementById("lbltext").innerHTML="invalid email";
            document.getElementById("lbltext").style.visibility="visible";
            document.getElementById("lbltext").style.color="black";
            return false;
            }

        }

<body>
<form onsubmit = "return validate()" action = "thankyou.html" class = "input"><br><br>
    <p style = "text-decoration: underline; color: white;">comment :</p><br>
    <input id= "name" placeholder= "Name" type= "text" style = "height: 25px; width:250px;"/><br><br>
    <input id = "text1" placeholder = "Email" type= "text" style = "height: 25px; width: 250px;"/><p style = "font-size: 25px; color: red; display: inline-block;">*</p><label id= "lbltext" style = "color: black;visibility: hidden"></label><br><br>
    <input id= "title1" placeholder= "title" type= "text" style = "height: 25px; width: 500px;"/><br><br>
    <textarea id= "cmt" placeholder= "Comment" type= "text" style = "height: 250px; width: 500px;"></textarea><br><br>
    <button type="submit" style = "color: white; font-weight: bold; background-color:  #9933ff; width: 75px; height: 30px;float: right; margin-right: 90px; border:thick; border-color: black;">Submit</button>
    </form>
</body>


来源: stackexchange

问:
Neo4j: return error if no matching nodes found when creating a relationship?
Apologies if this has already been asked, but I was unable to find the answer

I would like to error when trying to create a relationship between nodes, where one or both of the nodes do not exist

For example, the following code just returns no results, but I would like it to raise an error to let me know that these nodes do not exist, so that I can surface that error to my application:

```<code>MATCH (user1: User{uuid: '123'}), (user2: User{uuid: '456'})
CREATE (user1)-[:LIKES]->(user2)
</code>```

Please assume that the database is empty and therefore no nodes were matched

I tried to add a constraint, but I didn't know how to approach it and if this is possible - are you able to help please?

答:
Instead of an error, your query can just return something (like the new relationship) when it successfully finds both nodes. If the query returns nothing, then that means one or both nodes do not exist.

For example:

```<code>MATCH (user1: User{uuid: '123'}), (user2: User{uuid: '456'})
CREATE (user1)-[r:LIKES]->(user2)
RETURN r;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Apologies if this has already been asked, but I was unable to find the answer

I would like to error when trying to create a relationship between nodes, where one or both of the nodes do not exist

For example, the following code just returns no results, but I would like it to raise an error to let me know that these nodes do not exist, so that I can surface that error to my application:

MATCH (user1: User{uuid: '123'}), (user2: User{uuid: '456'})
CREATE (user1)-[:LIKES]->(user2)

Please assume that the database is empty and therefore no nodes were matched

I tried to add a constraint, but I didn't know how to approach it and if this is possible - are you able to help please?

Body:
Instead of an error, your query can just return something (like the new relationship) when it successfully finds both nodes. If the query returns nothing, then that means one or both nodes do not exist.

For example:

MATCH (user1: User{uuid: '123'}), (user2: User{uuid: '456'})
CREATE (user1)-[r:LIKES]->(user2)
RETURN r;


问:
Is a private member secure in javascript?
I'm following freecodecamp JavaScript oop course. The course describes how you should declare a private variable inside objects for cases like passwords and bank accounts which cannot be changed from outside. the only access to private variables is through public method that has access to the private variable. then it gives this demo code to illustrate the point.

```<code>function Bird() {
  let hatchedEgg = 10; // private variable

  /* publicly available method that a bird object can use */
  this.getHatchedEggCount = function() {
    return hatchedEgg;
  };
}
let ducky = new Bird();
ducky.getHatchedEggCount(); // returns 10
</code>```

What i don't understand is how can the hatchedEgg variable be called as secured.
As a user/hacker all i have to do is to guess the variable name that is being returned from the function getHatchedEggCount() . in this case hatchedEgg (which is not too difficult for a hacker) and then i can use this line to modify the private variable;

```<code>Bird.hatchedEgg = 20;
console.log(Bird) // returns { [Function: Bird] hatchedEgg : 20 }
</code>```

Am i missing something ?

```<code>//-------------- Clarification Edit
</code>```

Apparently the problem was with the freecodecamp console (A Bug) , it was changing the value of a private variable .
if you want you can try pasting the above code in this link and you will see. freecodeConsoleLink

答:
I think you're getting a little confused about the variables that are being created, and how each one is accessed.

You begin with a function:

```<code>function Bird() {
  let hatchedEgg = 10;

  this.getHatchedEggCount = function () {
    return hatchedEgg;
  };
}
</code>```

This function does not have any properties.

When this function is called, it is simply attaching a getHatchedEggCount property to the this object. That getHatchedEggCount property is itself, a function, that references the hatchedEgg variable created when the Bird function runs.

Therefore we can do this:

```<code>// We call the 'Bird' function.
// As we are using the 'new' keyword, we create an empty context for the function.
// The empty context is referenced using the 'this' keyword inside the 'Bird' function.
// We assign 'getHatchedEggCount' as a method on the 'this' empty object
// We then return the 'this' object
// The 'ducky' variable now points to the returned 'this' object
// Therefore the 'ducky' variable is an object with a 'getHatchedEggCount' method
let ducky = new Bird();
</code>```

and console logging gives the following output:

```<code>console.log(ducky);
// Output: Bird { getHatchedEggCount: [Function] }

console.log(ducky.hatchedEgg);
// Output: undefined

console.log(ducky.getHatchedEggCount());
// Output: 10
</code>```

This is all to be expected, because ducky is an object with only a single property - the getHatchedEggCount method.

Most importantly though, notice what happens when we log the following:

```<code>console.log(Bird);
// Output: [Function: Bird]

console.log(Bird.hatchedEgg);
// Output: undefined

console.log(Bird.getHatchedEggCount);
// Output: undefined
</code>```

We see that the Bird function is actually an empty object. It has no properties (that we have assigned ourselves), therefore Bird.hatchedEgg doesn't exist!

So why can we access the hatchedEgg variable when calling ducky.getHatchedEggCount()? This is due to how closures work, but that is off topic. Needless to say, the hatchedEgg variable is ONLY accessible to the getHatchedEggCount function.

Now, if we say:

```<code>    Bird.hatchedEgg = 20;
</code>```

We are adding a brand new property to the Bird function. So we can console log:

```<code>console.log(Bird);
// Output: [Function: Bird] { hatchedEgg: 20 }

console.log(Bird.hatchedEgg);
// Output: 20
</code>```

We have added a new hatchedEgg property to the Bird function that didn't exist before!

Notice however, this is NOT the same property as the hatchedEgg variable that is used by the getHatchedEggCount function.

The original hatchedEgg variable is created inside the Bird function and is accessible inside the function body, but is not a property OF the Bird function object, therefore not accessible by doing Bird.hatchedEgg. Do you see the difference?

For example, run this code:

```<code>function Bird() {
  let hatchedEgg = 10;

  this.getHatchedEggCount = function () {
    return hatchedEgg;
  };
}

Bird.hatchedEgg = 20;
console.log(Bird.hatchedEgg);
// Output: 20

let ducky = new Bird();
console.log(ducky.getHatchedEggCount());
// Output: 10
</code>```

Do you see why the hatchedEgg variable with the value of 10 is still inaccessible? It is not the same variable as Ducky.hatchedEgg.

Body:
I'm following freecodecamp JavaScript oop course. The course describes how you should declare a private variable inside objects for cases like passwords and bank accounts which cannot be changed from outside. the only access to private variables is through public method that has access to the private variable. then it gives this demo code to illustrate the point.

function Bird() {
  let hatchedEgg = 10; // private variable

  /* publicly available method that a bird object can use */
  this.getHatchedEggCount = function() {
    return hatchedEgg;
  };
}
let ducky = new Bird();
ducky.getHatchedEggCount(); // returns 10

What i don't understand is how can the hatchedEgg variable be called as secured.
As a user/hacker all i have to do is to guess the variable name that is being returned from the function getHatchedEggCount() . in this case hatchedEgg (which is not too difficult for a hacker) and then i can use this line to modify the private variable;

Bird.hatchedEgg = 20;
console.log(Bird) // returns { [Function: Bird] hatchedEgg : 20 }

Am i missing something ?

//-------------- Clarification Edit

Apparently the problem was with the freecodecamp console (A Bug) , it was changing the value of a private variable .
if you want you can try pasting the above code in this link and you will see. freecodeConsoleLink

Body:
I think you're getting a little confused about the variables that are being created, and how each one is accessed.

You begin with a function:

function Bird() {
  let hatchedEgg = 10;

  this.getHatchedEggCount = function () {
    return hatchedEgg;
  };
}

This function does not have any properties.

When this function is called, it is simply attaching a getHatchedEggCount property to the this object. That getHatchedEggCount property is itself, a function, that references the hatchedEgg variable created when the Bird function runs.

Therefore we can do this:

// We call the 'Bird' function.
// As we are using the 'new' keyword, we create an empty context for the function.
// The empty context is referenced using the 'this' keyword inside the 'Bird' function.
// We assign 'getHatchedEggCount' as a method on the 'this' empty object
// We then return the 'this' object
// The 'ducky' variable now points to the returned 'this' object
// Therefore the 'ducky' variable is an object with a 'getHatchedEggCount' method
let ducky = new Bird();

and console logging gives the following output:

console.log(ducky);
// Output: Bird { getHatchedEggCount: [Function] }

console.log(ducky.hatchedEgg);
// Output: undefined

console.log(ducky.getHatchedEggCount());
// Output: 10

This is all to be expected, because ducky is an object with only a single property - the getHatchedEggCount method.

Most importantly though, notice what happens when we log the following:

console.log(Bird);
// Output: [Function: Bird]

console.log(Bird.hatchedEgg);
// Output: undefined

console.log(Bird.getHatchedEggCount);
// Output: undefined

We see that the Bird function is actually an empty object. It has no properties (that we have assigned ourselves), therefore Bird.hatchedEgg doesn't exist!

So why can we access the hatchedEgg variable when calling ducky.getHatchedEggCount()? This is due to how closures work, but that is off topic. Needless to say, the hatchedEgg variable is ONLY accessible to the getHatchedEggCount function.

Now, if we say:

    Bird.hatchedEgg = 20;

We are adding a brand new property to the Bird function. So we can console log:

console.log(Bird);
// Output: [Function: Bird] { hatchedEgg: 20 }

console.log(Bird.hatchedEgg);
// Output: 20

We have added a new hatchedEgg property to the Bird function that didn't exist before!

Notice however, this is NOT the same property as the hatchedEgg variable that is used by the getHatchedEggCount function.

The original hatchedEgg variable is created inside the Bird function and is accessible inside the function body, but is not a property OF the Bird function object, therefore not accessible by doing Bird.hatchedEgg. Do you see the difference?

For example, run this code:

function Bird() {
  let hatchedEgg = 10;

  this.getHatchedEggCount = function () {
    return hatchedEgg;
  };
}

Bird.hatchedEgg = 20;
console.log(Bird.hatchedEgg);
// Output: 20

let ducky = new Bird();
console.log(ducky.getHatchedEggCount());
// Output: 10

Do you see why the hatchedEgg variable with the value of 10 is still inaccessible? It is not the same variable as Ducky.hatchedEgg.


问:
what do i need to do to develope an iphone\android app in vs2010?
we are a .net team that devleoped a full app in c# with web services and services that support it. we now want to develope a Mobile app (Android\Iphone) that will look similiar to the original to allow mobile use of it.
we thought about MonoTouch instead of trying to learn Objective-c and to try to develope a cross platform mobile app.
is anyone tried developing a mobile app in vs 2010 in MonoTouch? is there a simple add in for it? is it possible?</p>

答:
Important caveat: both of these tools are in pain - since the vendor fired the dev team (read the "Fighting for Your Right to Party" paragraph). Hopefully soon to be replaced by Xamarin.

MonoDroid does exactly that for android development. For iPhone, you need to be on a mac, and it runs inside MonoDevelop - but ultimately the code is pretty similar.

I would expect any Xamarin tools be have similar architecture.

ContentLicense: CC BY-SA 3.0


问:
RelativeLayout doesn't locate well in ConstraintLayout
I think I did everything true but the RelativeLayout in ConstraintLayout don't do what i command. When i add something under the RelativeLayout it supposed to be smaller and make room to other items but it doesn't matter what i do, it always push them out of the screen.

The left and right arrows should be below of RelativeLayout and adView should be below of arrows.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relativeLayout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:paddingTop="25dp"
    android:paddingBottom="25dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">

    <RelativeLayout
        android:id="@+id/container_main"
        android:paddingBottom="16dp"
        android:background="@drawable/card_bg"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">
        <TextView
            android:textStyle="bold"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/title_text_color"
            android:id="@+id/activity_main_text_view_id"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="40dp"
            android:layout_marginStart="40dp"
            android:layout_marginTop="20dp"
            android:text="simple Title Text"/>

        <TextView
            android:padding="10dp"
            android:gravity="center"
            android:textColor="#000000"
            android:lineSpacingExtra="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/factTextView"
            android:textSize="18dp"
            android:layout_alignStart="@id/activity_main_text_view_id"
            android:layout_alignLeft="@id/activity_main_text_view_id"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:layout_marginTop="8dp"
            android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."/>

        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:id="@+id/activity_main_did_u_know"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            android:text="Category"
            android:layout_marginTop="20dp"/>
        <ImageView
            android:layout_marginLeft="25dp"
            android:id="@+id/activity_main_image_view"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_alignParentBottom="true"
            android:clickable="true"
            android:src="@drawable/ic_share_black_24dp" />

        <ImageView
            android:layout_marginRight="25dp"
            android:id="@+id/activity_main_fav_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:clickable="true"
            android:src="@drawable/ic_favorite_border_black_24dp"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/LeftRight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/container_main"
        app:layout_constraintBottom_toTopOf="@+id/adView"
        >
        <ImageView
            android:layout_marginLeft="25dp"
            android:id="@+id/activity_main_left_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_alignParentBottom="true"
            android:clickable="true"
            app:layout_constraintRight_toLeftOf="@+id/activity_main_right_button"
            android:src="@drawable/ic_left" />

        <ImageView
            android:id="@+id/activity_main_right_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginRight="25dp"
            android:clickable="true"
            android:src="@drawable/ic_right"
            app:layout_constraintLeft_toRightOf="@+id/activity_main_left_button" />

    </RelativeLayout>

    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:layout_constraintTop_toBottomOf="@id/LeftRight"
        ads:layout_constraintRight_toRightOf="parent"
        ads:layout_constraintLeft_toLeftOf="parent"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
    </com.google.android.gms.ads.AdView>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I am open the any kind of advice. Thanks.

答:
I prefer to use whole Constraint Layout in your xml. Checkout below xml, hope the same what you want to design.

```<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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/container_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:background="@drawable/card_bg"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/activity_main_text_view_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:text="simple Title Text"
            android:textColor="@color/title_text_color"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/activity_main_did_u_know"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:text="Category"
            android:textColor="#000000"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/factTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:lineSpacingExtra="8dp"
            android:padding="10dp"
            android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."
            android:textColor="#000000"
            android:textSize="18dp"
            app:layout_constraintBottom_toTopOf="@id/activity_main_image_view"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/activity_main_did_u_know" />

        <ImageView
            android:id="@+id/activity_main_image_view"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/ic_share_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/factTextView" />

        <ImageView
            android:id="@+id/activity_main_fav_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/ic_favorite_border_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@id/factTextView" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/LeftRight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@id/adView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/container_main">

        <ImageView
            android:id="@+id/activity_main_left_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="25dp"
            android:clickable="true"
            android:src="@drawable/ic_left"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/activity_main_right_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="25dp"
            android:clickable="true"
            android:src="@drawable/ic_right"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintLeft_toRightOf="@+id/activity_main_left_button"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:layout_constraintLeft_toLeftOf="parent"
        ads:layout_constraintRight_toRightOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

For more see below view .

Body:
I think I did everything true but the RelativeLayout in ConstraintLayout don't do what i command. When i add something under the RelativeLayout it supposed to be smaller and make room to other items but it doesn't matter what i do, it always push them out of the screen.

The left and right arrows should be below of RelativeLayout and adView should be below of arrows.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relativeLayout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:paddingTop="25dp"
    android:paddingBottom="25dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">

    <RelativeLayout
        android:id="@+id/container_main"
        android:paddingBottom="16dp"
        android:background="@drawable/card_bg"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">
        <TextView
            android:textStyle="bold"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/title_text_color"
            android:id="@+id/activity_main_text_view_id"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="40dp"
            android:layout_marginStart="40dp"
            android:layout_marginTop="20dp"
            android:text="simple Title Text"/>

        <TextView
            android:padding="10dp"
            android:gravity="center"
            android:textColor="#000000"
            android:lineSpacingExtra="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/factTextView"
            android:textSize="18dp"
            android:layout_alignStart="@id/activity_main_text_view_id"
            android:layout_alignLeft="@id/activity_main_text_view_id"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:layout_marginTop="8dp"
            android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."/>

        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:id="@+id/activity_main_did_u_know"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            android:text="Category"
            android:layout_marginTop="20dp"/>
        <ImageView
            android:layout_marginLeft="25dp"
            android:id="@+id/activity_main_image_view"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_alignParentBottom="true"
            android:clickable="true"
            android:src="@drawable/ic_share_black_24dp" />

        <ImageView
            android:layout_marginRight="25dp"
            android:id="@+id/activity_main_fav_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:clickable="true"
            android:src="@drawable/ic_favorite_border_black_24dp"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/LeftRight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/container_main"
        app:layout_constraintBottom_toTopOf="@+id/adView"
        >
        <ImageView
            android:layout_marginLeft="25dp"
            android:id="@+id/activity_main_left_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_alignParentBottom="true"
            android:clickable="true"
            app:layout_constraintRight_toLeftOf="@+id/activity_main_right_button"
            android:src="@drawable/ic_left" />

        <ImageView
            android:id="@+id/activity_main_right_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginRight="25dp"
            android:clickable="true"
            android:src="@drawable/ic_right"
            app:layout_constraintLeft_toRightOf="@+id/activity_main_left_button" />

    </RelativeLayout>

    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:layout_constraintTop_toBottomOf="@id/LeftRight"
        ads:layout_constraintRight_toRightOf="parent"
        ads:layout_constraintLeft_toLeftOf="parent"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
    </com.google.android.gms.ads.AdView>
</androidx.constraintlayout.widget.ConstraintLayout>

I am open the any kind of advice. Thanks.

Body:
I prefer to use whole Constraint Layout in your xml. Checkout below xml, hope the same what you want to design.

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/container_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:background="@drawable/card_bg"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/activity_main_text_view_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:text="simple Title Text"
            android:textColor="@color/title_text_color"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/activity_main_did_u_know"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:text="Category"
            android:textColor="#000000"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/factTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:lineSpacingExtra="8dp"
            android:padding="10dp"
            android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."
            android:textColor="#000000"
            android:textSize="18dp"
            app:layout_constraintBottom_toTopOf="@id/activity_main_image_view"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/activity_main_did_u_know" />

        <ImageView
            android:id="@+id/activity_main_image_view"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/ic_share_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/factTextView" />

        <ImageView
            android:id="@+id/activity_main_fav_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/ic_favorite_border_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@id/factTextView" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/LeftRight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@id/adView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/container_main">

        <ImageView
            android:id="@+id/activity_main_left_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="25dp"
            android:clickable="true"
            android:src="@drawable/ic_left"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/activity_main_right_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="25dp"
            android:clickable="true"
            android:src="@drawable/ic_right"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintLeft_toRightOf="@+id/activity_main_left_button"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:layout_constraintLeft_toLeftOf="parent"
        ads:layout_constraintRight_toRightOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

For more see below view .


问:
redirect page after axios success login - reactJS
I am trying to create a login page with react. I submit the form and send data to the server (PHP/Symfony) where I run login logic and return JSON object with success or error data.
Then if user data is right and login is ok, I need to redirect him to another page. I am using react state.

LoginComponent.js

```<code>import React, { Component } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory';
import {Link} from 'react-router-dom';
const browserHistory = createBrowserHistory();

class LoginComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      errors: {},
      login:'',
      password:'',
      fireRedirect: false
    };

    this.processForm = this.processForm.bind(this);
  }

  processForm(event) {
    event.preventDefault();

    const login = this.state.login;
    const password = this.state.password;
    //TODO validation

    const formData = { login:login, password:password };

    axios.post('http://myweburl.org/app/web/login', formData, { headers: {'Accept': 'application/json'} })
      .then((response) => {

        if(response.data.success) {
          this.setState({ fireRedirect: true })
        }else if(response.data.error){
            this.setState({
            errors:response.data.error
          });
        }
      });
  }

  handleLoginChange(e) {
    this.setState({login: e.target.value});
  }

  handlePasswordChange(e) {
    this.setState({password: e.target.value});
  }

  render() {
    //const { fireRedirect } = this.state;
    if(this.state.fireRedirect) {
        return <Redirect to={'/obligation'}/>
    }

    return (
      <div className="wrapper">
        <div className="full-content">
            <div className="login-page">
              <div className="egz-logo"><img src={`/img/logo.png`} alt="MyEGZ" title="MyEGZ"/></div>
              <form autoComplete="off" onSubmit={this.processForm}>
                <div className="login-block">
                  <input type="text" name="login" value={this.state.login} onChange={this.handleLoginChange.bind(this)} placeholder="login" id="client-login"/>
                </div>
                <div className="login-block">
                  <input type="password" autoComplete="off" name="password" value={this.state.password} onChange={this.handlePasswordChange.bind(this)} placeholder="mot de passe" id="client-pwd"/>
                </div>
                <div className="login-block">
                  <input type="checkbox" name="remember-me" id="client-remember-me"/>
                  <label>Se souvenire de moi</label>
                </div>
                <div className="login-button-block">
                  <input type="submit" name="login-submit" id="login-submit" value="Connexion"/>
                  <div >
                    <Link key="forgot-pwd" to={`/login/forgetpassword`}>
                      mot de passe oubile
                    </Link>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    );
  }
}

export default LoginComponent;
</code>```

App.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import './index.css';
import { Router,Route } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory';
import Obligation from './components/obligation/ObligationComponent';
import Contacts from './components/contacts/ContactComponent';
import ContactPage from './components/contacts/ContactPage';
import LoginPage from './components/LoginComponent';
const browserHistory = createBrowserHistory();

function auth() {

  axios.post('http://myweburl.org/app/web/checkLogin', { headers: {'Accept': 'application/json'} })
    .then((response) => {
      console.log(response);
      if(response.data.success){
        return true;
      }else if(response.data.error){
        return false;
      }
    });

};

const isAuthorized = auth();

ReactDOM.render(
    <Router history={browserHistory}>
      <div>
        <Route exact path="/" component={() => <LoginPage isAuthorized={isAuthorized} />} />
        <Route path="/obligation" component={() => <Obligation title="Obligations légales" isAuthorized={isAuthorized} style="home-header"/> }/>
        <Route path='/contacts' component={() => <Contacts title="Contacts" isAuthorized={isAuthorized} style="contact-header" />} />
        <Route path="/contact/:id" component={() => <ContactPage isAuthorized={isAuthorized} />}/>
      </div>
    </Router>,
  document.getElementById("root")
);
</code>```

When I submit form with right data, it returns success with correct data
{"success":1,"data":{"clients_id":"2"}}
and the print response data in loginComponent ajax success it also returns me this -

console.log(response.data.success,this.state.fireRedirect);

1 true

But redirect is not working. What am I doing wrong?

答:
This is how i usually do my api calls.</p>

```<code>axios
                .post("/yourApiEnd", {
                    accounts: this.accounts
                })
                .then(function(response) {
                    const status = response.status;
                    //redirect logic
                    if (response.status == 200) {
                            window.location = "/script"
                    }
                })
                .catch(e => {
    console.error(e);
  });
        }
</code>```

Body:
I am trying to create a login page with react. I submit the form and send data to the server (PHP/Symfony) where I run login logic and return JSON object with success or error data.
Then if user data is right and login is ok, I need to redirect him to another page. I am using react state.

LoginComponent.js

import React, { Component } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory';
import {Link} from 'react-router-dom';
const browserHistory = createBrowserHistory();

class LoginComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      errors: {},
      login:'',
      password:'',
      fireRedirect: false
    };

    this.processForm = this.processForm.bind(this);
  }

  processForm(event) {
    event.preventDefault();

    const login = this.state.login;
    const password = this.state.password;
    //TODO validation

    const formData = { login:login, password:password };

    axios.post('http://myweburl.org/app/web/login', formData, { headers: {'Accept': 'application/json'} })
      .then((response) => {

        if(response.data.success) {
          this.setState({ fireRedirect: true })
        }else if(response.data.error){
            this.setState({
            errors:response.data.error
          });
        }
      });
  }

  handleLoginChange(e) {
    this.setState({login: e.target.value});
  }

  handlePasswordChange(e) {
    this.setState({password: e.target.value});
  }

  render() {
    //const { fireRedirect } = this.state;
    if(this.state.fireRedirect) {
        return <Redirect to={'/obligation'}/>
    }

    return (

<img src={`/img/logo.png`} alt="MyEGZ" title="MyEGZ"/>

              <form autoComplete="off" onSubmit={this.processForm}>

                  <input type="text" name="login" value={this.state.login} onChange={this.handleLoginChange.bind(this)} placeholder="login" id="client-login"/>

                  <input type="password" autoComplete="off" name="password" value={this.state.password} onChange={this.handlePasswordChange.bind(this)} placeholder="mot de passe" id="client-pwd"/>

                  <input type="checkbox" name="remember-me" id="client-remember-me"/>
                  Se souvenire de moi

                  <input type="submit" name="login-submit" id="login-submit" value="Connexion"/>

                    <Link key="forgot-pwd" to={`/login/forgetpassword`}>
                      mot de passe oubile
                    </Link>

              </form>

    );
  }
}

export default LoginComponent;

App.js

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import './index.css';
import { Router,Route } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory';
import Obligation from './components/obligation/ObligationComponent';
import Contacts from './components/contacts/ContactComponent';
import ContactPage from './components/contacts/ContactPage';
import LoginPage from './components/LoginComponent';
const browserHistory = createBrowserHistory();

function auth() {

  axios.post('http://myweburl.org/app/web/checkLogin', { headers: {'Accept': 'application/json'} })
    .then((response) => {
      console.log(response);
      if(response.data.success){
        return true;
      }else if(response.data.error){
        return false;
      }
    });

};

const isAuthorized = auth();

ReactDOM.render(
    <Router history={browserHistory}>

        <Route exact path="/" component={() => <LoginPage isAuthorized={isAuthorized} />} />
        <Route path="/obligation" component={() => <Obligation title="Obligations légales" isAuthorized={isAuthorized} style="home-header"/> }/>
        <Route path='/contacts' component={() => <Contacts title="Contacts" isAuthorized={isAuthorized} style="contact-header" />} />
        <Route path="/contact/:id" component={() => <ContactPage isAuthorized={isAuthorized} />}/>

    </Router>,
  document.getElementById("root")
);

When I submit form with right data, it returns success with correct data
{"success":1,"data":{"clients_id":"2"}}
and the print response data in loginComponent ajax success it also returns me this -

console.log(response.data.success,this.state.fireRedirect);

1 true

But redirect is not working. What am I doing wrong?

Body:
This is how i usually do my api calls.

axios
                .post("/yourApiEnd", {
                    accounts: this.accounts
                })
                .then(function(response) {
                    const status = response.status;
                    //redirect logic
                    if (response.status == 200) {
                            window.location = "/script"
                    }
                })
                .catch(e => {
    console.error(e);
  });
        }


答:
You can't use year inside UDF, as it is pyspark function.

If you really need to use UDF, you can do it with usual python datetime functions:

```<code>from datetime import datetime

def extractYear(datestring):
   dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')
   return dt.year

time_udf = udf(lambda x: extractYear(x), IntegerType())
</code>```

But using year, like in .withColumn('Year',year(new_df.time)) would be just easier and quicker, so if it works - better stick to it.

Title: Aws Glue pypark UDF is throwing error An error occurred while calling o104.showString. Traceback (most recent call last)

Body:
I need to get an expected dataframe in aws glue using pyspark showing at the end

    #################Initial Dataframe#################
    +---+--------------------+-------------------+
    |_c0|                 _c1|               time|
    +---+--------------------+-------------------+
    |  1|                null|2020-05-30 19:36:32|
    |  2|Mobii5              |2020-05-30 19:36:32|
    |  3|Nooft biHi ooFrame 2|2020-05-30 19:36:32|
    |  4|Samsung mobile   ...|2020-05-30 19:36:32|
    |  5|Samsung ppjomes  ...|2020-05-30 19:36:32|
    |  6| samsung GTP G Tv ne|2020-05-30 19:36:32|
    |  7| all mightyPanasoci |2020-05-30 19:36:32|
    |  8|Samsung hola       .|2020-05-30 19:36:32|
    |  9|Mooron phoines Mondo|2020-05-30 19:36:32|
    | 10|Samsung Guru .......|2020-05-30 19:36:32|
    +---+--------------------+-------------------+

Below is my code

    time_udf = udf(lambda x: year(x), IntegerType())

    timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
                new_df = df.withColumn('time',unix_timestamp(lit(timestamp),'yyyy-MM-dd HH:mm:ss').cast("timestamp"))
                print(new_df.show(10))
                time.sleep(30)
    df1 = new_df.withColumn('Year',time_udf(col("time")))
    df1.createOrReplaceTempView("people")
                sqlDF = spark.sql("SELECT * FROM people")
                sqlDF.show()
                print(df1.printSchema())
                return(df1)

Need to get an output like shown above using aws UDF pyspark

    ###############Expected###################
    +---+--------------------+-------------------+----+
    |_c0|                 _c1|               time|Year|
    +---+--------------------+-------------------+----+
    |  1|                null|2020-05-29 20:07:58|2020|
    |  2|Mobiistar Prime 5...|2020-05-29 20:07:58|2020|
    |  3|NTT Hikari i-Frame 2|2020-05-29 20:07:58|2020|
    |  4|Samsung SM-P605K ...|2020-05-29 20:07:58|2020|
    |  5|Samsung SM-G850W ...|2020-05-29 20:07:58|2020|
    |  6|samsung GTP G Tv ne |2020-05-29 20:07:58|2020|
    |  7|all mightyPanasoci  |2020-05-29 20:07:58|2020|
    |  8|Samsung hola       .|2020-05-29 20:07:58|2020|
    |  9|Mooron phoines Mondo|2020-05-29 20:07:58|2020|
    | 10|Samsung Guru .......|2020-05-29 20:07:58|2020|
    +---+--------------------+-------------------+----+

I can get it right using this below line

    df1 = new_df.withColumn('Year',year(new_df.time))

But i need to use UDF as requirments

Body:
You can't use year inside UDF, as it is pyspark function.

If you really need to use UDF, you can do it with usual python datetime functions:

from datetime import datetime

def extractYear(datestring):
   dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')
   return dt.year

time_udf = udf(lambda x: extractYear(x), IntegerType())

But using year, like in .withColumn('Year',year(new_df.time)) would be just easier and quicker, so if it works - better stick to it.


问:
How to protect a button in disabled mode?
I want to disable a button if user doesnt have rights to access it. I am
                            disabling at Page_Load event

```<code> Page_Load() {
      if(!userhasrights) {
           btn.Enabled=false;
      }
 }
</code>```

but after rendering asp.net just sets its disabled property to disabled which
                        a hacker can easily set to 'true' & can access the button. How can i
                        protect my button in disabled mode?

答:
Instead of using button's Enable property you should use Visible property to make it secure, because if a control's Visible property is false in that case it will not rendered. So there is no question of hacking.

```<code>Page_Load() {
      if(!userhasrights) {
           btn.Visible=false;
      }
 }
</code>```

Body:
I want to disable a button if user doesnt have rights to access it. I am
                            disabling at Page_Load event

 Page_Load() {
      if(!userhasrights) {
           btn.Enabled=false;
      }
 }

but after rendering asp.net just sets its disabled property to disabled which
                        a hacker can easily set to 'true' & can access the button. How can i
                        protect my button in disabled mode?

Body:
Instead of using button's Enable property you should use Visible property to make it secure, because if a control's Visible property is false in that case it will not rendered. So there is no question of hacking.

Page_Load() {
      if(!userhasrights) {
           btn.Visible=false;
      }
 }


问:
Add active class after page loading
I am trying to add an active class after page load. Here is my script. This script is working when I click. But when the page is loaded, the active class disappear.

```<code><ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">

          <li class="nav-item">
            <a class="nav-link" href="{{url('/account')}}" target="_blank">
              <i class="fas fa-fw fa-tachometer-alt"> account</i>
          </li>
    </ul>

       $(document).ready(function(){
           $(".nav-item a").on("click", function(){  $(".nav-item").find(".active").removeClass("active");  $(this).parent().addClass("active");});
        });
</code>```

I am trying to work with localStorage function not succeed .please suggest me what I have to do.

答:
You can clean up your code in many ways:

use toggleClass instead of add/remove class

use .nav-link rather than .nav-item a for one, a will be any anchor element, not just the first child (you'd do better to do .nav-item > a), but that has a distinctive class (.nav-link) so use that

to assign a class on load, just do it and don't put it in the click event

$(document).ready(function() {
  $('.nav-item').addClass('active'); // <-- how to add the class on page load
  $(".nav-link").on("click", function() {
    $(this).parent().toggleClass('active');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active .nav-link::after {
  content: " <==";
  color: red;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

         account

```

Title: Add active class after page loading

Body:
I am trying to add an active class after page load. Here is my script. This script is working when I click. But when the page is loaded, the active class disappear.

               account

       $(document).ready(function(){
           $(".nav-item a").on("click", function(){  $(".nav-item").find(".active").removeClass("active");  $(this).parent().addClass("active");});
        });

I am trying to work with localStorage function not succeed .please suggest me what I have to do.

Body:
You can clean up your code in many ways:

use toggleClass instead of add/remove class

use .nav-link rather than .nav-item a for one, a will be any anchor element, not just the first child (you'd do better to do .nav-item > a), but that has a distinctive class (.nav-link) so use that

to assign a class on load, just do it and don't put it in the click event

$(document).ready(function() {
  $('.nav-item').addClass('active'); // <-- how to add the class on page load
  $(".nav-link").on("click", function() {
    $(this).parent().toggleClass('active');
  });
});

.active .nav-link::after {
  content: " <==";
  color: red;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

<div class="container">
  <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
    <li class="nav-item">
      <a class="nav-link" href="{{url('/account')}}" target="_blank">
        <i class="fas fa-fw fa-tachometer-alt"> account</i>
      </a>
    </li>
  </ul>
</div>


问:
How to add webview in react-native
i am working with the new react native version 0.62 , unfortunately webview is not there anymore , can any one please tell me how to get the webview on the latest react native built.

thanks in advance .
najath

答:
React native web view is removed from a core and moved to a separate package, you will have to install the package to use webview now.
You can install by

```<code>npm i react-native-webview

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';

// ...
class MyWebComponent extends Component {
  render() {
    return <WebView source={{ uri: 'https://reactnative.dev/' }} />;
  }
}
</code>```

You can read the docs using the below url
https://github.com/react-native-community/react-native-webview

Title: How to add webview in react-native

Body:
React native web view is removed from a core and moved to a separate package, you will have to install the package to use webview now.
You can install by

npm i react-native-webview

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';

// ...
class MyWebComponent extends Component {
  render() {
    return <WebView source={{ uri: 'https://reactnative.dev/' }} />;
  }
}

You can read the docs using the below url
https://github.com/react-native-community/react-native-webview


问:
Slow Reading from CDROM
I hope this isn't too off-topic, but found an interesting problem. I have an old CD that I want to back up. If a copy from fresh (putting the CD for the first tame) using the System Drag 'n' Drop, cp or rsync it just hangs.

The files are video files. I can play the video files in VLC. If I watch the whole video, I can copy the video file to my hard drive instantly. I assume VLC has loaded the data into hard drive.

I wrote a simple cp program in Rust. It opens to files, and via buffer of a fixed size, reads one file into that buffer and then writes the buffer to the other (basically uses std::fs::copy, one file to another).

I have tried adjusting the buffer size (as, as far as I can see, it is the only thing I can change) to get the data copying at a reasonable pace. The best ones I have so far found are 1 KiB and 96 KiB buffers. But the copy is excruciatingly slow. Nothing like watching the video in real-time.

My questions are:

why is this happening?

what does vlc do that the OS isn't doing?

答:
Most video players (I don't know about VLC specifically) have some "error tolerance"; primarily because they're designed to cope with unreliable sources (e.g. "free to air TV" with radio interference, streaming over internet with packet losses, etc). Mostly; if part of the data is corrupt or unavailable it will just cause "glitches" in playback, like a small area of one frame that is the wrong color (or a whole frame being skipped) for video and/or a brief period of silence in audio, and these glitches can be very difficult to notice.

It would be "very normal" for a video player (designed with "error tolerance") to handle read errors from CD by simply skipping the corrupted/unavailable data and letting the error tolerance (that had to exist anyway) deal with it.

For copying raw file data, there is no error tolerance - every bit of every byte is (supposed to be) an exact copy of the original and pieces of the data can't be skipped/ignored.

Title: Slow Reading from CDROM


问:
react js, how to sequentially / synchronously update states that depend on each other?
I have a state, lets call it B, that I always reset when I change state A.

But: now I want to reset it, and then set it again. how to do that with react js?

Example is here:
https://codepen.io/jossnaz/pen/bGVXxev

the goal is to have "B is 1" in the output

You cannot just remove setB(0) from the useEffect of A

why does this not work? how to make it work, the right way?

Javascript:

```<code>const { useState, useEffect } = React

const App = () => {
  const [A, setA] = useState(0);
  const [B, setB] = useState(0);
  const [msgB, setMsgB] = useState('');

  useEffect(()=>{
      setB(0);
  }, [A]);
  useEffect(()=>{
      setMsgB('B is: ' + B);
  }, [B]);
  const onClick = () =>{
    setA(A ? 0 : 1); //basically a toggle
    setB(1);
  };
  return(
    <div className="box">
      <button onClick={onClick}>click me to test </button>

      <div><strong>A:</strong> {A}</div>
      <div><strong>B:</strong> {B}</div>
      <div>debug:</div>
      <div>{msgB}</div>
    </div>
  );
}

ReactDOM.render(<App />,
document.getElementById("root"))
</code>```

again, what do I want?

I want to call

```<code>    setA(A ? 0 : 1); //basically a toggle
    setB(1); // <--------- make this work!
</code>```

and have B on value 1. now its always 0.

EDIT

the initial thought was as well, that those 2 states depend on each other in a non trivial way.

E.g. And imagine that setB(1) depends on A. Just imagine: maybe setB(A == 1 ? 'one' : 'zero'); which is a trivial example, but imagine a none-trivial example

答:
You can use a setTimeout with a delay of 0 to update B separately from the onClick handler. This will enqueue that update into a different render cycle as the event queue is processed. All the state updates from the current render cycle will be processed before the update queued in the timeout callback placed at the end of the event queue.

Basically it is because react state updates are asynchronous, but processed in the order in which they are queued up, combined with the fact that a function needs to complete before the effects can be processed. In your code you queue up an "update(A, B1)", but when A is updated it queues an "update(B2)" and overwrites B1. When you use the setTimeout it places the "update(B1)" at the end of the event queue, which will be processed after all effects from the render phase are committed.

```<code>const App = () => {
  const [A, setA] = useState(0);
  const [B, setB] = useState(0);
  const [msgB, setMsgB] = useState("");

  useEffect(() => {
    setB(0);
  }, [A]);

  useEffect(() => {
    setMsgB("B is: " + B);
  }, [B]);

  const onClick = () => {
    setA(A ? 0 : 1); //basically a toggle
    // setB(1) // <-- This update is overwritten by the setB(0) from effect A
    setTimeout(setB, 0, 1); // <-- This delays a setB(1) after all effects processed
  };

  return (
    <div className="box">
      <button onClick={onClick}>click me to test </button>

      <div>
        <strong>A:</strong> {A}
      </div>
      <div>
        <strong>B:</strong> {B}
      </div>
      <div>debug:</div>
      <div>{msgB}</div>
    </div>
  );
};
</code>```

You can play with the delay (the second value to setTimeout) to something like 500 or 1000 and you'll see the rendered B value "blip" 1 then set back to 0, then finally set to 1.

EDIT: Moving reducer solution here for conversational clarity

Hooks run once per render cycle. The effect is update A -> reset B. If
  you then also want another effect, update B -> reset C, it has to wait
  until the next render cycle to pick up the change in B in order to
  trigger the effect. Each effect like this delays the actual change by
  1 render cycle. This is ok until you try to not reset state by queuing
  a set B in the same cycle and expect all the later triggered effects
  to not work as designed.

```<code>const initialState = {
  A: 0,
  B: 0,
  C: 0
};

const reducer = (state, action) => {
  switch (action.type) {
    case "SET_A":
      // Reset to { A: value, B: 0, C: 0 }
      return { ...initialState, A: action.value };

    case "SET_B":
      // Keep A, set B, reset C
      return { ...state, B: action.value, C: 0 };

    case "SET_C":
      // Keep A & B, set C
      return { ...state, C: action.value };
    default:
      return state;
  }
};

const App = () => {
  const [{ A, B, C }, dispatch] = useReducer(reducer, initialState);
  const [msgB, setMsgB] = useState("");

  useEffect(() => {
    setMsgB("B is: " + B);
  }, [B]);

  const onClickA = () => {
    dispatch({ type: "SET_A", value: A ? 0 : 1 });
    dispatch({ type: "SET_B", value: 1 });
    dispatch({ type: "SET_C", value: 3 });
  };

  return (
    <div className="box">
      <div>
        <strong>A:</strong> {A}
        <button onClick={onClickA}>Toggle A</button>
      </div>
      <div>
        <strong>B:</strong> {B}
      </div>
      <div>
        <strong>C:</strong> {C}
      </div>
      <div>debug:</div>
      <div>{msgB}</div>
    </div>
  );
};
</code>```

How/why this works

Because of the delay caused by "reacting" to state updates it is very difficult to reconcile asynchronous updates to be synchronous. The timeout works in the short term, but even just adding a third variable to work with really complicates it.

With a reducer, however, we've control of the entire "set" of variables (A, B, C, ... Z?) that need to be reset at the same time. This means we can "collapse" all the state value resets we know/want will happen into a single atomic "action" and make the update all in a single render cycle. The benefit of using a reducer function is it serializes state updates, meaning it processes one action at a time; it runs to completion before the next dispatched action can be processed.

```<code>dispatch({ type: "SET_A", value: A ? 0 : 1 });
// We know here that state will be { A: <0|1>, B: 0, C: 0 }
dispatch({ type: "SET_B", value: 1 });
// We know here that state will be { A: <0|1>, B: 1, C: 0 }
dispatch({ type: "SET_C", value: 3 });
// We know here that state will be { A: <0|1>, B: 1, C: 3 }
</code>```

Body:
I have a state, lets call it B, that I always reset when I change state A.

But: now I want to reset it, and then set it again. how to do that with react js?

Example is here:
https://codepen.io/jossnaz/pen/bGVXxev

the goal is to have "B is 1" in the output

You cannot just remove setB(0) from the useEffect of A

why does this not work? how to make it work, the right way?

Javascript:

const { useState, useEffect } = React

const App = () => {
  const [A, setA] = useState(0);
  const [B, setB] = useState(0);
  const [msgB, setMsgB] = useState('');

  useEffect(()=>{
      setB(0);
  }, [A]);
  useEffect(()=>{
      setMsgB('B is: ' + B);
  }, [B]);
  const onClick = () =>{
    setA(A ? 0 : 1); //basically a toggle
    setB(1);
  };
  return(

      <button onClick={onClick}>click me to test </button>

A: {A}

B: {B}

debug:

{msgB}

  );
}

ReactDOM.render(<App />,
document.getElementById("root"))

again, what do I want?

I want to call

    setA(A ? 0 : 1); //basically a toggle
    setB(1); // <--------- make this work!

and have B on value 1. now its always 0.

EDIT

the initial thought was as well, that those 2 states depend on each other in a non trivial way.

E.g. And imagine that setB(1) depends on A. Just imagine: maybe setB(A == 1 ? 'one' : 'zero'); which is a trivial example, but imagine a none-trivial example

Body:
You can use a setTimeout with a delay of 0 to update B separately from the onClick handler. This will enqueue that update into a different render cycle as the event queue is processed. All the state updates from the current render cycle will be processed before the update queued in the timeout callback placed at the end of the event queue.

Basically it is because react state updates are asynchronous, but processed in the order in which they are queued up, combined with the fact that a function needs to complete before the effects can be processed. In your code you queue up an "update(A, B1)", but when A is updated it queues an "update(B2)" and overwrites B1. When you use the setTimeout it places the "update(B1)" at the end of the event queue, which will be processed after all effects from the render phase are committed.

const App = () => {
  const [A, setA] = useState(0);
  const [B, setB] = useState(0);
  const [msgB, setMsgB] = useState("");

  useEffect(() => {
    setB(0);
  }, [A]);

  useEffect(() => {
    setMsgB("B is: " + B);
  }, [B]);

  const onClick = () => {
    setA(A ? 0 : 1); //basically a toggle
    // setB(1) // <-- This update is overwritten by the setB(0) from effect A
    setTimeout(setB, 0, 1); // <-- This delays a setB(1) after all effects processed
  };

  return (
    <div className="box">
      <button onClick={onClick}>click me to test </button>

      <div>
        <strong>A:</strong> {A}
      </div>
      <div>
        <strong>B:</strong> {B}
      </div>
      <div>debug:</div>
      <div>{msgB}</div>
    </div>
  );
};

You can play with the delay (the second value to setTimeout) to something like 500 or 1000 and you'll see the rendered B value "blip" 1 then set back to 0, then finally set to 1.

EDIT: Moving reducer solution here for conversational clarity

Hooks run once per render cycle. The effect is update A -> reset B. If
  you then also want another effect, update B -> reset C, it has to wait
  until the next render cycle to pick up the change in B in order to
  trigger the effect. Each effect like this delays the actual change by
  1 render cycle. This is ok until you try to not reset state by queuing
  a set B in the same cycle and expect all the later triggered effects
  to not work as designed.

const initialState = {
  A: 0,
  B: 0,
  C: 0
};

const reducer = (state, action) => {
  switch (action.type) {
    case "SET_A":
      // Reset to { A: value, B: 0, C: 0 }
      return { ...initialState, A: action.value };

    case "SET_B":
      // Keep A, set B, reset C
      return { ...state, B: action.value, C: 0 };

    case "SET_C":
      // Keep A & B, set C
      return { ...state, C: action.value };
    default:
      return state;
  }
};

const App = () => {
  const [{ A, B, C }, dispatch] = useReducer(reducer, initialState);
  const [msgB, setMsgB] = useState("");

  useEffect(() => {
    setMsgB("B is: " + B);
  }, [B]);

  const onClickA = () => {
    dispatch({ type: "SET_A", value: A ? 0 : 1 });
    dispatch({ type: "SET_B", value: 1 });
    dispatch({ type: "SET_C", value: 3 });
  };

  return (
    <div className="box">
      <div>
        <strong>A:</strong> {A}
        <button onClick={onClickA}>Toggle A</button>
      </div>
      <div>
        <strong>B:</strong> {B}
      </div>
      <div>
        <strong>C:</strong> {C}
      </div>
      <div>debug:</div>
      <div>{msgB}</div>
    </div>
  );
};

How/why this works

Because of the delay caused by "reacting" to state updates it is very difficult to reconcile asynchronous updates to be synchronous. The timeout works in the short term, but even just adding a third variable to work with really complicates it.

With a reducer, however, we've control of the entire "set" of variables (A, B, C, ... Z?) that need to be reset at the same time. This means we can "collapse" all the state value resets we know/want will happen into a single atomic "action" and make the update all in a single render cycle. The benefit of using a reducer function is it serializes state updates, meaning it processes one action at a time; it runs to completion before the next dispatched action can be processed.

dispatch({ type: "SET_A", value: A ? 0 : 1 });
// We know here that state will be { A: <0|1>, B: 0, C: 0 }
dispatch({ type: "SET_B", value: 1 });
// We know here that state will be { A: <0|1>, B: 1, C: 0 }
dispatch({ type: "SET_C", value: 3 });
// We know here that state will be { A: <0|1>, B: 1, C: 3 }


问:
How to Best Factor Out Common Class Methods
I am building an in-memory instance model in Ruby. There are a bunch of classes that each get instantiated and managed by class methods on that class. There are a bunch of those class methods, e.g. list all instances, retrieve all instances, etc.

The code for these methods is common across all classes and does not need to take any account of any particularities of those classes. Hence, I would like that code to live in a common place. See the list method below. My question: How to best achieve this.

```<code>class A
    attr_reader :value
    @@instances = []

    def initialize(value:)
        @value = value; @@instances << self
    end

    def self.list
        @@instances.each { |i| puts "#{i.value}"}
    end
end

class B
    attr_reader :value
    @@instances = []

    def initialize(value:)
        @value = value; @@instances << self
    end

    def self.list
        @@instances.each { |i| puts "#{i.value}"}
    end
end

A.new(value: '100')
A.new(value: '101')
B.new(value: '200')
B.new(value: '201')

A.list
B.list
</code>```

Ideally, I define the list method only once. I have also tried moving that to a super-class:

```<code>class Entity
    def self.list
        @@instances.each { |i| puts "AB: #{i.value}"}
    end
end

class A < Entity
    attr_reader :value
    @@instances = []

    def initialize(value:)
        @value = value; @@instances << self
    end
end

class B < Entity
    attr_reader :value
    @@instances = []

    def initialize(value:)
        @value = value; @@instances << self
    end
end
</code>```

...but as one would expect the super-class cannot access the @@instances array of its sub-classes. Moving the @@instances array to the super-class results in the array being common to all classes, which is not what I need.

答:
The main change you need to make is to use class instance variables rather than class variables. For reasons explained here class variables should be used sparingly; class instance variables are generally a better choice, as is illustrated nicely by this question.

```<code>class Entity
  attr_reader :value

  class << self
    attr_reader :ins
  end

  def self.inherited(klass)
    klass.instance_variable_set(:@ins, [])
  end

  def initialize(value:)
    @value = value
    self.class.ins << self
  end

  def self.list
    @ins.each { |i| puts "#{i.value}"}
  end
end
</code>```

```<code>class A < Entity; end
class B < Entity; end
</code>```

```<code>A.new(value: '100')
  #=> #<A:0x00005754a59dc640 @value="100">
A.new(value: '101')
  #=> #<A:0x00005754a59e4818 @value="101">
A.list
  # 100
  # 101
</code>```

```<code>B.new(value: '200')
  #=> #<B:0x00005754a59f0910 @value="200">
B.new(value: '201')
  #=> #<B:0x00005754a59f8b88 @value="201">
B.list
  # 200
  # 201
</code>```

I defined a getter for the class instance variable @ins in Entity's singleton class1:

```<code>class << self
  attr_reader :ins
end
</code>```

When subclasses of Entity are created the callback method Class::inherited is executed on Entity, passing as an argument the class that has been created. inherited creates and initializes (to an empty array) the class instance variable @ins for the class created.

Another way of doing that, without using a callback method, is as follows.

```<code>class Entity
  attr_reader :value

  class << self
    attr_accessor :ins
  end

  def initialize(value:)
    @value = value
    (self.class.ins ||= []) << self
  end

  def self.list
    @ins.each { |i| puts "#{i.value}"}
  end
end
</code>```

The fragment:

```<code>(self.class.ins ||= [])
</code>```

sets @ins to an empty array if @ins equals nil. If @ins is referenced before it is created, nil is returned, so either way, @ins is set equal to []. In order to execute this statement I needed to change attr_reader :ins to attr_accessor :ins in order to perform the assignment @ins = [] (though I could have used instance_variable_set instead).

Note that if I were to add the line @ins = [] to Entity (as th first line, say), the instance variable @ins would be created for every subclass when the subclass is created, but that instance variable would not be initialized to an empty array, so that line would serve no purpose.

1. Alternatively, one could write, singleton_class.public_send(:attr_reader, :ins).

Body:
I am building an in-memory instance model in Ruby. There are a bunch of classes that each get instantiated and managed by class methods on that class. There are a bunch of those class methods, e.g. list all instances, retrieve all instances, etc.

The code for these methods is common across all classes and does not need to take any account of any particularities of those classes. Hence, I would like that code to live in a common place. See the list method below. My question: How to best achieve this.

class A
    attr_reader :value
    @@instances = []

    def initialize(value:)
        @value = value; @@instances << self
    end

    def self.list
        @@instances.each { |i| puts "#{i.value}"}
    end
end

class B
    attr_reader :value
    @@instances = []

    def initialize(value:)
        @value = value; @@instances << self
    end

    def self.list
        @@instances.each { |i| puts "#{i.value}"}
    end
end

A.new(value: '100')
A.new(value: '101')
B.new(value: '200')
B.new(value: '201')

A.list
B.list

Ideally, I define the list method only once. I have also tried moving that to a super-class:

class Entity
    def self.list
        @@instances.each { |i| puts "AB: #{i.value}"}
    end
end

class A < Entity
    attr_reader :value
    @@instances = []

    def initialize(value:)
        @value = value; @@instances << self
    end
end

class B < Entity
    attr_reader :value
    @@instances = []

    def initialize(value:)
        @value = value; @@instances << self
    end
end

...but as one would expect the super-class cannot access the @@instances array of its sub-classes. Moving the @@instances array to the super-class results in the array being common to all classes, which is not what I need.

Body:
The main change you need to make is to use class instance variables rather than class variables. For reasons explained here class variables should be used sparingly; class instance variables are generally a better choice, as is illustrated nicely by this question.

class Entity
  attr_reader :value

  class << self
    attr_reader :ins
  end

  def self.inherited(klass)
    klass.instance_variable_set(:@ins, [])
  end

  def initialize(value:)
    @value = value
    self.class.ins << self
  end

  def self.list
    @ins.each { |i| puts "#{i.value}"}
  end
end

class A < Entity; end
class B < Entity; end

A.new(value: '100')
  #=> #<A:0x00005754a59dc640 @value="100">
A.new(value: '101')
  #=> #<A:0x00005754a59e4818 @value="101">
A.list
  # 100
  # 101

B.new(value: '200')
  #=> #<B:0x00005754a59f0910 @value="200">
B.new(value: '201')
  #=> #<B:0x00005754a59f8b88 @value="201">
B.list
  # 200
  # 201

I defined a getter for the class instance variable @ins in Entity's singleton class1:

class << self
  attr_reader :ins
end

When subclasses of Entity are created the callback method Class::inherited is executed on Entity, passing as an argument the class that has been created. inherited creates and initializes (to an empty array) the class instance variable @ins for the class created.

Another way of doing that, without using a callback method, is as follows.

class Entity
  attr_reader :value

  class << self
    attr_accessor :ins
  end

  def initialize(value:)
    @value = value
    (self.class.ins ||= []) << self
  end

  def self.list
    @ins.each { |i| puts "#{i.value}"}
  end
end

The fragment:

(self.class.ins ||= [])

sets @ins to an empty array if @ins equals nil. If @ins is referenced before it is created, nil is returned, so either way, @ins is set equal to []. In order to execute this statement I needed to change attr_reader :ins to attr_accessor :ins in order to perform the assignment @ins = [] (though I could have used instance_variable_set instead).

Note that if I were to add the line @ins = [] to Entity (as th first line, say), the instance variable @ins would be created for every subclass when the subclass is created, but that instance variable would not be initialized to an empty array, so that line would serve no purpose.

1. Alternatively, one could write, singleton_class.public_send(:attr_reader, :ins).


问:
How to Implement Progress Indicator in Flutter
I am trying to implement a Progress Indicator in Flutter but I am not sure whether I need to put in the if condition to show Progress Indicator while the item is still Loading.

```<code>class HomePageNewArrival extends StatefulWidget {
  final List<Product> productList;

  HomePageNewArrival({this.productList});

  @override
  _HomePageNewArrivalState createState() => _HomePageNewArrivalState();
}

class _HomePageNewArrivalState extends State<HomePageNewArrival> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 550,
      child: GridView.builder(
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 2 / 3.2,
            crossAxisSpacing: 1,
            mainAxisSpacing: 1,
          ),
          itemCount: this.widget.productList.length,
          itemBuilder: (context, index) {
            if (index.) {
              return HomenewArrivalProducts(this.widget.productList[index]);
            } else {
              return new CircularProgressIndicator();
            }
          }),
    );
  }
}
</code>```

答:
Building widgets in flutter is instant
i think what you wanna do is to show a circular spinner while images are loading in HomenewArrivalProducts() Widget if you have a Image.network() try this:

```<code>child: Image.network(
      'https://example.com/image.jpg',
      loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent loadingProgress) {
        if (loadingProgress == null)
          return child;
        return Center(
          child: CircularProgressIndicator(
            value: loadingProgress.expectedTotalBytes != null
                ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes
                : null,
          ),
        );
      },
    ),
</code>```

and if you wanna just to make an illusion of something is loading you can use FutureBuilder()

```<code>FutureBuilder(
      future: Future.delayed(Duration(milliseconds: 500)),
      builder: (ctx, snapshot) =>
          snapshot.connectionState == ConnectionState.waiting
              ? CircularProgressIndicator()
              : GridView.builder(...),
    );
</code>```

Body:
I am trying to implement a Progress Indicator in Flutter but I am not sure whether I need to put in the if condition to show Progress Indicator while the item is still Loading.

class HomePageNewArrival extends StatefulWidget {
  final List<Product> productList;

  HomePageNewArrival({this.productList});

  @override
  _HomePageNewArrivalState createState() => _HomePageNewArrivalState();
}

class _HomePageNewArrivalState extends State<HomePageNewArrival> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 550,
      child: GridView.builder(
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 2 / 3.2,
            crossAxisSpacing: 1,
            mainAxisSpacing: 1,
          ),
          itemCount: this.widget.productList.length,
          itemBuilder: (context, index) {
            if (index.) {
              return HomenewArrivalProducts(this.widget.productList[index]);
            } else {
              return new CircularProgressIndicator();
            }
          }),
    );
  }
}

Body:
Building widgets in flutter is instant
i think what you wanna do is to show a circular spinner while images are loading in HomenewArrivalProducts() Widget if you have a Image.network() try this:

child: Image.network(
      'https://example.com/image.jpg',
      loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent loadingProgress) {
        if (loadingProgress == null)
          return child;
        return Center(
          child: CircularProgressIndicator(
            value: loadingProgress.expectedTotalBytes != null
                ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes
                : null,
          ),
        );
      },
    ),

and if you wanna just to make an illusion of something is loading you can use FutureBuilder()

FutureBuilder(
      future: Future.delayed(Duration(milliseconds: 500)),
      builder: (ctx, snapshot) =>
          snapshot.connectionState == ConnectionState.waiting
              ? CircularProgressIndicator()
              : GridView.builder(...),
    );


问:
Sucess notification animation extra arguments error SwiftUI
I'm getting an error when trying to do the animation:

```<code>SuccessNotificationView()
    .offset(y: self.showSuccessSave ? -UIScreen.main.bounds.height/3 : -UIScreen.main.bounds.height)
    .animation(.interactiveSpring(mass: 1.0, stiffness: 100.0, damping: 10, initialVelocity: 0))
</code>```

where SuccessNotificationView() is:

```<code>struct SuccessNotificationView: View {
    var body: some View {
        Text("Success")
            .padding()
            .foregroundColor(Color.white)
            .frame(width: UIScreen.main.bounds.width, height: 100)
            .background(Color.green)
            .cornerRadius(20)
    }
}
</code>```

The error I'm getting is: Extra arguments at positions #1, #2, #3, #4 in call

How can I fix that?

答:
You need to pass in the the proper parameters to interactiveSpring().

```<code>.animation(
  .interactiveSpring(
    response: Double,
    dampingFraction: Double,
    blendDuration: Double
  )
)
</code>```

There are only two method calls for interactiveSpring(). One is with no parameters and the second is the example shown above.

I believe that you are trying to use interpolatingSpring(). In that case, use the following code snippet:

```<code>.animation(
  .interpolatingSpring(
    mass: 1,
    stiffness: 100.0,
    damping: 10,
    initialVelocity: 0
  )
)
</code>```

Body:
I'm getting an error when trying to do the animation:

SuccessNotificationView()
    .offset(y: self.showSuccessSave ? -UIScreen.main.bounds.height/3 : -UIScreen.main.bounds.height)
    .animation(.interactiveSpring(mass: 1.0, stiffness: 100.0, damping: 10, initialVelocity: 0))

where SuccessNotificationView() is:

struct SuccessNotificationView: View {
    var body: some View {
        Text("Success")
            .padding()
            .foregroundColor(Color.white)
            .frame(width: UIScreen.main.bounds.width, height: 100)
            .background(Color.green)
            .cornerRadius(20)
    }
}

The error I'm getting is: Extra arguments at positions #1, #2, #3, #4 in call

How can I fix that?

Body:
You need to pass in the the proper parameters to interactiveSpring().

.animation(
  .interactiveSpring(
    response: Double,
    dampingFraction: Double,
    blendDuration: Double
  )
)

There are only two method calls for interactiveSpring(). One is with no parameters and the second is the example shown above.

I believe that you are trying to use interpolatingSpring(). In that case, use the following code snippet:

.animation(
  .interpolatingSpring(
    mass: 1,
    stiffness: 100.0,
    damping: 10,
    initialVelocity: 0
  )
)


问:
Problem while retrieving Button tags
my app requirements are as follows:-

1.) Make a Buttton  according to Number of images store in a library.(i have done it).
2.) Disable all buttons when user click on Disable Button.
to full fill the second requirement i set the tag of each button at the time of creation:

```<code>button.setTag=tag;
</code>```

where tag increase on e by one.

problem is that when i disable button it disable only last button.how can i acess button tag value one by one.?

```<code>for (int index = 0; index < [objectButtonArray count];index++) {
    UIButton *button = [objectButtonArray objectAtIndex:index];
    button.hidden = NO;
    imageButton.userInteractionEnabled = NO;
}
</code>```

答:
Try this way....</p>

```<code>for (UIView *view in yourView.subviews) {

                        [view viewWithTag:BUTTON_TAG].userInteractionEnabled = NO;
                    }
</code>```

Title: Problem while retrieving Button tags

Body:
my app requirements are as follows:-

1.) Make a Buttton  according to Number of images store in a library.(i have done it).
2.) Disable all buttons when user click on Disable Button.
to full fill the second requirement i set the tag of each button at the time of creation:

button.setTag=tag;

where tag increase on e by one.

problem is that when i disable button it disable only last button.how can i acess button tag value one by one.?

for (int index = 0; index < [objectButtonArray count];index++) {
    UIButton *button = [objectButtonArray objectAtIndex:index];
    button.hidden = NO;
    imageButton.userInteractionEnabled = NO;
}

Body:
Try this way....

for (UIView *view in yourView.subviews) {

                        [view viewWithTag:BUTTON_TAG].userInteractionEnabled = NO;
                    }


问:
Asp Sql Data Uniq Id String + Integer +1
I want to make an incremental value in my sql table automatically, but I want it to read the previous data and str + int every time.
For example ;
ABC0001
ABC0002
ABC0003
.
.
.
to be continued .

Can you help with this

答:
You can do this in many ways. The first way is automate way which is using computed column specification. You can add an auto-increment column and also create another column that will be computed base on the auto-increment column. For example, you can create the USER table:

```<code>CREATE TABLE [dbo].[UserTable](
  [ID] [int] IDENTITY(1,1) NOT NULL,
  [UserNo]  AS ('ABC'+ RIGHT('0000' + CAST(Id AS VARCHAR(4)), 4)) PERSISTED,
  [FirstName] VARCHAR(50),
  [LastName] VARCHAR(50),
  CONSTRAINT [PK_UserTable] PRIMARY KEY ([ID] ASC)
)
</code>```

Now you can add data to your table:

```<code>INSERT INTO [dbo].[UserTable] ([FirstName],[LastName])
     VALUES ('sample name','sample family name')
</code>```

Body:
You can do this in many ways. The first way is automate way which is using computed column specification. You can add an auto-increment column and also create another column that will be computed base on the auto-increment column. For example, you can create the USER table:

CREATE TABLE [dbo].[UserTable](
  [ID] [int] IDENTITY(1,1) NOT NULL,
  [UserNo]  AS ('ABC'+ RIGHT('0000' + CAST(Id AS VARCHAR(4)), 4)) PERSISTED,
  [FirstName] VARCHAR(50),
  [LastName] VARCHAR(50),
  CONSTRAINT [PK_UserTable] PRIMARY KEY ([ID] ASC)
)

Now you can add data to your table:

INSERT INTO [dbo].[UserTable] ([FirstName],[LastName])
     VALUES ('sample name','sample family name')