问:
Automation of social media account creation by using python3 and pyautogui
Hi everyone i am working on a project to automate the creation of social media account .For this i have an api which provide me phone no and OTP. So basically my first script is fetching phone no and Otp from that api and the second one is clicking buttons and filling forms.
My problem is i am unable to fill the forms because my main function is stuck in a loop because i am not sending any otp to that api. If anybody has any suggestions about how to integrate these two scripts please share your idea with me. I am sharing my both scripts.
Thanks in advance.

This is the code to fetch phone no and otp from api.

```<code>import requests
import json
import time

# This main function takes the value of tzid and call the api inbuild function to print the
# state of operation which has  {response: RESPONSE, service: SERVICE, number: NOMER, msg: ANSWER}

def main(tzid):

    result2 = requests.get("http://api.sms-reg.com/getState.php?tzid=" +tzid+ "&apikey=my_api_key")
    #time.sleep(20)
    xyz = result2.text
    y = json.loads(xyz)
    print(y)

    if(y["response"] != "TZ_NUM_PREPARE"):          #if response is not equal to "TZ_NUM_PREPARE"
        main(tzid)                                  #call the function again and again until we
                                                    #get response == "TZ_NUM_PREPARE"

    elif(y["response"] == "TZ_NUM_PREPARE"):
        print(y["number"])
        time.sleep(5)
        result3 =requests.get("http://api.sms-reg.com/setReady.php?tzid=" +tzid+ "&apikey=my_api_key")

        z = result3.text                            # result3 call api inbuilt setReady method which
        zx = json.loads(z)                          # tell api that the number is ready for operation
        print(z)

        if(zx["response"] == "1"):                  #if we get response 1 for result3 it means number is
            time.sleep(15)                          #now ready for operation

            result4 = requests.get("http://api.sms-reg.com/getState.php?tzid=" +tzid+ "&apikey=my_api_key")
            r_xyx = result4.text
            r_y = json.loads(r_xyx)                 #result4 is similar to result 2 , this process is repeated
                                                    #because we want updated data which contains OTP

            if(r_y["response"] != "TZ_NUM_ANSWER"):  #if the response does not contains OTP call the function
                main(tzid)                           #again and again

            else:
                #print(r_y["answer"])                #print otp
                print(r_y["answer"])

#Driver Code
if __name__ == "__main__":
    # result = requests.get send request to the api to fetch data
    # Basically it provides us two parameters "response" and "tzid"
    result = requests.get('http://api.sms-reg.com/getNum.php?country=ru&service=gmail&apikey=my_api_key')
    id = result.text                    #id fetch the data in text form
    x = json.loads(id)                  #x loads the text into json
    tzid = str(x["tzid"])               #variable tzid fetch the value from json
    #print(tzid)
    print(tzid)
    main(tzid)

</code>```

And thsi is the code where i want my phone no and otp

```<code>import pyautogui
import time
import pandas as pd
import requests
import json
import fetchapidata

df = pd.read_csv("input.csv")

df0 = df ["name1"]
df1 = df ["job"]
df2 = df ["name2"]
df3 = df ["name3"]
df4 = df ["name4"]

for i in range(1):
    #print(df0[i],df1[i])

 pyautogui.click(1308, 170)      #click on the small account logo

 time.sleep(5)

 pyautogui.click(1159, 527)      #clicks on the sign out button

 time.sleep(4)

 pyautogui.click(1270, 169)      #clicks on the sign in button

 time.sleep(4.5)

 pyautogui.click(620, 468)       #clicks on remove account

 time.sleep(2.5)

 pyautogui.click(888, 396)      #clicks on remove logo

 time.sleep(3.5)

 pyautogui.click(802, 528)     #clicks on yes remove

 #pyautogui.click(675, 422)          #add another account
 time.sleep(5)

 pyautogui.click(580, 601)         #create account

 time.sleep(6)

 pyautogui.click(594, 654)         #for myself

 time.sleep(4)

 pyautogui.click(450, 345)         #firstname

 pyautogui.write(df0[i],interval=0.5)

 time.sleep(2)

 pyautogui.click(641, 344)         #lastname

 pyautogui.write(df1[i],interval=0.5)

 time.sleep(1.5)

 pyautogui.click(453, 407)         #userid

 pyautogui.write(df2[i],interval=0.4)

 time.sleep(1.8)

 pyautogui.click(423, 515)        #password

 pyautogui.write(df3[i],interval=0.4)

 time.sleep(1.4)

 pyautogui.click(592, 516)       #cnfrm password

 pyautogui.write(df4[i],interval=0.6)

 time.sleep(0.5)

 pyautogui.click(706, 637)      #done button

 time.sleep(7)

 pyautogui.click(516, 452)                  #click on the phone no field

 time.sleep(3)

x = fetchapidata.callingfun()

pyautogui.write(y, interval=0.2)  #enters phone no

 time.sleep(1)

 pyautogui.click(705, 532)

 time.sleep(5)

 pyautogui.click(449, 480)            #clicks on otp box

 time.sleep(1.5)

 pyautogui.write(r_y, interval=0.2)          #enters otp

 time.sleep(1)

 pyautogui.click(710, 570)           #clicks verify button

 time.sleep(6)

 pyautogui.click(414, 580)           #clicks month section

 time.sleep(1)

 pyautogui.click(415, 359)           #selects the month

 time.sleep(0.5)

 pyautogui.click(533, 585)          #click on day section

 pyautogui.write("1")               #write day

 time.sleep(0.5)

 pyautogui.click(664, 585)          #clicks on year

 time.sleep(0.3)

 pyautogui.write("2000")            #write in year section

 time.sleep(0.2)

 pyautogui.click(423, 669)         #click on gender

 time.sleep(0.2)

 pyautogui.click(401, 735)                  #select gender

 time.sleep(1.5)

 pyautogui.scroll(-100)

 time.sleep(0.5)

 pyautogui.click(697, 638)                 #click on next button

 time.sleep(8)

 pyautogui.click(621, 618)                 #click on skip button

 pyautogui.moveTo(189, 589)

 time.sleep(0.1)

 pyautogui.scroll(-100)

 time.sleep(0.4)

 pyautogui.click(699, 642)                #click on agree button

 time.sleep(10)

</code>```

答: Import your program in another program as module and call your functions in another program. Also break your main function into two parts .Call result 3 and 4 in another function and call both fuctions in another program.</p>

Body:
Hi everyone i am working on a project to automate the creation of social media account .For this i have an api which provide me phone no and OTP. So basically my first script is fetching phone no and Otp from that api and the second one is clicking buttons and filling forms.
My problem is i am unable to fill the forms because my main function is stuck in a loop because i am not sending any otp to that api. If anybody has any suggestions about how to integrate these two scripts please share your idea with me. I am sharing my both scripts.
Thanks in advance.

This is the code to fetch phone no and otp from api.

import requests
import json
import time

# This main function takes the value of tzid and call the api inbuild function to print the
# state of operation which has  {response: RESPONSE, service: SERVICE, number: NOMER, msg: ANSWER}

def main(tzid):

    result2 = requests.get("http://api.sms-reg.com/getState.php?tzid=" +tzid+ "&apikey=my_api_key")
    #time.sleep(20)
    xyz = result2.text
    y = json.loads(xyz)
    print(y)

    if(y["response"] != "TZ_NUM_PREPARE"):          #if response is not equal to "TZ_NUM_PREPARE"
        main(tzid)                                  #call the function again and again until we
                                                    #get response == "TZ_NUM_PREPARE"

    elif(y["response"] == "TZ_NUM_PREPARE"):
        print(y["number"])
        time.sleep(5)
        result3 =requests.get("http://api.sms-reg.com/setReady.php?tzid=" +tzid+ "&apikey=my_api_key")

        z = result3.text                            # result3 call api inbuilt setReady method which
        zx = json.loads(z)                          # tell api that the number is ready for operation
        print(z)

        if(zx["response"] == "1"):                  #if we get response 1 for result3 it means number is
            time.sleep(15)                          #now ready for operation

            result4 = requests.get("http://api.sms-reg.com/getState.php?tzid=" +tzid+ "&apikey=my_api_key")
            r_xyx = result4.text
            r_y = json.loads(r_xyx)                 #result4 is similar to result 2 , this process is repeated
                                                    #because we want updated data which contains OTP

            if(r_y["response"] != "TZ_NUM_ANSWER"):  #if the response does not contains OTP call the function
                main(tzid)                           #again and again

            else:
                #print(r_y["answer"])                #print otp
                print(r_y["answer"])

#Driver Code
if __name__ == "__main__":
    # result = requests.get send request to the api to fetch data
    # Basically it provides us two parameters "response" and "tzid"
    result = requests.get('http://api.sms-reg.com/getNum.php?country=ru&service=gmail&apikey=my_api_key')
    id = result.text                    #id fetch the data in text form
    x = json.loads(id)                  #x loads the text into json
    tzid = str(x["tzid"])               #variable tzid fetch the value from json
    #print(tzid)
    print(tzid)
    main(tzid)

And thsi is the code where i want my phone no and otp

import pyautogui
import time
import pandas as pd
import requests
import json
import fetchapidata

df = pd.read_csv("input.csv")

df0 = df ["name1"]
df1 = df ["job"]
df2 = df ["name2"]
df3 = df ["name3"]
df4 = df ["name4"]

for i in range(1):
    #print(df0[i],df1[i])

 pyautogui.click(1308, 170)      #click on the small account logo

 time.sleep(5)

 pyautogui.click(1159, 527)      #clicks on the sign out button

 time.sleep(4)

 pyautogui.click(1270, 169)      #clicks on the sign in button

 time.sleep(4.5)

 pyautogui.click(620, 468)       #clicks on remove account

 time.sleep(2.5)

 pyautogui.click(888, 396)      #clicks on remove logo

 time.sleep(3.5)

 pyautogui.click(802, 528)     #clicks on yes remove

 #pyautogui.click(675, 422)          #add another account
 time.sleep(5)

 pyautogui.click(580, 601)         #create account

 time.sleep(6)

 pyautogui.click(594, 654)         #for myself

 time.sleep(4)

 pyautogui.click(450, 345)         #firstname

 pyautogui.write(df0[i],interval=0.5)

 time.sleep(2)

 pyautogui.click(641, 344)         #lastname

 pyautogui.write(df1[i],interval=0.5)

 time.sleep(1.5)

 pyautogui.click(453, 407)         #userid

 pyautogui.write(df2[i],interval=0.4)

 time.sleep(1.8)

 pyautogui.click(423, 515)        #password

 pyautogui.write(df3[i],interval=0.4)

 time.sleep(1.4)

 pyautogui.click(592, 516)       #cnfrm password

 pyautogui.write(df4[i],interval=0.6)

 time.sleep(0.5)

 pyautogui.click(706, 637)      #done button

 time.sleep(7)

 pyautogui.click(516, 452)                  #click on the phone no field

 time.sleep(3)

x = fetchapidata.callingfun()

pyautogui.write(y, interval=0.2)  #enters phone no

 time.sleep(1)

 pyautogui.click(705, 532)

 time.sleep(5)

 pyautogui.click(449, 480)            #clicks on otp box

 time.sleep(1.5)

 pyautogui.write(r_y, interval=0.2)          #enters otp

 time.sleep(1)

 pyautogui.click(710, 570)           #clicks verify button

 time.sleep(6)

 pyautogui.click(414, 580)           #clicks month section

 time.sleep(1)

 pyautogui.click(415, 359)           #selects the month

 time.sleep(0.5)

 pyautogui.click(533, 585)          #click on day section

 pyautogui.write("1")               #write day

 time.sleep(0.5)

 pyautogui.click(664, 585)          #clicks on year

 time.sleep(0.3)

 pyautogui.write("2000")            #write in year section

 time.sleep(0.2)

 pyautogui.click(423, 669)         #click on gender

 time.sleep(0.2)

 pyautogui.click(401, 735)                  #select gender

 time.sleep(1.5)

 pyautogui.scroll(-100)

 time.sleep(0.5)

 pyautogui.click(697, 638)                 #click on next button

 time.sleep(8)

 pyautogui.click(621, 618)                 #click on skip button

 pyautogui.moveTo(189, 589)

 time.sleep(0.1)

 pyautogui.scroll(-100)

 time.sleep(0.4)

 pyautogui.click(699, 642)                #click on agree button

 time.sleep(10)


来源: stackexchange

问:
The app that runs on my device is different to the preview
android java

button positioning

the display that runs up on my device is different to the preview. The width and height aren't fixed, and this is in ConstraintLayout. The problem is with the Button; I want it to appear lower than both TextViews. What should i change with my code? (I did try to google it, and look for an answer but couldn't find anything relevant except for the "absoluteX, absoluteY" code for the button)

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

 <Button
   android:id="@+id/button_button_view"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textAllCaps="true"
   android:text="order"
   tools:layout_editor_absoluteY="100dp"
   tools:layout_editor_absoluteX="4dp"/>

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAllCaps="true"
    android:text="quantity"
    android:textSize="16sp"
    app:layout_constraintLeft_toLeftOf="parent"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    app:layout_constraintBottom_toBottomOf="@id/quantity_text_view"
    app:layout_constraintTop_toTopOf="@id/button_button_view"/>
</code>```

答:
The preview looks different because you are using:

```<code>tools:layout_editor_absoluteY="100dp"
tools:layout_editor_absoluteX="4dp"
</code>```

which only affect the preview and have no power on the device.

Try this for putting the button below the TextView

```<code><Button
   android:id="@+id/button_button_view"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   app:layout_constraintTop_toBottomOf="@+id/quantity_text_view"
   app:layout_constraintStart_toStartOf="@+id/quantity_text_view"
   .../>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
android java

button positioning

the display that runs up on my device is different to the preview. The width and height aren't fixed, and this is in ConstraintLayout. The problem is with the Button; I want it to appear lower than both TextViews. What should i change with my code? (I did try to google it, and look for an answer but couldn't find anything relevant except for the "absoluteX, absoluteY" code for the button)

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

 <Button
   android:id="@+id/button_button_view"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textAllCaps="true"
   android:text="order"
   tools:layout_editor_absoluteY="100dp"
   tools:layout_editor_absoluteX="4dp"/>

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAllCaps="true"
    android:text="quantity"
    android:textSize="16sp"
    app:layout_constraintLeft_toLeftOf="parent"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    app:layout_constraintBottom_toBottomOf="@id/quantity_text_view"
    app:layout_constraintTop_toTopOf="@id/button_button_view"/>

Body:
The preview looks different because you are using:

tools:layout_editor_absoluteY="100dp"
tools:layout_editor_absoluteX="4dp"

which only affect the preview and have no power on the device.

Try this for putting the button below the TextView

<Button
   android:id="@+id/button_button_view"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   app:layout_constraintTop_toBottomOf="@+id/quantity_text_view"
   app:layout_constraintStart_toStartOf="@+id/quantity_text_view"
   .../>


问:
C#: How to transform String "[['x','x'],['x','x']]" into an Array without Split()ing?
The string looks like a 2-D array:

```<code>[['a;b;c','d','e'],['a;b;c;d','h','k'], ... ]
</code>```

But how do i evaluate it and transform it into 2D array in C# without using Split()?

答:
When you have a programming problem and you are stuck, break it down into a simpler programming problem.  This answer will show you how to crudely parse using only C# string primitives just one "sub-array" of your string into a list.  That would be good progress and then you can start extending and improving the code.

```<code>var s = "['a;b;c','d','e']";
List<string> list = new List<string>();
int i = 0;
while (i < s.Length)
{
    char c = s[i++];
    if (c == '[')
    {
        while (i < s.Length)
        {
            c = s[i++];
            if (c == '\'')
            {
                int start = i;
                while (i < s.Length && s[i] != '\'')
                    i++;
                list.Add(s.Substring(start, i - start));
                i++;
            }
            if (i < s.Length && s[i] == ',')
                i++;
            if (i < s.Length && s[i] == ']')
            {
                i++;
                break;
            }
        }
    }
}
foreach (var item in list)
    Console.WriteLine(item);
</code>```

This produces as output:

```<code>a;b;c
d
e
</code>```

It's not two-dimensional but I'm not going to write your whole program for you.  It's also puts it into a List instead of an array, but you have to do that anyway because you don't know how big it is.  This is what I mean by breaking the problem down into smaller parts that you can solve.

You can also improve the code by considerable error-checking for missing commas, etc.  But this should get you started.

ContentLicense: CC BY-SA 3.0

Body:
The string looks like a 2-D array:

[['a;b;c','d','e'],['a;b;c;d','h','k'], ... ]

But how do i evaluate it and transform it into 2D array in C# without using Split()?

Body:
When you have a programming problem and you are stuck, break it down into a simpler programming problem.  This answer will show you how to crudely parse using only C# string primitives just one "sub-array" of your string into a list.  That would be good progress and then you can start extending and improving the code.

var s = "['a;b;c','d','e']";
List<string> list = new List<string>();
int i = 0;
while (i < s.Length)
{
    char c = s[i++];
    if (c == '[')
    {
        while (i < s.Length)
        {
            c = s[i++];
            if (c == '\'')
            {
                int start = i;
                while (i < s.Length && s[i] != '\'')
                    i++;
                list.Add(s.Substring(start, i - start));
                i++;
            }
            if (i < s.Length && s[i] == ',')
                i++;
            if (i < s.Length && s[i] == ']')
            {
                i++;
                break;
            }
        }
    }
}
foreach (var item in list)
    Console.WriteLine(item);

This produces as output:

a;b;c
d
e

It's not two-dimensional but I'm not going to write your whole program for you.  It's also puts it into a List instead of an array, but you have to do that anyway because you don't know how big it is.  This is what I mean by breaking the problem down into smaller parts that you can solve.

You can also improve the code by considerable error-checking for missing commas, etc.  But this should get you started.


问:
Hibernate: saving an entity with foreign primary key
I have a database with two entities (Product and Feedback). Feedback has a single foreign key that refers to Product, whose primary key is an integer. They are therefore in a one-to-one relationship.

I want to add a new Feedback entry to the database with my web application.
To do so I'm trying to perform a PUT request to my Spring server from my Angular client application.

The client has an Object of class Feedback with the following attributes (content of Feedback.ts)

```<code>export class Feedback {
  constructor(
    public productId: number,
    public score: number,
    public preferred: boolean,
    public textNote: string
  ) {
  }
}
</code>```

The class Feedback.java, server side:

```<code>@Entity
@Table(name = "feedback")
public class Feedback implements Serializable {
    @Id
    @JoinColumn(name = "product", unique = true)
    @OneToOne(cascade = CascadeType.ALL)
    private Product product;

    @Column(name = "score")
    private double score;

    @Column(name = "preferred")
    private boolean preferred;

    @Column(name = "textnote")
    private String textNote;

    // ... getters, setters, constructor

}
</code>```

As you can see there is a non-matching attribute: productId is a number, while product is of class Product. How can I give the Spring application the correct object in order to save it in the database?

I'm trying to follow the Hibernate guidelines and as far as I understood it would be a bad practice to use an attribute in the java class of type int instead of Product. What should I do?

答:
I had a similar issue as you had, and this blog post helped me solve it: https://www.baeldung.com/spring-data-rest-relationships. This works very well if you are also using the Spring Data REST, but I think you can adapt it to your usage.

Basically, after you create your Feedback entry (with an initial POST request), you should perform another PUT request to associate the Feedback entry to your Product. For your example, you could have something like:

curl -i -X PUT
 -d "http://localhost:8080/feedback/1"
 -H "Content-Type:text/uri-list" http://localhost:8080/product/1/feedbackProduct
```

Body:
I have a database with two entities (Product and Feedback). Feedback has a single foreign key that refers to Product, whose primary key is an integer. They are therefore in a one-to-one relationship.

I want to add a new Feedback entry to the database with my web application.
To do so I'm trying to perform a PUT request to my Spring server from my Angular client application.

The client has an Object of class Feedback with the following attributes (content of Feedback.ts)

export class Feedback {
  constructor(
    public productId: number,
    public score: number,
    public preferred: boolean,
    public textNote: string
  ) {
  }
}

The class Feedback.java, server side:

@Entity
@Table(name = "feedback")
public class Feedback implements Serializable {
    @Id
    @JoinColumn(name = "product", unique = true)
    @OneToOne(cascade = CascadeType.ALL)
    private Product product;

    @Column(name = "score")
    private double score;

    @Column(name = "preferred")
    private boolean preferred;

    @Column(name = "textnote")
    private String textNote;

    // ... getters, setters, constructor

}

As you can see there is a non-matching attribute: productId is a number, while product is of class Product. How can I give the Spring application the correct object in order to save it in the database?

I'm trying to follow the Hibernate guidelines and as far as I understood it would be a bad practice to use an attribute in the java class of type int instead of Product. What should I do?


问:
Does Java support default parameter values?
I came across some Java code that had the following structure:

```<code>public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}

public MyParameterizedFunction(String param1, int param2, boolean param3)
{
    //use all three parameters here
}
</code>```

I know that in C++ I can assign a parameter a default value.  For example:

```<code>void MyParameterizedFunction(String param1, int param2, bool param3=false);
</code>```

Does Java support this kind of syntax?  Are there any reasons why this two step syntax is preferable?

答:
Instead of using:

```<code>void parameterizedMethod(String param1, int param2) {
    this(param1, param2, false);
}

void parameterizedMethod(String param1, int param2, boolean param3) {
    //use all three parameters here
}
</code>```

You could utilize java's Optional functionality by having a single method:

```<code>void parameterizedMethod(String param1, int param2, @Nullable Boolean param3) {
    param3 = Optional.ofNullable(param3).orElse(false);
    //use all three parameters here
}
</code>```

The main difference is that you have to use wrapper classes instead of primitive Java types to allow null input.Boolean instead of boolean, Integer instead of int and so on.

ContentLicense: CC BY-SA 2.5

Body:
I came across some Java code that had the following structure:

public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}

public MyParameterizedFunction(String param1, int param2, boolean param3)
{
    //use all three parameters here
}

I know that in C++ I can assign a parameter a default value.  For example:

void MyParameterizedFunction(String param1, int param2, bool param3=false);

Does Java support this kind of syntax?  Are there any reasons why this two step syntax is preferable?

Body:
Instead of using:

void parameterizedMethod(String param1, int param2) {
    this(param1, param2, false);
}

void parameterizedMethod(String param1, int param2, boolean param3) {
    //use all three parameters here
}

You could utilize java's Optional functionality by having a single method:

void parameterizedMethod(String param1, int param2, @Nullable Boolean param3) {
    param3 = Optional.ofNullable(param3).orElse(false);
    //use all three parameters here
}

The main difference is that you have to use wrapper classes instead of primitive Java types to allow null input.Boolean instead of boolean, Integer instead of int and so on.


问:
NullPointerException : FragmentManager.beginTransaction()
I'm getting this error while trying to launch a Fragment from a first Fragment :

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()' on a null object reference
</code>```

Here's the method where I'm getting the error :

```<code>    @Override
    public void onClick(View v) {
        Fragment fragment = new PropertyFragment();
        if (fragment != null) {
            FragmentManager fragmentManager = fragment.getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            fragmentTransaction.replace(R.id.rent_viewer, fragment);
            fragmentTransaction.addToBackStack(null);

            // Commit the transaction
            fragmentTransaction.commit();
        }
    }
</code>```

Precisely, the following code instruction is causing the error :

```<code>fragmentManager.beginTransaction();
</code>```

Here's how the class and the nested class look like :

```<code>public class RentFragment extends Fragment {

    ...

    @SuppressWarnings("unused")
    private OnRentFragmentInteractionListener mListener;

    public RentFragment() {
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnRentFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnRentFragmentInteractionListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_rent, container, false);

        myOnClickListener = new RentOnClickListener(getActivity());

        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnRentFragmentInteractionListener {
        public void onRentFragmentInteraction(Uri uri);
    }

    private static class RentOnClickListener implements View.OnClickListener {

        private final Context context;

        private RentOnClickListener(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View v) {
            Fragment fragment = new PropertyFragment();
            if (fragment != null) {
                FragmentManager fragmentManager =  fragment.getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack so the user can navigate back
                fragmentTransaction.replace(R.id.rent_viewer, fragment);
                fragmentTransaction.addToBackStack(null);

                // Commit the transaction
                fragmentTransaction.commit();
            }
        }
    }
}
</code>```

答:
Declare your FragmentTransaction and initialize it like this

```<code>FragmentTransaction fm;

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    fm = getFragmentManager();
}
</code>```

Then on your code, you can call this

```<code>Fragment fragment = new PropertyFragment();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.rent_viewer, fragment).addToBackStack(null).commit();;
</code>```

Body:
I'm getting this error while trying to launch a Fragment from a first Fragment :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()' on a null object reference

Here's the method where I'm getting the error :

    @Override
    public void onClick(View v) {
        Fragment fragment = new PropertyFragment();
        if (fragment != null) {
            FragmentManager fragmentManager = fragment.getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            fragmentTransaction.replace(R.id.rent_viewer, fragment);
            fragmentTransaction.addToBackStack(null);

            // Commit the transaction
            fragmentTransaction.commit();
        }
    }

Precisely, the following code instruction is causing the error :

fragmentManager.beginTransaction();

Here's how the class and the nested class look like :

public class RentFragment extends Fragment {

    ...

    @SuppressWarnings("unused")
    private OnRentFragmentInteractionListener mListener;

    public RentFragment() {
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnRentFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnRentFragmentInteractionListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_rent, container, false);

        myOnClickListener = new RentOnClickListener(getActivity());

        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnRentFragmentInteractionListener {
        public void onRentFragmentInteraction(Uri uri);
    }

    private static class RentOnClickListener implements View.OnClickListener {

        private final Context context;

        private RentOnClickListener(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View v) {
            Fragment fragment = new PropertyFragment();
            if (fragment != null) {
                FragmentManager fragmentManager =  fragment.getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack so the user can navigate back
                fragmentTransaction.replace(R.id.rent_viewer, fragment);
                fragmentTransaction.addToBackStack(null);

                // Commit the transaction
                fragmentTransaction.commit();
            }
        }
    }
}

Body:
Declare your FragmentTransaction and initialize it like this

FragmentTransaction fm;

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    fm = getFragmentManager();
}

Then on your code, you can call this

Fragment fragment = new PropertyFragment();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.rent_viewer, fragment).addToBackStack(null).commit();;


问:
Running an executable when the docker-compose exits
I am trying to execute a javascript file using nodejs when the docker container exits. This is what I have got so far and my Dockerfile contents look like the one below. I am not able to catch the SIGINT signal during exit and thus not able to run the int_handler() function. Is there any issue in the script that I provided below ?

I run the command docker-compose up to start the server and then CTRL + C to exit.

```<code>FROM node:10.16.0-slim

ENV NPM_CONFIG_PREFIX=/home/node/.npm-global

ENV PATH=$PATH:/home/node/.npm-global/bin

RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app

RUN mkdir -p /home/node/app/logs && chown -R node:node /home/node/app

WORKDIR /home/node/app

COPY package*.json ./

USER node

RUN npm install

COPY --chown=node:node . .

EXPOSE 8080

EXPOSE 8523

COPY ./docker-script.sh ./docker-script.sh

ENTRYPOINT ["./docker-script.sh"]
</code>```

And the contents of the docker-script.sh file looks like this:

```<code>#!/bin/bash
set -x

pid=0

int_handler() {
  echo "handler"
  node deactivator & pid="$!"
}

# setup handlers
trap 'kill ${!}; int_handler' SIGINT

# run application
node server & pid="$!"

# wait forever
while true
do
  tail -f /dev/null & wait ${!}
done
</code>```

My docker-compose.yml file

```<code>version: '3'
services:
  mongo:
    image: mongo:3.6
  web:
    image: myimage/imagexyz:0.9.1
    restart: always
    ports:
     - "80:8081"
     - "443:8524"
    links:
     - mongo
    depends_on:
     - mongo
</code>```

答:
There's a couple of small details in this that matter.

The most significant is that, when you send Ctrl+C to a foreground docker-compose up, it does the equivalent of docker-compose stop, which in turn is the equivalent of docker stop.  That sends SIGTERM, not SIGINT.  Changing your trap line to catch the right signal will help.

In experimenting with this, once you've sent the Ctrl+C, docker-compose up will stop printing container output.  It does still get generated, and you can still see it with docker-compose logs web though.

This script seems to be running a lot of things in the background that it doesn't need to, and the one other thing that jumps out at me is that your int_handler function starts a background process just as the container is about to exit.  This also has the anti-pattern of running tail -f "to keep the container alive", while your application is running as kind of a side effect.

I've gotten reasonable behavior out of this modification of your script:

#!/bin/sh

int_handler() {
  echo "int_handler"
  # node deactivator

  # forcibly exit the script (and the container)
  exit 0
}

# trap SIGTERM here, not SIGINT
trap int_handler SIGTERM

echo start

# run the CMD from the Dockerfile or the `docker run` command
"$@" &

# wait for that process to exit
# (don't start an artificial `tail -f`)
# (you must `wait` or else the signal is delayed until
# the process exits on its own)
wait $!
```

<p>And a matching trivial <code>Dockerfile</code>:</p>

<pre class="lang-sh prettyprint-override"><code>FROM alpine
COPY script /
ENTRYPOINT ["/script"]
CMD ["sleep", "15"]
</code>```

If the trap function doesn't exit, then anything in the entrypoint script after the final wait will execute.  You could use this if you want to unconditionally clean up.  This variant always prints stop even if you docker stop the container, and exits with the exit status from the script.

#!/bin/sh
trap 'kill $pid' SIGTERM
echo start
"$@" &
pid=$!
wait $pid
rc=$?
echo stop
exit $rc
```

Body:
I am trying to execute a javascript file using nodejs when the docker container exits. This is what I have got so far and my Dockerfile contents look like the one below. I am not able to catch the SIGINT signal during exit and thus not able to run the int_handler() function. Is there any issue in the script that I provided below ?

I run the command docker-compose up to start the server and then CTRL + C to exit.

FROM node:10.16.0-slim

ENV NPM_CONFIG_PREFIX=/home/node/.npm-global

ENV PATH=$PATH:/home/node/.npm-global/bin

RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app

RUN mkdir -p /home/node/app/logs && chown -R node:node /home/node/app

WORKDIR /home/node/app

COPY package*.json ./

USER node

RUN npm install

COPY --chown=node:node . .

EXPOSE 8080

EXPOSE 8523

COPY ./docker-script.sh ./docker-script.sh

ENTRYPOINT ["./docker-script.sh"]

And the contents of the docker-script.sh file looks like this:

#!/bin/bash
set -x

pid=0

int_handler() {
  echo "handler"
  node deactivator & pid="$!"
}

# setup handlers
trap 'kill ${!}; int_handler' SIGINT

# run application
node server & pid="$!"

# wait forever
while true
do
  tail -f /dev/null & wait ${!}
done

My docker-compose.yml file

version: '3'
services:
  mongo:
    image: mongo:3.6
  web:
    image: myimage/imagexyz:0.9.1
    restart: always
    ports:
     - "80:8081"
     - "443:8524"
    links:
     - mongo
    depends_on:
     - mongo

Body:
There's a couple of small details in this that matter.

The most significant is that, when you send Ctrl+C to a foreground docker-compose up, it does the equivalent of docker-compose stop, which in turn is the equivalent of docker stop.  That sends SIGTERM, not SIGINT.  Changing your trap line to catch the right signal will help.

In experimenting with this, once you've sent the Ctrl+C, docker-compose up will stop printing container output.  It does still get generated, and you can still see it with docker-compose logs web though.

This script seems to be running a lot of things in the background that it doesn't need to, and the one other thing that jumps out at me is that your int_handler function starts a background process just as the container is about to exit.  This also has the anti-pattern of running tail -f "to keep the container alive", while your application is running as kind of a side effect.

I've gotten reasonable behavior out of this modification of your script:

#!/bin/sh

int_handler() {
  echo "int_handler"
  # node deactivator

  # forcibly exit the script (and the container)
  exit 0
}

# trap SIGTERM here, not SIGINT
trap int_handler SIGTERM

echo start

# run the CMD from the Dockerfile or the `docker run` command
"$@" &

# wait for that process to exit
# (don't start an artificial `tail -f`)
# (you must `wait` or else the signal is delayed until
# the process exits on its own)
wait $!

And a matching trivial Dockerfile:

FROM alpine
COPY script /
ENTRYPOINT ["/script"]
CMD ["sleep", "15"]

If the trap function doesn't exit, then anything in the entrypoint script after the final wait will execute.  You could use this if you want to unconditionally clean up.  This variant always prints stop even if you docker stop the container, and exits with the exit status from the script.

#!/bin/sh
trap 'kill $pid' SIGTERM
echo start
"$@" &
pid=$!
wait $pid
rc=$?
echo stop
exit $rc


问:
Random System.NotSupportedException on WP7
Sporadically, I receive an error in my WP7 Silverlight application. The error is a random "System.NotSupportedException". This error is thrown occassionally when the following code is executed:

```<code>// 1. Build the url
string serviceURL = "http://www.mydomain.com/service.svc/param1/param2";

// 2. Asynchronously execute the query using HttpWebRequest instead of WebClient. There is a UI performance issue with the WebClient currently
WebRequest request = HttpWebRequest.Create(serviceUrl);
request.BeginGetResponse(new AsyncCallback(MyService_Completed), request);

...

private void MyService_Completed(IAsyncResult result)
{
  // Do stuff
}
</code>```

I have verified that the URL I am sending is correct. Please note, that this request is part of my view model, which may have other network requests fired off at the same time. I have no idea why this happens ocassionally. Can anybody point out any potential reasons?

Thank you!

答: When this happens, make sure you look at the View Detail part of the exception report. It might be that your service is refusing connection or the data passed is invalid. NotSupported is a very general exception that covers many possible situations.

Body:
Sporadically, I receive an error in my WP7 Silverlight application. The error is a random "System.NotSupportedException". This error is thrown occassionally when the following code is executed:

// 1. Build the url
string serviceURL = "http://www.mydomain.com/service.svc/param1/param2";

// 2. Asynchronously execute the query using HttpWebRequest instead of WebClient. There is a UI performance issue with the WebClient currently
WebRequest request = HttpWebRequest.Create(serviceUrl);
request.BeginGetResponse(new AsyncCallback(MyService_Completed), request);

...

private void MyService_Completed(IAsyncResult result)
{
  // Do stuff
}

I have verified that the URL I am sending is correct. Please note, that this request is part of my view model, which may have other network requests fired off at the same time. I have no idea why this happens ocassionally. Can anybody point out any potential reasons?

Thank you!


问:
Async Method Timeout in Nodejs
I am downloading a file and sometimes file size can be big and timeout is not enough. when timeout, I would like to cancel download process because even I get a timeout error, it continues to process the file and give the following exception

_http_outgoing.js:470
      throw new ERR_HTTP_HEADERS_SENT('set');    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
      at ServerResponse.setHeader (_http_outgoing.js:470:11)

here is my async method

```<code>router.get('/api/files/GetFile', urlencodedParser, (req, res) => {

 return new Promise(function (resolve, reject) {
    (async function () {
      try {

        var folderName = "File_" + moment().format('DD-MM-YYYY HH_mm_ss');
        await routerFile.CreatePdfZip(req.query.VoucherCodes, req.query.AppNames, folderName);

        var fullzipPath = './FilesToDownload/' + folderName + '.zip';

        zipFolder('./FilesToDownload/' + folderName, './FilesToDownload/' + folderName + '.zip', function (err) {
          if (err) {
            return reject(err);
          } else {

            console.log('zip created');
            rimraf('./FilesToDownload/' + folderName, function () {
              console.log("folder has been deleted");
            });

            fs.readFile(fullzipPath, (err2, zipData) => {
              if (err2) reject(err2);

              const base64 = zipData.toString('base64');
              res.setHeader('Content-type', 'application/zip');
              res.type('zip');
              res.end(base64, 'binary');
              console.log('EXCELLENT');
            });
          }
        });
      } catch (error) {
        return reject(error);
      }
    })();
    }).catch(error => {
      console.log(error);
      res.send(error);
   });
});
</code>```

The error occurs in the line res.setHeader('Content-type', 'application/zip');

PS: router variable comesfrom const router = express.Router();

and here is the timeout set

```<code>const app = express();
app.use(timeout('2s'));
app.use(bodyParser());
app.use(haltOnTimedout);
app.use(cookieParser());
app.use(haltOnTimedout);

function haltOnTimedout(req, res, next) {
  if (!req.timedout)
    next();
  else {
    console.log('TIMEOUT.----------------------------------------------');
  }
}
</code>```

What am I doing wrong here? Or is there better way to set a timeout and cancel the downloading process

PS: CreatePdfZip method takes time.

答:
To avoid this error, you can check if the response is already sent and sent the response only if not sent (But does not really solve/cancel download processing)

```<code>...
fs.readFile(fullzipPath, (err2, zipData) => {
    if (err2) reject(err2);

    if (!res.headersSent) {
        const base64 = zipData.toString('base64');
        res.setHeader('Content-type', 'application/zip');
        res.type('zip');
        res.end(base64, 'binary');
        console.log('EXCELLENT');
    }
});
...
</code>```

Doc Link

Title: Async Method Timeout in Nodejs

Body:
I am downloading a file and sometimes file size can be big and timeout is not enough. when timeout, I would like to cancel download process because even I get a timeout error, it continues to process the file and give the following exception

_http_outgoing.js:470
      throw new ERR_HTTP_HEADERS_SENT('set');    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
      at ServerResponse.setHeader (_http_outgoing.js:470:11)

here is my async method

router.get('/api/files/GetFile', urlencodedParser, (req, res) => {

 return new Promise(function (resolve, reject) {
    (async function () {
      try {

        var folderName = "File_" + moment().format('DD-MM-YYYY HH_mm_ss');
        await routerFile.CreatePdfZip(req.query.VoucherCodes, req.query.AppNames, folderName);

        var fullzipPath = './FilesToDownload/' + folderName + '.zip';

        zipFolder('./FilesToDownload/' + folderName, './FilesToDownload/' + folderName + '.zip', function (err) {
          if (err) {
            return reject(err);
          } else {

            console.log('zip created');
            rimraf('./FilesToDownload/' + folderName, function () {
              console.log("folder has been deleted");
            });

            fs.readFile(fullzipPath, (err2, zipData) => {
              if (err2) reject(err2);

              const base64 = zipData.toString('base64');
              res.setHeader('Content-type', 'application/zip');
              res.type('zip');
              res.end(base64, 'binary');
              console.log('EXCELLENT');
            });
          }
        });
      } catch (error) {
        return reject(error);
      }
    })();
    }).catch(error => {
      console.log(error);
      res.send(error);
   });
});

The error occurs in the line res.setHeader('Content-type', 'application/zip');

PS: router variable comesfrom const router = express.Router();

and here is the timeout set

const app = express();
app.use(timeout('2s'));
app.use(bodyParser());
app.use(haltOnTimedout);
app.use(cookieParser());
app.use(haltOnTimedout);

function haltOnTimedout(req, res, next) {
  if (!req.timedout)
    next();
  else {
    console.log('TIMEOUT.----------------------------------------------');
  }
}

What am I doing wrong here? Or is there better way to set a timeout and cancel the downloading process

PS: CreatePdfZip method takes time.

Body:
To avoid this error, you can check if the response is already sent and sent the response only if not sent (But does not really solve/cancel download processing)

...
fs.readFile(fullzipPath, (err2, zipData) => {
    if (err2) reject(err2);

    if (!res.headersSent) {
        const base64 = zipData.toString('base64');
        res.setHeader('Content-type', 'application/zip');
        res.type('zip');
        res.end(base64, 'binary');
        console.log('EXCELLENT');
    }
});
...

Doc Link


问:
Flutter: CustomPainter Destination image not dropping on BlendMode.src
I am trying to learn CustomPainter. I have created two rectangles successfully and trying to understand BlendMode.

As the document says when setting paintObj.blendMode = BlendMode.src, it should

Drop the destination image, only paint the source image.`

But here both destination and source painted on top of each other and not clearing destination.

This is full code:

```<code>import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: SizedBox.expand(
          child: CustomPaint(
            painter: MyPainter(),
          ),
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paintObj = Paint();

    paintObj.color = Colors.red;
    canvas.drawRect(
      Rect.fromCircle(
        center: size.center(Offset.zero),
        radius: 40.0,
      ),
      paintObj,
    );

    paintObj.blendMode = BlendMode.src;

    paintObj.color = Colors.green;
    canvas.drawRect(
      Rect.fromCenter(
        center: size.center(Offset.zero),
        height: 160,
        width: 40,
      ),
      paintObj,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
</code>```

Result:
I don't know why the red rectangle(destination) is still drawn

What am I missing here?

答:
```<code>  void paint(Canvas canvas, Size size) {
    final paintObj = Paint();

    canvas.saveLayer(
        Rect.fromCircle(center: Offset(size.width, size.height), radius: 100),
        paintObj);

    paintObj.color = Colors.red;

    canvas.drawRect(
      Rect.fromCircle(
        center: size.center(Offset.zero),
        radius: 40.0,
      ),
      paintObj,
    );

    paintObj.blendMode = BlendMode.src;

    paintObj.color = Colors.green;
    canvas.drawRect(
      Rect.fromCenter(
        center: size.center(Offset.zero),
        height: 160,
        width: 40,
      ),
      paintObj,
    );

    canvas.restore();
  }

</code>```

Body:
I am trying to learn CustomPainter. I have created two rectangles successfully and trying to understand BlendMode.

As the document says when setting paintObj.blendMode = BlendMode.src, it should

Drop the destination image, only paint the source image.`

But here both destination and source painted on top of each other and not clearing destination.

This is full code:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: SizedBox.expand(
          child: CustomPaint(
            painter: MyPainter(),
          ),
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paintObj = Paint();

    paintObj.color = Colors.red;
    canvas.drawRect(
      Rect.fromCircle(
        center: size.center(Offset.zero),
        radius: 40.0,
      ),
      paintObj,
    );

    paintObj.blendMode = BlendMode.src;

    paintObj.color = Colors.green;
    canvas.drawRect(
      Rect.fromCenter(
        center: size.center(Offset.zero),
        height: 160,
        width: 40,
      ),
      paintObj,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

Result:
I don't know why the red rectangle(destination) is still drawn

What am I missing here?


问:
decrease height and row spacing in vuetify form
I am trying to make a form using vuetify which is basically, replicating this form.

I have tried to use vuetify grid and columns after a lot of tries I have got to this

I want to decrease the height of inputs as well as the spacing between rows.

Live code snippet https://codepen.io/ijunaid8088/pen/xxGZzGv

答:
You need to override padding (and/or margin) values on the appropriate elements.

I'd recommend placing a class or id on a common ancestor of all the fields you want to modify (inputs-container class on <v-container>, in the example below), which allows you to only target the inputs inside that element, so you don't change all inputs in your app:

.inputs-container {
  .col-12 {
    padding-top: 0;
    padding-bottom: 0;
  }
  .theme--light.v-input {
    padding-top: 0;
  }
  .v-input__slot {
    margin-bottom: 0;
  }
}
```

See it working.

Body:
You need to override padding (and/or margin) values on the appropriate elements.

I'd recommend placing a class or id on a common ancestor of all the fields you want to modify (inputs-container class on <v-container>, in the example below), which allows you to only target the inputs inside that element, so you don't change all inputs in your app:

.inputs-container {
  .col-12 {
    padding-top: 0;
    padding-bottom: 0;
  }
  .theme--light.v-input {
    padding-top: 0;
  }
  .v-input__slot {
    margin-bottom: 0;
  }
}

See it working.


问:
Nightwatch Cucumber is not finding my step definitions

Current behavior

step definitions are not being recognized … no matter what I try, when I run nightwatch my features and steps come back as undefined.

Expected/desired behavior

The code in my step_definitions folder is executed.

Environment:

nightwatch-cucumber version: 9.1.3

nightwatch version:0.9.21

cucumber version:6.0.5

Selenium_server version:3.141.59

Phantomjs-prebuilt version:2.1.16

Node.js version:10.17.0

Package.json

```<code>    {
      "name": "nightwatchcucumbertest",
      "version": "1.0.0",
      "description": "Test the setup of nightwatch and cucumber",
      "main": "index.js",
      "scripts": {
        "test": "nightwatch"
      },
      "author": "Mark Strohfus",
      "license": "ISC",
      "devDependencies": {
        "cucumber": "^6.0.5",
        "nightwatch": "^0.9.21",
        "nightwatch-cucumber": "^9.1.3",
        "phantomjs-prebuilt": "^2.1.16",
        "selenium-server": "^3.141.59"
      },
      "dependencies": {
        "cucumber": "^6.0.5",
        "phantomjs-prebuilt": "^2.1.16",
        "selenium-server": "^3.141.59"
      }
    }
</code>```

nightwatch.conf.js

```<code>var seleniumServer = require('selenium-server')
var phantomjs = require('phantomjs-prebuilt')
var nightwatchCucumber = require('nightwatch-cucumber')

// Handles the runner, location of feature files and step definitions,
// and closing of nightwatch
var nightwatchCucumberConf = {
    runner: 'nightwatch',
    featureFiles: 'features',
    stepDefinitions: 'step_definitions',
    closeSession: 'afterFeature'
}

module.exports = {
    // Loads nightwatch-cucumber configuration into main nightwatch.js conf
    src_folders: [nightwatchCucumber(nightwatchCucumberConf)],
    custom_commands_path: '',
    custom_assertions_path: '',
    page_objects_path: '',
    live_output: false,
    disable_colors: false,

    // Sets configuration for Selenium Server
    selenium: {
        start_process: true,
        server_path: seleniumServer.path,
        host: '127.0.0.1',
        port: 4444
    },

    // Sets config options for different testing environments defined by the user
    test_settings: {
        default: {
            launch_url: 'https://moduscreate.com',
            silent: true,
            desiredCapabilities: {
                browserName: 'chrome',
                javascriptEnabled: true,
                acceptSslCerts: true
            },
            'screenshots': {
                enabled: true,
                on_error: true,
                on_failure: true,
                path: '/screenshots'
            }
        },
        firefox: {
            desiredCapabilities: {
                browserName: 'firefox',
                javascriptEnabled: true,
                acceptSslCerts: true
            }
        }
    }
}
</code>```

features/about.feature

```<code>Feature: Modus About Page
    To establish that our website has an About Page
    As a user, I want to ensure that our Home page has a link to the about page

    Scenario: Verify About Page Link
        Given I open the Modus Create home page
        And the title is "Modus Create - HTML5 Application Development & Training"
        Then the About Page link exists
</code>```

step_definitions/about.js

```<code>const { client } = require('nightwatch-cucumber');
const { Given, Then, When } = require('cucumber');

    Given('I open the Modus Create home page', function () {
        client
            .url('https://moduscreate.com')
            .waitForElementVisible('body', 1000);
        return 'pending';
      });

    Given('the title is {string}', function (string) {
        client.assert.title(title);
        return 'pending';
      });

    Then('the About Page link exists', function () {
        client.assert.elementPresent('a[href="/about"]');
        return 'pending';
    });
</code>```

output from running nightwatch

```<code>Starting selenium server... started - PID:  13800
UUU

Warnings:

1) Scenario: Verify About Page Link # features\modusAbout.feature:6
   ? Given I open the Modus Create home page
       Undefined. Implement with the following snippet:

         Given('I open the Modus Create home page', function () {
           // Write code here that turns the phrase above into concrete actions
           return 'pending';
         });

   ? And the title is "Modus Create - HTML5 Application Development & Training"
       Undefined. Implement with the following snippet:

         Given('the title is {string}', function (string) {
           // Write code here that turns the phrase above into concrete actions
           return 'pending';
         });

   ? Then the About Page link exists
       Undefined. Implement with the following snippet:

         Then('the About Page link exists', function () {
           // Write code here that turns the phrase above into concrete actions
           return 'pending';
         });

1 scenario (1 undefined)
3 steps (3 undefined)
0m00.000s

true
'''
</code>```

答:
I would highly recommend to move from nightwatch-cucumber plugin to nightwatch-api.

Regarding the issue you are facing, I could not see any cucumber related settings in your config file which will help the runner to identify the step definition files. Below is a link which might give you an idea of what it needs.

http://mucsi96.github.io/nightwatch-cucumber/#passing-additional-cli-options-for-cucumberjs

https://github.com/mucsi96/nightwatch-cucumber/blob/master/examples/simple-example/nightwatch.conf.js#L5

Cheers!

Body:
Current behavior

step definitions are not being recognized … no matter what I try, when I run nightwatch my features and steps come back as undefined.

Expected/desired behavior

The code in my step_definitions folder is executed.

Environment:

nightwatch-cucumber version: 9.1.3

nightwatch version:0.9.21

cucumber version:6.0.5

Selenium_server version:3.141.59

Phantomjs-prebuilt version:2.1.16

Node.js version:10.17.0

Package.json

    {
      "name": "nightwatchcucumbertest",
      "version": "1.0.0",
      "description": "Test the setup of nightwatch and cucumber",
      "main": "index.js",
      "scripts": {
        "test": "nightwatch"
      },
      "author": "Mark Strohfus",
      "license": "ISC",
      "devDependencies": {
        "cucumber": "^6.0.5",
        "nightwatch": "^0.9.21",
        "nightwatch-cucumber": "^9.1.3",
        "phantomjs-prebuilt": "^2.1.16",
        "selenium-server": "^3.141.59"
      },
      "dependencies": {
        "cucumber": "^6.0.5",
        "phantomjs-prebuilt": "^2.1.16",
        "selenium-server": "^3.141.59"
      }
    }

nightwatch.conf.js

var seleniumServer = require('selenium-server')
var phantomjs = require('phantomjs-prebuilt')
var nightwatchCucumber = require('nightwatch-cucumber')

// Handles the runner, location of feature files and step definitions,
// and closing of nightwatch
var nightwatchCucumberConf = {
    runner: 'nightwatch',
    featureFiles: 'features',
    stepDefinitions: 'step_definitions',
    closeSession: 'afterFeature'
}

module.exports = {
    // Loads nightwatch-cucumber configuration into main nightwatch.js conf
    src_folders: [nightwatchCucumber(nightwatchCucumberConf)],
    custom_commands_path: '',
    custom_assertions_path: '',
    page_objects_path: '',
    live_output: false,
    disable_colors: false,

    // Sets configuration for Selenium Server
    selenium: {
        start_process: true,
        server_path: seleniumServer.path,
        host: '127.0.0.1',
        port: 4444
    },

    // Sets config options for different testing environments defined by the user
    test_settings: {
        default: {
            launch_url: 'https://moduscreate.com',
            silent: true,
            desiredCapabilities: {
                browserName: 'chrome',
                javascriptEnabled: true,
                acceptSslCerts: true
            },
            'screenshots': {
                enabled: true,
                on_error: true,
                on_failure: true,
                path: '/screenshots'
            }
        },
        firefox: {
            desiredCapabilities: {
                browserName: 'firefox',
                javascriptEnabled: true,
                acceptSslCerts: true
            }
        }
    }
}

features/about.feature

Feature: Modus About Page
    To establish that our website has an About Page
    As a user, I want to ensure that our Home page has a link to the about page

    Scenario: Verify About Page Link
        Given I open the Modus Create home page
        And the title is "Modus Create - HTML5 Application Development & Training"
        Then the About Page link exists

step_definitions/about.js

const { client } = require('nightwatch-cucumber');
const { Given, Then, When } = require('cucumber');

    Given('I open the Modus Create home page', function () {
        client
            .url('https://moduscreate.com')
            .waitForElementVisible('body', 1000);
        return 'pending';
      });

    Given('the title is {string}', function (string) {
        client.assert.title(title);
        return 'pending';
      });

    Then('the About Page link exists', function () {
        client.assert.elementPresent('a[href="/about"]');
        return 'pending';
    });

output from running nightwatch

Starting selenium server... started - PID:  13800
UUU

Warnings:

1) Scenario: Verify About Page Link # features\modusAbout.feature:6
   ? Given I open the Modus Create home page
       Undefined. Implement with the following snippet:

         Given('I open the Modus Create home page', function () {
           // Write code here that turns the phrase above into concrete actions
           return 'pending';
         });

   ? And the title is "Modus Create - HTML5 Application Development & Training"
       Undefined. Implement with the following snippet:

         Given('the title is {string}', function (string) {
           // Write code here that turns the phrase above into concrete actions
           return 'pending';
         });

   ? Then the About Page link exists
       Undefined. Implement with the following snippet:

         Then('the About Page link exists', function () {
           // Write code here that turns the phrase above into concrete actions
           return 'pending';
         });

1 scenario (1 undefined)
3 steps (3 undefined)
0m00.000s

true
'''


问:
How to replace ByteArray elements with modified in hex ASCII symbols?
I have a problem with QByteArray functions.
My intention is to write the function which will edit the QByteArray i.e:
Input: "1W34567"
Function adds 0x80 to 2nd char - W.
It should replace W(0x57 in ASCII) with ×(0xD7 in ASCII).
I try to solve this problem with following function:</p>

```<code>void MainWindow::msgModify(QByteArray& ba)
{
    QByteArray t1,t2;
    t1 = ba.toHex();
    int b1 = t1.mid(2,2).toInt(&OK, 16);
    b1+=0x80;
    t2 = QByteArray::number(b1);
    t2 = t2.toHex();
    qDebug() << t1; //Here output is "31573334353637" - correct
    t1 = QByteArray::fromHex(t1);
    qDebug() << t1; //I check if it will give me orginal msg, output is "1W34567" - correct
    qDebug() << b1; //215 decimal - it's correct
    qDebug() << t2; //"323135" I expect the symbol which has index 215 decimal in ASCII table but I
                    //got this - why?
}
</code>```

答:
OK, I solved my problem:

```<code>void MainWindow::msgModify(QByteArray& ba)
   {
    QByteArray hexBa = ba.toHex();
    int t = hexBa.mid(2,2).toInt(&OK,16) + 0x80;
    QByteArray c;
    hexBa.replace(2,2, c.setNum(t,16));
    ba = QByteArray::fromHex(hexBa);

   }
</code>```

I wanted that function to only modify 2nd character by adding 0x80 in hex format, ie.
Input:
ascii: "123456" -> hex: 3132333435
Output:
ascii: "1²3456" -> hex: 31B2333435

Of course console will encode it like "1\xB2""3456", but it doesn't metter, it turned out that hex format is most important in my case.

Body:
I have a problem with QByteArray functions.
My intention is to write the function which will edit the QByteArray i.e:
Input: "1W34567"
Function adds 0x80 to 2nd char - W.
It should replace W(0x57 in ASCII) with ×(0xD7 in ASCII).
I try to solve this problem with following function:

void MainWindow::msgModify(QByteArray& ba)
{
    QByteArray t1,t2;
    t1 = ba.toHex();
    int b1 = t1.mid(2,2).toInt(&OK, 16);
    b1+=0x80;
    t2 = QByteArray::number(b1);
    t2 = t2.toHex();
    qDebug() << t1; //Here output is "31573334353637" - correct
    t1 = QByteArray::fromHex(t1);
    qDebug() << t1; //I check if it will give me orginal msg, output is "1W34567" - correct
    qDebug() << b1; //215 decimal - it's correct
    qDebug() << t2; //"323135" I expect the symbol which has index 215 decimal in ASCII table but I
                    //got this - why?
}

Body:
OK, I solved my problem:

void MainWindow::msgModify(QByteArray& ba)
   {
    QByteArray hexBa = ba.toHex();
    int t = hexBa.mid(2,2).toInt(&OK,16) + 0x80;
    QByteArray c;
    hexBa.replace(2,2, c.setNum(t,16));
    ba = QByteArray::fromHex(hexBa);

   }

I wanted that function to only modify 2nd character by adding 0x80 in hex format, ie.
Input:
ascii: "123456" -> hex: 3132333435
Output:
ascii: "1²3456" -> hex: 31B2333435

Of course console will encode it like "1\xB2""3456", but it doesn't metter, it turned out that hex format is most important in my case.


问:
Typescript: How to defined type of object key for generic type
I have some piece of code like below. I write custom hook with generic type for defined custom type return of my hook.

```<code>type Return<T> = [T, (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void, Record<keyof T, boolean>, () => void]

function useInput<T>(): Return<T> {
    const [input, setInput] = useState<T>({} as T);
    const [isDirty, setDirty] = useState({} as Record<keyof T, boolean>);

    const handleInputChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setInput({
            ...input,
            [e.target.name]: e.target.value
        });
        setDirty({
            ...isDirty,
            [e.target.name]: true
        });
    };

    const resetInput = () => {
        Object.keys(input).forEach((v) => input[v] = ''); //this line i get error
        setInput({...input});
    };

    return [input, handleInputChange, isDirty, resetInput]
}

export default useInput;
</code>```

My generic type T is object. But when I loop over this, I get this error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. How can I defined type of key for generic type T? Please help me.

答:
So Object.keys function is not generic parametrized, by this reason v in the forEach is always string. Here is reasoning why - Why doesn't Object.keys return a keyof type in TypeScript?.

Thats said you cannot narrow type of v it will be just string. What you can do is type assertion:

```<code> Object.keys(input).forEach((v) => input[v as keyof T] = '')
</code>```

But you will get next error as you don't define that T has all values as strings, and you assign to it empty string. This is actually correct error. You cannot assign to every field of unknown object a string.

In order to fix the second we need to narrow the type of value of T

```<code>function useInput<T extends Record<string, string>>(): Return<T>
</code>```

We are saying now T has keys and values which are string or subtypes of string. Because of the fact that they can be subtypes of string we need to do the second assertion after. Why - Subtype can be for example 'a' | 'b' and such type cannot take empty string value.

```<code>Object.keys(input).forEach((v) => (input[v as keyof T] as string) = '')
</code>```

But without stating that T extends Record<string, string> we would not able to assert property type of such to string.

As I said before such implementation has an issue, its risky as if you have object which is for example type A { a: 'x' | 'y'} and you pass it to such construct, then you can get empty string in property a and this is invalid member of type A. But if you work with types which have string values only, and I assume you do, then its fully ok.

Body:
I have some piece of code like below. I write custom hook with generic type for defined custom type return of my hook.

type Return<T> = [T, (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void, Record<keyof T, boolean>, () => void]

function useInput<T>(): Return<T> {
    const [input, setInput] = useState<T>({} as T);
    const [isDirty, setDirty] = useState({} as Record<keyof T, boolean>);

    const handleInputChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setInput({
            ...input,
            [e.target.name]: e.target.value
        });
        setDirty({
            ...isDirty,
            [e.target.name]: true
        });
    };

    const resetInput = () => {
        Object.keys(input).forEach((v) => input[v] = ''); //this line i get error
        setInput({...input});
    };

    return [input, handleInputChange, isDirty, resetInput]
}

export default useInput;

My generic type T is object. But when I loop over this, I get this error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. How can I defined type of key for generic type T? Please help me.

Body:
So Object.keys function is not generic parametrized, by this reason v in the forEach is always string. Here is reasoning why - Why doesn't Object.keys return a keyof type in TypeScript?.

Thats said you cannot narrow type of v it will be just string. What you can do is type assertion:

 Object.keys(input).forEach((v) => input[v as keyof T] = '')

But you will get next error as you don't define that T has all values as strings, and you assign to it empty string. This is actually correct error. You cannot assign to every field of unknown object a string.

In order to fix the second we need to narrow the type of value of T

function useInput<T extends Record<string, string>>(): Return<T>

We are saying now T has keys and values which are string or subtypes of string. Because of the fact that they can be subtypes of string we need to do the second assertion after. Why - Subtype can be for example 'a' | 'b' and such type cannot take empty string value.

Object.keys(input).forEach((v) => (input[v as keyof T] as string) = '')

But without stating that T extends Record<string, string> we would not able to assert property type of such to string.

As I said before such implementation has an issue, its risky as if you have object which is for example type A { a: 'x' | 'y'} and you pass it to such construct, then you can get empty string in property a and this is invalid member of type A. But if you work with types which have string values only, and I assume you do, then its fully ok.


问:
How i can add choice field related to other model and pass id current objects?
I have the form:

```<code>class PersonForm(forms.ModelForm):
    amount = forms.DecimalField(label='Сумма')
    cars = forms.ModelChoiceField(
        queryset=CarProductData.objects.all()
    )

    class Meta:
        labels = {
            'last_name': 'Фамилия',
            'first_name': 'Имя',
            'middle_name': 'Отчество',
            'amount': 'Сумма к списанию',
        }
        fields = ['amount', ]

</code>```

and i want to get queryset inside admin.ModelAdmin related to current object, something like this:

```<code>    def get_form(self, request, obj, **kwargs):
        from django import forms
        from taxi_billing.models import CarProductData
        form = super().get_form(request, obj, **kwargs)
        form.cars = forms.ModelChoiceField(
            queryset=CarProductData.objects.filter(
                product__subscriptionitem__subscription__customer__person__id=obj.id
            )
        )
        return form
</code>```

How can i make it done?

答:
I found solution. I have to override method get_form that belongs to ModelAdmin.
Just add fields to the new_attrs dict.

```<code>       # Add to the dict fields what you need.
        new_attrs['Арнедованные автомобили'] = forms.ModelChoiceField(
            queryset=CarProductData.objects.filter(
                product__subscriptionitem__subscription__customer__person__id=obj.id
            )
        )
</code>```

```<code>    def get_form(self, request, obj=None, change=False, **kwargs):
        """
        Return a Form class for use in the admin add view. This is used by
        add_view and change_view.
        """

        if 'fields' in kwargs:
            fields = kwargs.pop('fields')
        else:
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))
        excluded = self.get_exclude(request, obj)
        exclude = [] if excluded is None else list(excluded)
        readonly_fields = self.get_readonly_fields(request, obj)
        exclude.extend(readonly_fields)
        if change and hasattr(request, 'user') and not self.has_change_permission(request, obj):
            exclude.extend(fields)
        if excluded is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
            exclude.extend(self.form._meta.exclude)
        exclude = exclude or None

        new_attrs = dict.fromkeys(f for f in readonly_fields if f in self.form.declared_fields)

       # Add to the dict fields what you need.
        new_attrs['Арнедованные автомобили'] = forms.ModelChoiceField(
            queryset=CarProductData.objects.filter(
                product__subscriptionitem__subscription__customer__person__id=obj.id
            )
        )

        form = type(self.form.__name__, (self.form,), new_attrs)

        defaults = {
            'form': form,
            'fields': fields,
            'exclude': exclude,
            'formfield_callback': partial(self.formfield_for_dbfield, request=request),
            **kwargs,
        }
        if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
            defaults['fields'] = forms.ALL_FIELDS

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError(
                '%s. Check fields/fieldsets/exclude attributes of class %s.'
                % (e, self.__class__.__name__)
            )

</code>```

Body:
I have the form:

class PersonForm(forms.ModelForm):
    amount = forms.DecimalField(label='Сумма')
    cars = forms.ModelChoiceField(
        queryset=CarProductData.objects.all()
    )

    class Meta:
        labels = {
            'last_name': 'Фамилия',
            'first_name': 'Имя',
            'middle_name': 'Отчество',
            'amount': 'Сумма к списанию',
        }
        fields = ['amount', ]

and i want to get queryset inside admin.ModelAdmin related to current object, something like this:

    def get_form(self, request, obj, **kwargs):
        from django import forms
        from taxi_billing.models import CarProductData
        form = super().get_form(request, obj, **kwargs)
        form.cars = forms.ModelChoiceField(
            queryset=CarProductData.objects.filter(
                product__subscriptionitem__subscription__customer__person__id=obj.id
            )
        )
        return form

How can i make it done?

Body:
I found solution. I have to override method get_form that belongs to ModelAdmin.
Just add fields to the new_attrs dict.

       # Add to the dict fields what you need.
        new_attrs['Арнедованные автомобили'] = forms.ModelChoiceField(
            queryset=CarProductData.objects.filter(
                product__subscriptionitem__subscription__customer__person__id=obj.id
            )
        )

    def get_form(self, request, obj=None, change=False, **kwargs):
        """
        Return a Form class for use in the admin add view. This is used by
        add_view and change_view.
        """

        if 'fields' in kwargs:
            fields = kwargs.pop('fields')
        else:
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))
        excluded = self.get_exclude(request, obj)
        exclude = [] if excluded is None else list(excluded)
        readonly_fields = self.get_readonly_fields(request, obj)
        exclude.extend(readonly_fields)
        if change and hasattr(request, 'user') and not self.has_change_permission(request, obj):
            exclude.extend(fields)
        if excluded is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
            exclude.extend(self.form._meta.exclude)
        exclude = exclude or None

        new_attrs = dict.fromkeys(f for f in readonly_fields if f in self.form.declared_fields)

       # Add to the dict fields what you need.
        new_attrs['Арнедованные автомобили'] = forms.ModelChoiceField(
            queryset=CarProductData.objects.filter(
                product__subscriptionitem__subscription__customer__person__id=obj.id
            )
        )

        form = type(self.form.__name__, (self.form,), new_attrs)

        defaults = {
            'form': form,
            'fields': fields,
            'exclude': exclude,
            'formfield_callback': partial(self.formfield_for_dbfield, request=request),
            **kwargs,
        }
        if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
            defaults['fields'] = forms.ALL_FIELDS

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError(
                '%s. Check fields/fieldsets/exclude attributes of class %s.'
                % (e, self.__class__.__name__)
            )


问:
How to inherit EventTarget Object?
I want to inherit EventTarget object.

So I tried the following code, which causes an error "Illegal constructor".

```<code>class OwnClass extends EventTarget {
  constructor () {
    super();
  }
}
function eventHandler () {
  console.log( arguments );
}
let et = new OwnClass();
et.addEventListener( "Own Event", eventHandler );
et.dispatchEvent( new Event( "Own Event" ) );
</code>```

So I use following code, currently.

```<code>class OwnClass extends Document {
  constructor () {
    super();
  }
}
function eventHandler () {
  console.log( arguments );
}
let et = new OwnClass();
et.addEventListener( "Own Event", eventHandler );
et.dispatchEvent( new Event( "Own Event" ) );
</code>```

But this cause meaningless memory usage.

Is there a way to inherit EventTarget directly?

答:
Maybe it comes a bit late for answering but now you can use the EventTarget class

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/EventTarget

Title: How to inherit EventTarget Object?

Body:
I want to inherit EventTarget object.

So I tried the following code, which causes an error "Illegal constructor".

class OwnClass extends EventTarget {
  constructor () {
    super();
  }
}
function eventHandler () {
  console.log( arguments );
}
let et = new OwnClass();
et.addEventListener( "Own Event", eventHandler );
et.dispatchEvent( new Event( "Own Event" ) );

So I use following code, currently.

class OwnClass extends Document {
  constructor () {
    super();
  }
}
function eventHandler () {
  console.log( arguments );
}
let et = new OwnClass();
et.addEventListener( "Own Event", eventHandler );
et.dispatchEvent( new Event( "Own Event" ) );

But this cause meaningless memory usage.

Is there a way to inherit EventTarget directly?


问:
Constrain layout is not working on all android devices screen size
I have the following layout, it works fine for big screens like note 9 Samsung, but it will not shrink to fit the screen size in small phones, please refer to the attached picture and codes.
I like to use the constraint layouts , I did choised all items to be in form of WRAPCONTENT or MATCHCONSTRAIN , but still have the start button jump out of screen in small phones .

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

    <EditText
        android:id="@+id/team1EdtTxt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="148dp"
        android:layout_marginLeft="148dp"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="49dp"
        android:layout_marginRight="49dp"
        android:layout_marginBottom="22dp"
        android:ems="10"
        android:hint="اللاعب 1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/team1EdtTxt2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/team1EdtTxt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="148dp"
        android:layout_marginLeft="148dp"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="49dp"
        android:layout_marginRight="49dp"
        android:layout_marginBottom="54dp"
        android:clickable="false"
        android:editable="false"
        android:ems="10"
        android:hint="اللاعب 2"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/team1EdtTxt1" />

    <EditText
        android:id="@+id/team2EdtTxt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="148dp"
        android:layout_marginLeft="148dp"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="49dp"
        android:layout_marginRight="49dp"
        android:layout_marginBottom="22dp"
        android:clickable="false"
        android:ems="10"
        android:hint="اللاعب 1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/team2EdtTxt2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <EditText
        android:id="@+id/team2EdtTxt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="148dp"
        android:layout_marginLeft="148dp"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="49dp"
        android:layout_marginRight="49dp"
        android:clickable="false"
        android:ems="10"
        android:hint="اللاعب 2"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/team2EdtTxt1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="209dp"
        android:layout_marginLeft="209dp"
        android:layout_marginTop="129dp"
        android:layout_marginEnd="41dp"
        android:layout_marginRight="41dp"
        android:layout_marginBottom="24dp"
        android:text="الفريق الاول"
        android:textSize="36sp"
        app:fontFamily="@font/advent_pro_thin"
        app:layout_constraintBottom_toTopOf="@+id/team1EdtTxt1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="209dp"
        android:layout_marginLeft="209dp"
        android:layout_marginTop="44dp"
        android:layout_marginEnd="41dp"
        android:layout_marginRight="41dp"
        android:layout_marginBottom="24dp"
        android:text="الفريق الثاني"
        android:textSize="36sp"
        app:layout_constraintBottom_toTopOf="@+id/team2EdtTxt1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/team1EdtTxt2" />

    <Button
        android:id="@+id/startBtn"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="110dp"
        android:layout_marginLeft="110dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="110dp"
        android:layout_marginRight="110dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/buttondomeno"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/team2EdtTxt2" />
</androidx.constraintlayout.widget.ConstraintLayout>```

答:
It doesn't fit because of fixed text sizes and margins in your views
You can try one of two things:
1) use ScrollView to make the layout scrollable
2) Remove hardcoded sizes and use different dimensions for different screen sizes</p>


问:
How to understand static shape and dynamic shape in TensorFlow?
In TensorFlow FAQ, it says:

In TensorFlow, a tensor has both a static (inferred) shape and a
  dynamic (true) shape. The static shape can be read using the
  tf.Tensor.get_shape() method: this shape is inferred from the
  operations that were used to create the tensor, and may be partially
  complete. If the static shape is not fully defined, the dynamic shape
  of a Tensor t can be determined by evaluating tf.shape(t).

But I still cannot fully understand the relationship between static shape and dynamic shape. Are there any examples showing their differences? Thanks.

答:
Tensorflow 2.0 Compatible Answer: Mentioning the Code which mrry has specified in his Answer, in Tensorflow Version 2.x (> 2.0), for the benefit of the Community.

```<code># Installing the Tensorflow Version 2.1
!pip install tensorflow==2.1

# If we don't Disable the Eager Execution, usage of Placeholder results in RunTimeError

tf.compat.v1.disable_eager_execution()

x = tf.compat.v1.placeholder(tf.int32, shape=[4])
print(x.get_shape())

# ==> 4

y, _ = tf.unique(x)
print(y.get_shape())

# ==> (None,)

sess = tf.compat.v1.Session()
print(sess.run(y, feed_dict={x: [0, 1, 2, 3]}).shape)
# ==> '(4,)'
print(sess.run(y, feed_dict={x: [0, 0, 0, 0]}).shape)
# ==> '(1,)'

z = tf.shape(y)
print(sess.run(z, feed_dict={x: [0, 1, 2, 3]}))
# ==> [4]
print(sess.run(z, feed_dict={x: [0, 0, 0, 0]}))
# ==> [1]
</code>```

Body:
Tensorflow 2.0 Compatible Answer: Mentioning the Code which mrry has specified in his Answer, in Tensorflow Version 2.x (> 2.0), for the benefit of the Community.

# Installing the Tensorflow Version 2.1
!pip install tensorflow==2.1

# If we don't Disable the Eager Execution, usage of Placeholder results in RunTimeError

tf.compat.v1.disable_eager_execution()

x = tf.compat.v1.placeholder(tf.int32, shape=[4])
print(x.get_shape())

# ==> 4

y, _ = tf.unique(x)
print(y.get_shape())

# ==> (None,)

sess = tf.compat.v1.Session()
print(sess.run(y, feed_dict={x: [0, 1, 2, 3]}).shape)
# ==> '(4,)'
print(sess.run(y, feed_dict={x: [0, 0, 0, 0]}).shape)
# ==> '(1,)'

z = tf.shape(y)
print(sess.run(z, feed_dict={x: [0, 1, 2, 3]}))
# ==> [4]
print(sess.run(z, feed_dict={x: [0, 0, 0, 0]}))
# ==> [1]


问:
COBOL Question - UNICODE
We are currently looking to convert our legacy COBOL code from ANSII to UNICODE however we have come across a problem where just changing the PIC X fields to PIC N and setting NSYMBOL(NATIONAL) will cause problems when data structures contain a REDEFINES or RENAME statement with elementary DATA items using PIC 9 fields.

```<code>01 WS-RECORD PIC N(26).
01 WS-RECORD-1 REDEFINES WS-RECORD.
02 WS-NUM PIC 9(6).
02 WS-DATA PIC N(20).

MOVE N"123456ABCDEFGHIJKLM" TO WS-RECORD.
</code>```

In the above the string being moved will be in UTF-16 format, therefore the field WS-NUM will be corrupt as it will contain X"310032003300" which is an invalid numeric, WS-DATA will contain X"3400350036004100..etc

The question is, when using NATIONAL (UTF-16) data types how can numerics be handled so as to get the correct data after it has been redefined.

I can sort of get this to work doing the following but will get invalid data in other WS-RECORD.

```<code>MOVE 123456 TO WS-NUM.
MOVE N"ABCDEFGHIJKLM" TO WS_DATA.
</code>```

The above will be correct, however if I examine WS-RECORD I will see ???ABCDEFGHIJKLM where ??? is X"313233343536" in hexi-decimal.

Our problem is that we have multiple data records depending on the record type identifier, we also use redefines on many of our LINKAGE ITEMS.

Has anyone had experience moving from legacy ASCII to UNICODE?

答:
You can use the DISPLAY-OF FUNCTION and reference modification and add a filler to ensure the size is balanced, add a 78 to reduce magic number use!

Anyway, as I said its a bit dirty but works..

eg:

```<code>  MOVE FUNCTION DISPLAY-OF(WS-RECORD-1(
                 1:LENGTH OF WS-RECORD(1:6)),1252)
</code>```

With the updated program being:

```<code>     78 NUM-SIZE  VALUE 6.

     01 WS-RECORD   PIC N(26).
     01 WS-RECORD-1 REDEFINES WS-RECORD.
       02 WS-NUM      PIC 9(NUM-SIZE).
       02 FILLER      PIC X(NUM-SIZE).
       02 WS-DATA     PIC N(20).

     MOVE N"123456ABCDEFGHIJKLM" TO WS-RECORD.

     DISPLAY "WS-NUM     : " WS-NUM
     DISPLAY "WS-DATA    : " WS-DATA

       MOVE FUNCTION DISPLAY-OF(WS-RECORD-1(
                 1:LENGTH OF WS-RECORD(1:NUM-SIZE)),1252)
              TO WS-NUM

     DISPLAY "WS-NUM     : " WS-NUM
     DISPLAY "WS-DATA    : " WS-DATA
</code>```

(updated with a better solution)

Title: COBOL Question - UNICODE

Body:
We are currently looking to convert our legacy COBOL code from ANSII to UNICODE however we have come across a problem where just changing the PIC X fields to PIC N and setting NSYMBOL(NATIONAL) will cause problems when data structures contain a REDEFINES or RENAME statement with elementary DATA items using PIC 9 fields.

01 WS-RECORD PIC N(26).
01 WS-RECORD-1 REDEFINES WS-RECORD.
02 WS-NUM PIC 9(6).
02 WS-DATA PIC N(20).

MOVE N"123456ABCDEFGHIJKLM" TO WS-RECORD.

In the above the string being moved will be in UTF-16 format, therefore the field WS-NUM will be corrupt as it will contain X"310032003300" which is an invalid numeric, WS-DATA will contain X"3400350036004100..etc

The question is, when using NATIONAL (UTF-16) data types how can numerics be handled so as to get the correct data after it has been redefined.

I can sort of get this to work doing the following but will get invalid data in other WS-RECORD.

MOVE 123456 TO WS-NUM.
MOVE N"ABCDEFGHIJKLM" TO WS_DATA.

The above will be correct, however if I examine WS-RECORD I will see ???ABCDEFGHIJKLM where ??? is X"313233343536" in hexi-decimal.

Our problem is that we have multiple data records depending on the record type identifier, we also use redefines on many of our LINKAGE ITEMS.

Has anyone had experience moving from legacy ASCII to UNICODE?

Body:
You can use the DISPLAY-OF FUNCTION and reference modification and add a filler to ensure the size is balanced, add a 78 to reduce magic number use!

Anyway, as I said its a bit dirty but works..

eg:

  MOVE FUNCTION DISPLAY-OF(WS-RECORD-1(
                 1:LENGTH OF WS-RECORD(1:6)),1252)

With the updated program being:

     78 NUM-SIZE  VALUE 6.

     01 WS-RECORD   PIC N(26).
     01 WS-RECORD-1 REDEFINES WS-RECORD.
       02 WS-NUM      PIC 9(NUM-SIZE).
       02 FILLER      PIC X(NUM-SIZE).
       02 WS-DATA     PIC N(20).

     MOVE N"123456ABCDEFGHIJKLM" TO WS-RECORD.

     DISPLAY "WS-NUM     : " WS-NUM
     DISPLAY "WS-DATA    : " WS-DATA

       MOVE FUNCTION DISPLAY-OF(WS-RECORD-1(
                 1:LENGTH OF WS-RECORD(1:NUM-SIZE)),1252)
              TO WS-NUM

     DISPLAY "WS-NUM     : " WS-NUM
     DISPLAY "WS-DATA    : " WS-DATA

(updated with a better solution)


问:
How Spring Boot Autowired and Post Construct work?
I have three classes as following -

```<code>@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@Component
public class Test {
    @Autowired
    Test2 test2;

    @PostConstruct
    public void sayHi(){
        System.out.println("Hello World");
        test2.SayHello();
    }

    public void printMe(){
        System.out.println("print me is called in Bean B");
    }
}

@Component
public class Test2 {
    @Autowired
    Test test;

    @PostConstruct
    public void SayHello(){
        System.out.println("Test2");
        test.sayHi();
    }
}
</code>```

Now this one throws exception -

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test2': Invocation of init method failed; nested exception is java.lang.NullPointerException
</code>```

However, if I change the class Test2 as follows -

```<code>    @Component
public class Test2 {
    @Autowired
    Test test;

    @PostConstruct
    public void SayHello(){
        System.out.println("Test2");
        test.printMe();
    }
}
</code>```

This one works. If it had to fail, why it did not fail in both the cases?
Or if it had to succeed, why it did not succeed in both the cases?

How Spring initialization with autowired and post constructor work?

答:
Spring instantiates beans and injects dependencies for them according to their relation.

Spring guarantees that a declared bean will have all its dependencies injected/set before that it invokes its method annotated @PostConstruct.

Here the relations between the beans :

Test --uses--> Test2

Test2 --uses--> Test

Here how it works :

1) Spring instantiates a bean and then the other without injecting their dependencies.  So far, the order doesn't matter.

2) Spring injects dependencies for a first bean. Since here dependencies are bi-directional, Spring decides arbitrarily which bean to handle firsrt. In your case, according to your error, Spring handles first Test2.

3) Spring invokes the @PostConstruct method of the Test2 bean after setting its dependencies.

The method you defined invokes the method of the Test bean that uses a dependency field (Test2 test2).
But since dependencies of that bean were not set yet,
that field is null and access it triggers NPE.

In your working case, you invoke from Test2 a Test method that doesn't refer to its dependency fields.

Note that cyclic dependencies are generally not recommended. Here is an illustration of problems that it may produce.

When you cannot remove them, you should at least avoid invoking the other bean in the @PostConstruct method because it defeats the job done by the container to break the cycle during their initialization.

Body:
I have three classes as following -

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@Component
public class Test {
    @Autowired
    Test2 test2;

    @PostConstruct
    public void sayHi(){
        System.out.println("Hello World");
        test2.SayHello();
    }

    public void printMe(){
        System.out.println("print me is called in Bean B");
    }
}

@Component
public class Test2 {
    @Autowired
    Test test;

    @PostConstruct
    public void SayHello(){
        System.out.println("Test2");
        test.sayHi();
    }
}

Now this one throws exception -

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test2': Invocation of init method failed; nested exception is java.lang.NullPointerException

However, if I change the class Test2 as follows -

    @Component
public class Test2 {
    @Autowired
    Test test;

    @PostConstruct
    public void SayHello(){
        System.out.println("Test2");
        test.printMe();
    }
}

This one works. If it had to fail, why it did not fail in both the cases?
Or if it had to succeed, why it did not succeed in both the cases?

How Spring initialization with autowired and post constructor work?