问:
Capturing span error for a text box with selenium python
With the script below i am trying to get the error text from a span error text box for first name when a name is not entered and the user clicks on the submit button, from a registration screen with the HTML below.(https://www.walmart.com/account/signup. However I end up just getting none instead of the text. When i try to get the text from chrome console i receive the text with the xpath and css selector as "$x("//span[@class='span-error']")[2]" and "$$(".span-error")[2]". I would like some guidance as to what I am missing, i think have tried everything i can think of.

Test case:

Get to the link Enter nothing on the first name,Get a validation
error Assert the validation error Enter an invalid name as ":::" Get
a validation error (they seem to have a couple)and so on

```<code>from time import sleep
from conftest import os
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

# LoginScreenSelectors
sel_first_name = "#first-name-su"
sel_last_name = "#last-name-su"
sel_email = "#email-su"
sel_password = "#password-su"
sel_error_message = ".span-error:nth-of-type(2)"
sel_submit = f"""[data-automation-id="signup-submit-btn"]"""
sel_required_error = f"""[data-error="required"]"""

class Login():
    '''This will signup to the applcaiton '''

    def __init__(self, driver):
        self.driver = driver
        wait = WebDriverWait(self.driver, 20)
        self.first_name = wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR, sel_first_name))
        )
        self.last_name = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_last_name))
        )
        self.email = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_email))
        )
        self.password = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_password))
        )
        self.submit = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_submit))
        )

    def login_to_website(self):
        wait = WebDriverWait(self.driver, 10)
        print(self.driver.title)
        self.first_name.click()
        self.first_name.send_keys("  ")
        self.first_name.send_keys(Keys.TAB)

        self.first_name_error_message = wait.until(
             EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_error_message))
         )
        type(self.first_name_error_message)
        error_messages = []
        for messages in self.first_name_error_message:
            print(error_messages.append(messages.text))

        #if i could get this then i could simply get the first index and then keep filtering
         it but even that is proving to be difficult.
</code>```

答:
Try out this to get all elements with error messages</p>

```<code>error_messages = self.driver.find_elements(By.XPATH, "//*[@id="sign-up-form"]/div/span[2]']")
</code>```

Body:
With the script below i am trying to get the error text from a span error text box for first name when a name is not entered and the user clicks on the submit button, from a registration screen with the HTML below.(https://www.walmart.com/account/signup. However I end up just getting none instead of the text. When i try to get the text from chrome console i receive the text with the xpath and css selector as "$x("//span[@class='span-error']")[2]" and "$$(".span-error")[2]". I would like some guidance as to what I am missing, i think have tried everything i can think of.

Test case:

Get to the link Enter nothing on the first name,Get a validation
error Assert the validation error Enter an invalid name as ":::" Get
a validation error (they seem to have a couple)and so on

from time import sleep
from conftest import os
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

# LoginScreenSelectors
sel_first_name = "#first-name-su"
sel_last_name = "#last-name-su"
sel_email = "#email-su"
sel_password = "#password-su"
sel_error_message = ".span-error:nth-of-type(2)"
sel_submit = f"""[data-automation-id="signup-submit-btn"]"""
sel_required_error = f"""[data-error="required"]"""

class Login():
    '''This will signup to the applcaiton '''

    def __init__(self, driver):
        self.driver = driver
        wait = WebDriverWait(self.driver, 20)
        self.first_name = wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR, sel_first_name))
        )
        self.last_name = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_last_name))
        )
        self.email = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_email))
        )
        self.password = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_password))
        )
        self.submit = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_submit))
        )

    def login_to_website(self):
        wait = WebDriverWait(self.driver, 10)
        print(self.driver.title)
        self.first_name.click()
        self.first_name.send_keys("  ")
        self.first_name.send_keys(Keys.TAB)

        self.first_name_error_message = wait.until(
             EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_error_message))
         )
        type(self.first_name_error_message)
        error_messages = []
        for messages in self.first_name_error_message:
            print(error_messages.append(messages.text))

        #if i could get this then i could simply get the first index and then keep filtering
         it but even that is proving to be difficult.

Body:
Try out this to get all elements with error messages

error_messages = self.driver.find_elements(By.XPATH, "//*[@id="sign-up-form"]/div/span[2]']")


来源: stackexchange

问:
On printing webpage , it prints all the images of image slider
I have got a jquery image slider on my webpage , when i try to print that page all the  images of that slider are printed , I want to print the current slide image , how can i acheive that , Below is the website :
Duxbury Caravans</p>

答:
It seems your stylesheet isn't being applied on print. I've had the same problem before. Adding an explicit "print" stylesheet fixed it:

```<code><link rel="stylesheet" type="text/css" media="print" href="style.css">
</code>```

Actually looking at your source, you are specifically saying media="screen", so maybe changing that to media="all" will work too.

ContentLicense: CC BY-SA 3.0

Body:
It seems your stylesheet isn't being applied on print. I've had the same problem before. Adding an explicit "print" stylesheet fixed it:

<link rel="stylesheet" type="text/css" media="print" href="style.css">

Actually looking at your source, you are specifically saying media="screen", so maybe changing that to media="all" will work too.


问:
Terraform and Azure Data Explorer
I am looking for recipes on how to standup a complete Azure Data Explorer stack using Terraform. So far I have found that Terraform has support to create clusters, apply access control and create databases.

I am yet to find guidance/recipes on creation of tables and table mappings.

How are others provisioning complete Azure Data Explorer stacks? What are some of the best practices to integrate create tables/table-mappings sql calls with Terraform scripts?

Thanks in advance.

答:
Update
This functionality is now released. Please check out this blog that explains how to configure a complete Azure Data Explorer with ARM templates that execute KQL configuration scripts during the deployment.

https://techcommunity.microsoft.com/t5/azure-data-explorer-blog/use-kql-scripts-to-configure-databases-e2e/ba-p/3063130

==================Previous Answer ==================

We are considering those.

Please vote for these on https://feedback.azure.com/d365community/idea/aa060248-ec24-ec11-b6e6-000d3a4f0da0

This is a known gap and we are looking at closing it. Till then you can execute control commands to create the table and mapping from a script/code.

ContentLicense: CC BY-SA 4.0

Title: Terraform and Azure Data Explorer


问:
NLP techniques for evaluating grammatical correctness?
I'm curious about applying NLP to predict/evaluate someone's level of education (or adherence to correct grammar, spelling, etc.) by analyzing text written by them.

It would be something like: f(t) = s where t is a text and s is some score which rates the grammatical correctness of that text.

Does that exist? I don't know how to search for it. If it does, I'd like some references to relevant papers or algorithms.

答:
It does not exist. "Grammatical correctness" is a vague concept anyway, as there is no complete grammatical description of any given language. Also, we all speak and write different variations of our language, which cannot be captured by a single grammar. A language is basically the union of all the individual variants that its speakers produce.

Leaving aside these linguistic philosophy issues, there is also no formal grammar of even a single variant of a language that you could use as a benchmark. I guess the nearest thing you could do is come up with a couple of heuristics and simple rules (which I assume commercial grammar checkers use), checking for example that reads always occurs after a third person singular noun. If you have a sufficient number of such heuristics, you can get an idea if a given text is grammatical according to the definition that grammaticality is equivalent to not breaking the rules you encoded.

However, language is very flexible, and hard to capture in rules. Sometimes a sentence might sound like an error, but then in a given context it is fine. If it was easy, someone would already have done it, and primary school teachers could focus their efforts on tasks other than teaching basic grammar...

You can probably capture a number of 'mistakes' easily, but I wouldn't want to guess what coverage you would get; there will be a lot of issues you cannot capture easily.


问:
Prevent UIButton touch event for multitouch
after finding out that there is a bug in the UITapGestureRecognizer ( How to cancel button tap if UIGestureRecognizer fires? ) I am thinking about detecting two finger taps and two finger double-taps in the touchesEnded method of my view controller.

Here is the situation, what I want to do and my problem:

Situaion: I have a UIView, managed by a UIViewController. This view contains multiple UIButtons that react to taps.

What I want: I want to react to two finger taps and to two finger double-taps on my view but also to one finger taps on the UIButtons.

Problem: Once a button is tapped (even if using two fingers on the view) the touchesEnded method on my view controller isn't called anymore.
How can I cancel button taps when more than one finger is used?

I already tried to subclass UIView and use the hitTest method, but the touches property of the event is always empty in this. Also I tried to overlay the buttons with a transparent UIView, but this also cancels the button touches.

答: @Mark I was trying to get your example from the other day working. As it is a bug, I altered it to use a tap recognizer. It's not a true solution as you don't get a clicked effect on the button but the right button messages the Touch Up Inside event. You can check out those changes here. See if it helps.


问:
Join two arrays of different size with condition
i have two arrays of different sizes and i want them to joint in one only if first three elements match.

for exapmle:

```<code>A1 = [
    [1,8,9,8,2],
    [2,9,9,8,2],
    [1,7,7,8,2],
    [8,6,2,6,7]
]

A2 = [[2,9,9,30,60],
      [8,6,2,70,20]]

Result = [[2,9,9,8,2,30,60]
         [8,6,2,6,7,70,20]]
</code>```

I guess there is some numpy function for this but i couldn't find it.

答:
```<code>result = [i+j[3:] for i in A1 for j in A2 if i[:3]==j[:3]]
</code>```

This is equivalent to:

```<code>result = []
for i in A1:
    for j in A2:
       if (i[:3] == j[:3]): # if the first three element match

           # skip the first 3 elements in j (they're already included in i)
           result.append(i + j[3:])
</code>```

To do this with numpy arrays:

```<code>result = np.array([np.concatenate((i,j[3:])) for i in A1 for j in A2 if all(i[:3]==j[:3])])
</code>```

Here we used np.concatenate() to merge the two arrays, and used all() to compare the first 3 elements.

Body:
i have two arrays of different sizes and i want them to joint in one only if first three elements match.

for exapmle:

A1 = [
    [1,8,9,8,2],
    [2,9,9,8,2],
    [1,7,7,8,2],
    [8,6,2,6,7]
]

A2 = [[2,9,9,30,60],
      [8,6,2,70,20]]

Result = [[2,9,9,8,2,30,60]
         [8,6,2,6,7,70,20]]

I guess there is some numpy function for this but i couldn't find it.

Body:
result = [i+j[3:] for i in A1 for j in A2 if i[:3]==j[:3]]

This is equivalent to:

result = []
for i in A1:
    for j in A2:
       if (i[:3] == j[:3]): # if the first three element match

           # skip the first 3 elements in j (they're already included in i)
           result.append(i + j[3:])

To do this with numpy arrays:

result = np.array([np.concatenate((i,j[3:])) for i in A1 for j in A2 if all(i[:3]==j[:3])])

Here we used np.concatenate() to merge the two arrays, and used all() to compare the first 3 elements.


问:
Trouble passing props to imported component
I have a "main" component which imports two other components, which contain a form each, and I'm having trouble passing some values which I get from an API call in the main component.

This is an example of what's happening on the "main" component with one of the imported forms:

```<code>user_id = null;
email = "";

componentDidMount() {
    get(`user-data/`, this.token).then((response) => {
        this.user_id = response.user_id;
        this.email = response.email;
        // Doing a console.log at this point shows both values are assigned properly
        // And that they exist
    }).catch((error) => notify.notifyError(error.message));
}

<UserForm
  email={this.email}
  id={this.user_id}
></UserForm>;
</code>```

Edit: I'm including the API call logic since I believe it has something to do with the issue.

```<code>export const get = async (url, authToken) => {
  try {
    const response = await axiosInstance.get(`${url}`, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `${BEARER} ${authToken}`,
      },
    });
    return response;
  } catch (error) {
    throw new Error();
  }
};
</code>```

On the UserForm component:

```<code>id = null;
email = "";

constructor(props) {
    super(props);
    this.id = props.id;
    this.email = props.email;
    // Doing a console.log here shows both props are empty
    // Trying to use either of them from here on out breaks the page
}
</code>```

I assume the issue has to do with the components rendering before the value gets assigned, but I'm not entirely sure about it.

Why aren't the props received properly on the imported form, and how can I make sure they are?

Edit 2: Waiting for props to be set on componentDidUpdate works, but operating the way I need to creates and endless loop of execution of componentDidUpdate

```<code>  componentDidUpdate() {
    if (this.props.id) {
      console.log("props are set!");
      this.getData();
    }
  }

  getData() {
    get(`user-data/${this.props.id}`, this.token)
      .then((user) => {
        // This creates and endless loop of updating
        this.setState({
          ...user.data
        });
      })
      .catch((error) => notify.notifyError(error.message));
  }
</code>```

答:
Since this two values are not managed by state, when the values varies, it won't triggered re-render. Hence, the props are not getting the up-to-date value. I suggest using state to handle those 2 values

```<code>constructor(props){
   this.state = {
    user_id = null;
    email = "";
   }
}

componentDidMount() {
    get(`user-data/`, this.token).then((response) => {
        console.log('response works fine?', response)
        this.setState = {
          user_id = response.user_id;
          email = response.email;
        }

        // Doing a console.log at this point shows both values are assigned properly
        // And that they exist
    }).catch((error) => notify.notifyError(error.message));
}

render(){

<UserForm
  email={this.state.email}
  id={this.state.user_id}
></UserForm>;

}

</code>```

In your UseForm component, there is no need to place it in state unless you want to do further modification. I suggest directly test them in render method.

```<code>
constructor(props) {
    super(props);
}

render(){
   const {id, email} = this.props
   return (
     <div>
        {id} and {email}
     </div>
   )
}
</code>```

Body:
I have a "main" component which imports two other components, which contain a form each, and I'm having trouble passing some values which I get from an API call in the main component.

This is an example of what's happening on the "main" component with one of the imported forms:

user_id = null;
email = "";

componentDidMount() {
    get(`user-data/`, this.token).then((response) => {
        this.user_id = response.user_id;
        this.email = response.email;
        // Doing a console.log at this point shows both values are assigned properly
        // And that they exist
    }).catch((error) => notify.notifyError(error.message));
}

<UserForm
  email={this.email}
  id={this.user_id}
></UserForm>;

Edit: I'm including the API call logic since I believe it has something to do with the issue.

export const get = async (url, authToken) => {
  try {
    const response = await axiosInstance.get(`${url}`, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `${BEARER} ${authToken}`,
      },
    });
    return response;
  } catch (error) {
    throw new Error();
  }
};

On the UserForm component:

id = null;
email = "";

constructor(props) {
    super(props);
    this.id = props.id;
    this.email = props.email;
    // Doing a console.log here shows both props are empty
    // Trying to use either of them from here on out breaks the page
}

I assume the issue has to do with the components rendering before the value gets assigned, but I'm not entirely sure about it.

Why aren't the props received properly on the imported form, and how can I make sure they are?

Edit 2: Waiting for props to be set on componentDidUpdate works, but operating the way I need to creates and endless loop of execution of componentDidUpdate

  componentDidUpdate() {
    if (this.props.id) {
      console.log("props are set!");
      this.getData();
    }
  }

  getData() {
    get(`user-data/${this.props.id}`, this.token)
      .then((user) => {
        // This creates and endless loop of updating
        this.setState({
          ...user.data
        });
      })
      .catch((error) => notify.notifyError(error.message));
  }

Body:
Since this two values are not managed by state, when the values varies, it won't triggered re-render. Hence, the props are not getting the up-to-date value. I suggest using state to handle those 2 values

constructor(props){
   this.state = {
    user_id = null;
    email = "";
   }
}

componentDidMount() {
    get(`user-data/`, this.token).then((response) => {
        console.log('response works fine?', response)
        this.setState = {
          user_id = response.user_id;
          email = response.email;
        }

        // Doing a console.log at this point shows both values are assigned properly
        // And that they exist
    }).catch((error) => notify.notifyError(error.message));
}

render(){

<UserForm
  email={this.state.email}
  id={this.state.user_id}
></UserForm>;

}

In your UseForm component, there is no need to place it in state unless you want to do further modification. I suggest directly test them in render method.

constructor(props) {
    super(props);
}

render(){
   const {id, email} = this.props
   return (
     <div>
        {id} and {email}
     </div>
   )
}


问:
How to install discord.py rewrite?
I ran python3 -m pip install -U discord.py but it only installed discord.py v0.16.x. How do I install the new discord.py rewrite v1.0?

I uninstalled the old discord.py using pip uninstall discord.py and re-ran pip to install discord.py, only to get version v0.16.x again instead of the new v1.0 version.

答:
Easy, open Command Prompt and type "pip install discord.py"
If you do that you're most probably going to want "pip install requests"
If the pip command doesn't work, open your python installer and make sure to click on the add to evironment variables option!
That's all your good to go!
Use Visual Studio Code or Atom, they are the best so far that I have used for my bot!</p>

Title: How to install discord.py rewrite?


问:
Is there any way to interact with open external application alert from a webpage using selenium?
I tried switching tab that had popup using driver.switch_to.window(driver.window_handles[1])
and
closing the first tab, but none of them worked
This is the code that I tried to accept the popup driver.switch_to_alert().accept()

答: It is not the usual javascript pop up. It is the browser pop up and you can't handle it with the code. I believe that you need to create a script with AutoIT to handle the same.</p>


问:
Calculate absolute difference |A-B| in assembly using only INC, DEC, JNZ, HALT - interview question
This is a question I encountered in an interview and for which I didn't find a solution - so I tried to solve it myself.

We can use pseudocode here - it doesn't need to be a formal code.

The question is to get the absolute difference of unsigned inputs:

Assume your assembly language includes ONLY the following instructions: inc, dec, jnz and halt (halt = stop running).

Task: A and B are registers that hold non-negative values.
  The program should calculate the value of |A-B| and locate the result in C. In addition, the language holds registers C, D, ..., Z, which you can assume are initialized to zero at program start.

This is my attempt, where my main idea is to decrease both registers till one becomes zero, and then move the other register's value to C:

```<code>// zero case handling
dec a
inc a
jnz a_pre_loop_not_zero // a != 0
// a == 0, check if b == 0
dec b
inc b
jnz move_b_to_c // a == 0, b !=0
// a == 0 , b == 0 -> c needs to be 0
halt

a_pre_loop_not_zero:
  dec b
  inc b
  jnz main_loop // a != 0, b != 0

// a != 0 , b == 0
move_a_to_c:
    inc c
    dec a
    jnz move_a_to_c
    halt

// a,b != 0
main_loop:
  dec b
  jnz b_not_zero // b!=0
  // b became zero before a -> a contains result+1 now
  dec a
  jnz move_a_to_c
  halt // if a == 0 now -> a == b -> c needs to be 0

  b_not_zero:
      dec a
      jnz main_loop // a != 0

  // a became zero before b -> b contains the result now
  move_b_to_c:
    inc c
    dec b
    jnz move_b_to_c
    halt
</code>```

Now, I think that it works - but it looks very dirty.

To be more specific, I think the zero case handling can be done in a cleaner way, and maybe we can even consider it in the main loop (without checking it in a pre loop code).

Also, I didn't use the fact that registers C, D, ..., Z are initialized to 0 and can be used - which makes me suspect that maybe there's a better way.

Is there a better solution for this problem?

答:
Now, I think that it works - but it looks very dirty.

You can improve how it looks by writting it more the assembly way:

```<code>    dec A                   // zero case handling
    inc A
    jnz A_pre_loop_not_zero // A != 0
    dec B                   // A == 0, check if B == 0
    inc B
    jnz move_B_to_C         // A == 0, B !=0
    halt                    // A == 0, B == 0 -> C needs to be 0
A_pre_loop_not_zero:
    dec B
    inc B
    jnz main_loop           // A != 0, B != 0

move_A_to_C:                // A != 0, B == 0
    inc C
    dec A
    jnz move_A_to_C
    halt
main_loop:                  // A,B != 0
    dec B
    jnz B_not_zero          // B != 0
    dec A                   // B became zero before A -> A contains result+1 now
    jnz move_A_to_C
    halt                    // if A == 0 now -> A == B -> C needs to be 0
B_not_zero:
    dec A
    jnz main_loop           // a != 0
move_B_to_C:                // a became zero before b -> b contains the result now
    inc c
    dec B
    jnz move_B_to_C
    halt
</code>```

The suggestion by Eric Eidt to increment A and B beforehand moves away from possible zeroes.

I think we can assume that both inc and dec use wraparound logic. If not these increments on A and B would be wrong!

```<code>    inc     A
    inc     B

L1: dec     A
    jnz     L4

L2: dec     B
    jnz     L3
    halt
L3: inc     C      ; A == 0 -> C = B
    jnz     L2     ; (*)

L4: dec     B
    jnz     L1

L5: inc     C      ; B == 0 -> C = A
    dec     A
    jnz     L5
    halt
</code>```

Incrementing the C register will never produce zero. Therefore the conditional jump marked with an asterisk will always jump. This shaved off 2 instructions.

A bit old school perhaps, but definitively nice to look at...

Body:
This is a question I encountered in an interview and for which I didn't find a solution - so I tried to solve it myself.

We can use pseudocode here - it doesn't need to be a formal code.

The question is to get the absolute difference of unsigned inputs:

Assume your assembly language includes ONLY the following instructions: inc, dec, jnz and halt (halt = stop running).

Task: A and B are registers that hold non-negative values.
  The program should calculate the value of |A-B| and locate the result in C. In addition, the language holds registers C, D, ..., Z, which you can assume are initialized to zero at program start.

This is my attempt, where my main idea is to decrease both registers till one becomes zero, and then move the other register's value to C:

// zero case handling
dec a
inc a
jnz a_pre_loop_not_zero // a != 0
// a == 0, check if b == 0
dec b
inc b
jnz move_b_to_c // a == 0, b !=0
// a == 0 , b == 0 -> c needs to be 0
halt

a_pre_loop_not_zero:
  dec b
  inc b
  jnz main_loop // a != 0, b != 0

// a != 0 , b == 0
move_a_to_c:
    inc c
    dec a
    jnz move_a_to_c
    halt

// a,b != 0
main_loop:
  dec b
  jnz b_not_zero // b!=0
  // b became zero before a -> a contains result+1 now
  dec a
  jnz move_a_to_c
  halt // if a == 0 now -> a == b -> c needs to be 0

  b_not_zero:
      dec a
      jnz main_loop // a != 0

  // a became zero before b -> b contains the result now
  move_b_to_c:
    inc c
    dec b
    jnz move_b_to_c
    halt

Now, I think that it works - but it looks very dirty.

To be more specific, I think the zero case handling can be done in a cleaner way, and maybe we can even consider it in the main loop (without checking it in a pre loop code).

Also, I didn't use the fact that registers C, D, ..., Z are initialized to 0 and can be used - which makes me suspect that maybe there's a better way.

Is there a better solution for this problem?

Body:
Now, I think that it works - but it looks very dirty.

You can improve how it looks by writting it more the assembly way:

    dec A                   // zero case handling
    inc A
    jnz A_pre_loop_not_zero // A != 0
    dec B                   // A == 0, check if B == 0
    inc B
    jnz move_B_to_C         // A == 0, B !=0
    halt                    // A == 0, B == 0 -> C needs to be 0
A_pre_loop_not_zero:
    dec B
    inc B
    jnz main_loop           // A != 0, B != 0

move_A_to_C:                // A != 0, B == 0
    inc C
    dec A
    jnz move_A_to_C
    halt
main_loop:                  // A,B != 0
    dec B
    jnz B_not_zero          // B != 0
    dec A                   // B became zero before A -> A contains result+1 now
    jnz move_A_to_C
    halt                    // if A == 0 now -> A == B -> C needs to be 0
B_not_zero:
    dec A
    jnz main_loop           // a != 0
move_B_to_C:                // a became zero before b -> b contains the result now
    inc c
    dec B
    jnz move_B_to_C
    halt

The suggestion by Eric Eidt to increment A and B beforehand moves away from possible zeroes.

I think we can assume that both inc and dec use wraparound logic. If not these increments on A and B would be wrong!

    inc     A
    inc     B

L1: dec     A
    jnz     L4

L2: dec     B
    jnz     L3
    halt
L3: inc     C      ; A == 0 -> C = B
    jnz     L2     ; (*)

L4: dec     B
    jnz     L1

L5: inc     C      ; B == 0 -> C = A
    dec     A
    jnz     L5
    halt

Incrementing the C register will never produce zero. Therefore the conditional jump marked with an asterisk will always jump. This shaved off 2 instructions.

A bit old school perhaps, but definitively nice to look at...


问:
Can't find variable: regeneratorRuntime (ReactNative)
While trying to run my project on an android emulator, the device throws this error emulator screenshot. I cannot seem to figure out what I am doing wrong. I am still quite new to react  </p>

答:
For anyone coming across this post later, @babel/polyfill has been deprecated in favour of core-js. See https://babeljs.io/docs/en/babel-polyfill

If you're using >7.4.0 babel, you should be able to configure this using @babel/env. Set your targets in .babelrc (or whatever you call your babel config)

```<code>{
"presets": [
  [
  "@babel/env",
    {
      "targets": {
        "edge": "17",
        "firefox": "60",
        "chrome": "67",
        "safari": "11.1"
        }
      }
    ]
  ]
}
</code>```

https://babeljs.io/docs/en/usage#configuration

Body:
For anyone coming across this post later, @babel/polyfill has been deprecated in favour of core-js. See https://babeljs.io/docs/en/babel-polyfill

If you're using >7.4.0 babel, you should be able to configure this using @babel/env. Set your targets in .babelrc (or whatever you call your babel config)

{
"presets": [
  [
  "@babel/env",
    {
      "targets": {
        "edge": "17",
        "firefox": "60",
        "chrome": "67",
        "safari": "11.1"
        }
      }
    ]
  ]
}

https://babeljs.io/docs/en/usage#configuration


问:
how to transform Gridview into Listview in flutter?
i would like to transform a GridView into a Listview, here is the Gridview code:

and here is what i tried to do :

```<code>      return ListView.builder(
 itemBuilder: (context,index){
     _buildGridCards(context);
   }

   );
  }

    List<dynamic> _buildGridCards(BuildContext context) {
   if (widget.productsToDisplay == null || widget.productsToDisplay.isEmpty) {
    return const <Card>[];
     }
   final ThemeData theme = Theme.of(context);
    return widget.productsToDisplay.map((product) {
    Uint8List img64;
    try {
    img64 = base64Decode(product.image);
    } catch (e) {
    print(e);
    }

  return Card(
    clipBehavior: Clip.antiAlias,
    child: InkWell(
      onTap: () {
        Navigator.push(
          context,
             ...
</code>```

when i executed the code, nothing appeared

答:
I believe you forgot itemCount, so the final will be

```<code>return ListView.builder(
  itemCount: 3, // the data length of your list view
 itemBuilder: (context,index){
     _buildGridCards(context);
   }
</code>```

You may also check the flutter doc.
I hope it helps.

Body:
i would like to transform a GridView into a Listview, here is the Gridview code:

and here is what i tried to do :

      return ListView.builder(
 itemBuilder: (context,index){
     _buildGridCards(context);
   }

   );
  }

    List<dynamic> _buildGridCards(BuildContext context) {
   if (widget.productsToDisplay == null || widget.productsToDisplay.isEmpty) {
    return const <Card>[];
     }
   final ThemeData theme = Theme.of(context);
    return widget.productsToDisplay.map((product) {
    Uint8List img64;
    try {
    img64 = base64Decode(product.image);
    } catch (e) {
    print(e);
    }

  return Card(
    clipBehavior: Clip.antiAlias,
    child: InkWell(
      onTap: () {
        Navigator.push(
          context,
             ...

when i executed the code, nothing appeared

Body:
I believe you forgot itemCount, so the final will be

return ListView.builder(
  itemCount: 3, // the data length of your list view
 itemBuilder: (context,index){
     _buildGridCards(context);
   }

You may also check the flutter doc.
I hope it helps.


问:
Can't create handler inside thread that has not called Looper.prepare()
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

```<code>public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });
</code>```

StartPayment Method:

```<code>    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}
</code>```

答: I assume you create a Handler in startPayment() method. You can't do that, as handlers can be created on th UI thread only. Just create it in your activity class.</p>

Body:
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });

StartPayment Method:

    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}


问:
React not closing dialog box
Im using materialUI to click a menu item that then opens a dialog box(child component) however after the dialogbox opens it wont seem to close and wont update the data for noticeModal. There are not any errors being thrown and i belive it has to do with using useEffect to setNoticeModal(props.open) for the initial state. Ive tried removing the useEffect() and throwing props.open into the default useDate() for the noticeModal however upon doing that then my dialogbox wont open anymore at all. What am i over looking here?

holidaySettings.js

```<code>    ...
    const [dialogOpen, setDialogOpen] = React.useState(false);
    const handleDialogOpen = (dataElement) => {
      setDialogData(dataElement);
      setDialogOpen(true);
      setOpen(false);
    }

    ...
    <ClickAwayListener onClickAway={handleClose}>
       <MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
          <MenuItem onClick={handleDialogOpen}>Add Holiday</MenuItem>
        </MenuList>
     </ClickAwayListener>

    ...

    <div className="card-body">
      <div className="row">
         <div className="text-left col-12">
            <Styles>
               <Table columns={columns} data={data} />
               <HolidayDialog open={dialogOpen} onClose={handleDialogClose} data={dialogData}/>
            </Styles>
         </div>
       </div>
     </div>
    ...
</code>```

holidayDialog.js

```<code>const HolidayDialog = (props) => {
    const [noticeModal, setNoticeModal] = useState(false);
    const [selectedDate, setSelectedDate] = useState(new Date());
    const [holidayData, setHolidayData] = useState(props.data);

    useEffect(() => {
        setNoticeModal(props.open)
    });

    const handleDateChange = (date) => {
        setSelectedDate(date);
    };

    const handleClose = () => {
        setNoticeModal(false);
        console.log(noticeModal);
    };

    const handleChange = (e) => {
        const { name, checked } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: checked }));
      };

    const updateValues = (e) => {
        const { name, value } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: value }));
    }
    return (
        <Dialog
            open={noticeModal}
            TransitionComponent={Transition}
            keepMounted
            onClose={handleClose}
            aria-labelledby="notice-modal-slide-title"
            aria-describedby="notice-modal-slide-description"
        >
            <DialogTitle id="customized-dialog-title" onClose={handleClose}>
                {holidayData.HolidayName ? holidayData.HolidayName : 'Create New Holiday'}
            </DialogTitle>
            <DialogContent dividers>
                <form noValidate autoComplete="off">
                    <div className="row">
                        <div className="col">
                            <TextField required name="HolidayName" id="outlined-basic" label="Holiday Name" variant="outlined" onChange={updateValues} value={holidayData.HolidayName || ''}/>
                        </div>
                        <div className="col">
                            <TextField id="outlined-basic" name="Branch" label="Branch" variant="outlined" onChange={updateValues} value={holidayData.Branch || 'ALL'}/>
                        </div>
                    </div>
                    <div className="row mt-3">
                        <div className="col">
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDatePicker
                                disableToolbar
                                variant="inline"
                                format="MM/dd/yyyy"
                                margin="normal"
                                id="date-picker-inline"
                                label="Date picker inline"
                                value={selectedDate}
                                onChange={handleDateChange}
                                KeyboardButtonProps={{
                                    'aria-label': 'change date',
                                }}
                            />
                        </MuiPickersUtilsProvider>
                        </div>
                        <div className="col">
                            <TextField id="outlined-basic" name="Hours" label="Hours" variant="outlined" onChange={updateValues} value={holidayData.Hours || 'Closed'}/>
                        </div>
                    </div>
                    <div className="row mt-3">
                        <div className="col d-flex flex-column">
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Web || false}
                                    value={holidayData.Web}
                                    onChange={handleChange}
                                    name="Web"
                                    color="primary"
                                />
                                }
                                label="Show on Web?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.CoOp || false}
                                    value={holidayData.CoOp}
                                    onChange={handleChange}
                                    name="CoOp"
                                    color="primary"
                                />
                                }
                                label="CoOp Holiday?"
                            />
                        </div>
                        <div className="col d-flex flex-column">
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Phone || false}
                                    value={holidayData.Phone}
                                    onChange={handleChange}
                                    name="Phone"
                                    color="primary"
                                />
                                }
                                label="Use in IVR?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Active || true}
                                    value={holidayData.Active}
                                    onChange={handleChange}
                                    disabled
                                    name="Active"
                                    color="primary"
                                />
                                }
                                label="Active"
                            />
                        </div>
                    </div>
                </form>
            </DialogContent>
            <DialogActions>
                <Button autoFocus onClick={handleClose} color="default">
                    Cancel
                </Button>
                <Button autoFocus onClick={handleClose} color="primary">
                    Create Holiday
                </Button>
            </DialogActions>
        </Dialog>
    )
}

export default HolidayDialog;
</code>```

答:
You are not providing any dependency to useEffect so it runs on every re-render. In your useEffect you are toggling the modal and hence the issue.

useEffect(() => {
        setNoticeModal(props.open)
    });//<---- issue - missing dependency

```

<p>Solution - pass dependency as <code>props.open</code>. This makes the useEffect to run only when props.open is changed.</p>

<pre class="lang-js prettyprint-override"><code>useEffect(() => {
        setNoticeModal(props.open)
    }, [props.open]); //<----- props.open
</code>```

Title: React not closing dialog box

Body:
Im using materialUI to click a menu item that then opens a dialog box(child component) however after the dialogbox opens it wont seem to close and wont update the data for noticeModal. There are not any errors being thrown and i belive it has to do with using useEffect to setNoticeModal(props.open) for the initial state. Ive tried removing the useEffect() and throwing props.open into the default useDate() for the noticeModal however upon doing that then my dialogbox wont open anymore at all. What am i over looking here?

holidaySettings.js

    ...
    const [dialogOpen, setDialogOpen] = React.useState(false);
    const handleDialogOpen = (dataElement) => {
      setDialogData(dataElement);
      setDialogOpen(true);
      setOpen(false);
    }

    ...
    <ClickAwayListener onClickAway={handleClose}>
       <MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
          <MenuItem onClick={handleDialogOpen}>Add Holiday</MenuItem>
        </MenuList>
     </ClickAwayListener>

    ...

    ...

holidayDialog.js

const HolidayDialog = (props) => {
    const [noticeModal, setNoticeModal] = useState(false);
    const [selectedDate, setSelectedDate] = useState(new Date());
    const [holidayData, setHolidayData] = useState(props.data);

    useEffect(() => {
        setNoticeModal(props.open)
    });

    const handleDateChange = (date) => {
        setSelectedDate(date);
    };

    const handleClose = () => {
        setNoticeModal(false);
        console.log(noticeModal);
    };

    const handleChange = (e) => {
        const { name, checked } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: checked }));
      };

    const updateValues = (e) => {
        const { name, value } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: value }));
    }
    return (
        <Dialog
            open={noticeModal}
            TransitionComponent={Transition}
            keepMounted
            onClose={handleClose}
            aria-labelledby="notice-modal-slide-title"
            aria-describedby="notice-modal-slide-description"
        >
            <DialogTitle id="customized-dialog-title" onClose={handleClose}>
                {holidayData.HolidayName ? holidayData.HolidayName : 'Create New Holiday'}
            </DialogTitle>
            <DialogContent dividers>
                <form noValidate autoComplete="off">

                            <TextField required name="HolidayName" id="outlined-basic" label="Holiday Name" variant="outlined" onChange={updateValues} value={holidayData.HolidayName || ''}/>

                            <TextField id="outlined-basic" name="Branch" label="Branch" variant="outlined" onChange={updateValues} value={holidayData.Branch || 'ALL'}/>

                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDatePicker
                                disableToolbar
                                variant="inline"
                                format="MM/dd/yyyy"
                                margin="normal"
                                id="date-picker-inline"
                                label="Date picker inline"
                                value={selectedDate}
                                onChange={handleDateChange}
                                KeyboardButtonProps={{
                                    'aria-label': 'change date',
                                }}
                            />
                        </MuiPickersUtilsProvider>

                            <TextField id="outlined-basic" name="Hours" label="Hours" variant="outlined" onChange={updateValues} value={holidayData.Hours || 'Closed'}/>

                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Web || false}
                                    value={holidayData.Web}
                                    onChange={handleChange}
                                    name="Web"
                                    color="primary"
                                />
                                }
                                label="Show on Web?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.CoOp || false}
                                    value={holidayData.CoOp}
                                    onChange={handleChange}
                                    name="CoOp"
                                    color="primary"
                                />
                                }
                                label="CoOp Holiday?"
                            />

                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Phone || false}
                                    value={holidayData.Phone}
                                    onChange={handleChange}
                                    name="Phone"
                                    color="primary"
                                />
                                }
                                label="Use in IVR?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Active || true}
                                    value={holidayData.Active}
                                    onChange={handleChange}
                                    disabled
                                    name="Active"
                                    color="primary"
                                />
                                }
                                label="Active"
                            />

                </form>
            </DialogContent>
            <DialogActions>
                <Button autoFocus onClick={handleClose} color="default">
                    Cancel
                </Button>
                <Button autoFocus onClick={handleClose} color="primary">
                    Create Holiday
                </Button>
            </DialogActions>
        </Dialog>
    )
}

export default HolidayDialog;

Body:
You are not providing any dependency to useEffect so it runs on every re-render. In your useEffect you are toggling the modal and hence the issue.

useEffect(() => {
        setNoticeModal(props.open)
    });//<---- issue - missing dependency

Solution - pass dependency as props.open. This makes the useEffect to run only when props.open is changed.

useEffect(() => {
        setNoticeModal(props.open)
    }, [props.open]); //<----- props.open


问:
How to solve an equation y=ax^2+bx+c when x is unknown and y known
I have this equation:

y = -0.00248793*x^2+20.77173764*x-371.01805798

And I would like to obtain the result of the equation when I give "y" numbers,

edited explanation 2/06/20:
I want to add a vector as my "y", and receive an output of one vector also.

This problem is a biological one, in which I performed citokine bead array (CBA) and I stablished a reference curve which is sinusoidal.

after stablishing the degree of the equation making the following:

```<code>fitil6_1=lm(Standards$`IL6 median`~poly(concentration,1,raw=TRUE))
fitil6_2=lm(Standards$`IL6 median`~poly(concentration,2,raw=TRUE))
fitil6_3=lm(Standards$`IL6 median`~poly(concentration,3,raw=TRUE))
fitil6_4=lm(Standards$`IL6 median`~poly(concentration,4,raw=TRUE))

lines(concentration,predict(fitil6_1,data.frame(x=concentration)),col="red")
lines(concentration,predict(fitil6_2,data.frame(x=concentration)),col="green")
lines(concentration,predict(fitil6_3,data.frame(x=concentration)),col="blue")
lines(concentration,predict(fitil6_4,data.frame(x=concentration)),col="purple)
legend(20,40000,legend=c("de grau 1","de grau 2","de grau 3","de grau 4"),lty=1,col=c("red","green","blue","purple"))
</code>```

I have chosen the degree 2 formula as it fits better to my dots for this cytokine (and most cytokines in this study)

So when I make

```<code>coef(fitil6_2)

 (Intercept)        poly(concentration, 2, raw = TRUE)1  poly(concentration, 2, raw = TRUE)2
-8.262381e+02                              2.371377e+01                       -2.847135e-03
</code>```

I receive that output and then I am able to build the formula (in this case):

y=-2.847135e-03 *x^2+2.371377e+01*x-8.262381e+02

but as my independent value is what I know is pretty difficult to isolate x!
(end of the editing)

I have tried many things like making function(x,y) but when you specify this you need to give a number of y, so really I am litlle bit lost!

Thank you

答:
As @Dave2e said, you can solve this particular example by algebra.  But you might need a programmatic solution, or you might be using the quadratic as an easy example.  in which case...

Rewrite your problem as "what value of y satisfies -0.00248793*x^2+20.77173764*x-371.01805798 - y = 0?".

There are plenty of ways to find the zeroes of a function.  That's what you've turned your problem into.  Suppose your "known value of y" is 10...

```<code>f <- function(x, y) {
  -0.00248793*x^2+20.77173764*x-371.01805798 - y
}

answer <- stats::uniroot(f, interval=c(0, 50), y=10)

# Check we've got the right answer
f(answer$root, 10)
</code>```

Giving

```<code>[1] -1.186322e-10
</code>```

Using this method, you do need to find/guess a range within which the answer might lie.  That's the purpose of the interval=c(0.50) part of the call to uniroot.  You can read the online help for more information about the value returned by uniroot and things you might want to look out for.

Body:
I have this equation:

y = -0.00248793*x^2+20.77173764*x-371.01805798

And I would like to obtain the result of the equation when I give "y" numbers,

edited explanation 2/06/20:
I want to add a vector as my "y", and receive an output of one vector also.

This problem is a biological one, in which I performed citokine bead array (CBA) and I stablished a reference curve which is sinusoidal.

after stablishing the degree of the equation making the following:

fitil6_1=lm(Standards$`IL6 median`~poly(concentration,1,raw=TRUE))
fitil6_2=lm(Standards$`IL6 median`~poly(concentration,2,raw=TRUE))
fitil6_3=lm(Standards$`IL6 median`~poly(concentration,3,raw=TRUE))
fitil6_4=lm(Standards$`IL6 median`~poly(concentration,4,raw=TRUE))

lines(concentration,predict(fitil6_1,data.frame(x=concentration)),col="red")
lines(concentration,predict(fitil6_2,data.frame(x=concentration)),col="green")
lines(concentration,predict(fitil6_3,data.frame(x=concentration)),col="blue")
lines(concentration,predict(fitil6_4,data.frame(x=concentration)),col="purple)
legend(20,40000,legend=c("de grau 1","de grau 2","de grau 3","de grau 4"),lty=1,col=c("red","green","blue","purple"))

I have chosen the degree 2 formula as it fits better to my dots for this cytokine (and most cytokines in this study)

So when I make

coef(fitil6_2)

 (Intercept)        poly(concentration, 2, raw = TRUE)1  poly(concentration, 2, raw = TRUE)2
-8.262381e+02                              2.371377e+01                       -2.847135e-03

I receive that output and then I am able to build the formula (in this case):

y=-2.847135e-03 *x^2+2.371377e+01*x-8.262381e+02

but as my independent value is what I know is pretty difficult to isolate x!
(end of the editing)

I have tried many things like making function(x,y) but when you specify this you need to give a number of y, so really I am litlle bit lost!

Thank you

Body:
As @Dave2e said, you can solve this particular example by algebra.  But you might need a programmatic solution, or you might be using the quadratic as an easy example.  in which case...

Rewrite your problem as "what value of y satisfies -0.00248793*x^2+20.77173764*x-371.01805798 - y = 0?".

There are plenty of ways to find the zeroes of a function.  That's what you've turned your problem into.  Suppose your "known value of y" is 10...

f <- function(x, y) {
  -0.00248793*x^2+20.77173764*x-371.01805798 - y
}

answer <- stats::uniroot(f, interval=c(0, 50), y=10)

# Check we've got the right answer
f(answer$root, 10)

Giving

[1] -1.186322e-10

Using this method, you do need to find/guess a range within which the answer might lie.  That's the purpose of the interval=c(0.50) part of the call to uniroot.  You can read the online help for more information about the value returned by uniroot and things you might want to look out for.


问:
Replace some parts of string and update the column in STANDARD SQL
I've a year column in a table called 'Movie', some of the year values are not in the standard format(few of them are like 'I 1999', 'XV 199', etc.(space is common in those years)). So I wanted to remove ' ', 'X', 'V', 'I' and replace them with '' so that I can convert them to the standard format of the year.

I was able to do the replacing part by this command:

SELECT (REPLACE(REPLACE(REPLACE((REPLACE(year, ' ', '')),'X',''),'V',''),'I','')) FROM Movie

But I'm unable to update my column(Getting error, command not executed). Below is the command I tried.

```<code>UPDATE Movie
SET year = (REPLACE(REPLACE((REPLACE(year, ' ', '')),'X',''),'V',''),'I',''))
WHERE year LIKE '% %'
</code>```

Please let me know how can I update my 'year' column. Please note I can only use STANDARD SQL commands.

Update: Attached the screenshot of the error. I am executing the SQL commands using pandas.read_sql_query() method. All standard SQL commands works nicely. But error encountered in this case.please note I've removed extra parenthesis.

答:
You are overusing parentheses, so something does not match.

Use this:

```<code>SET year = REPLACE(REPLACE(REPLACE(REPLACE(year, ' ', ''), 'X', ''), 'V', ''), 'I', '')
</code>```

Body:
I've a year column in a table called 'Movie', some of the year values are not in the standard format(few of them are like 'I 1999', 'XV 199', etc.(space is common in those years)). So I wanted to remove ' ', 'X', 'V', 'I' and replace them with '' so that I can convert them to the standard format of the year.

I was able to do the replacing part by this command:

SELECT (REPLACE(REPLACE(REPLACE((REPLACE(year, ' ', '')),'X',''),'V',''),'I','')) FROM Movie

But I'm unable to update my column(Getting error, command not executed). Below is the command I tried.

UPDATE Movie
SET year = (REPLACE(REPLACE((REPLACE(year, ' ', '')),'X',''),'V',''),'I',''))
WHERE year LIKE '% %'

Please let me know how can I update my 'year' column. Please note I can only use STANDARD SQL commands.

Update: Attached the screenshot of the error. I am executing the SQL commands using pandas.read_sql_query() method. All standard SQL commands works nicely. But error encountered in this case.please note I've removed extra parenthesis.

Body:
You are overusing parentheses, so something does not match.

Use this:

SET year = REPLACE(REPLACE(REPLACE(REPLACE(year, ' ', ''), 'X', ''), 'V', ''), 'I', '')


答:
You can use window functions, then aggregation:

```<code>select
    state_id,
    sum(datediff(second, t_stamp, lead_t_stamp)) duration_second
from  (
    select
        t.*,
        lead(t_stamp) over(order by t_stamp) lead_t_stamp
    from mytable t
) t
where lead_t_stamp is not null
group by state_id
order by state_id
</code>```

This demo on DB Fiddle with your uample data returns:

```
state_id | duration_second
-------: | --------------:
       0 |             190
       2 |              40
       3 |              20
```

Title: SQL Server 2012 - Calculate time in state based on state change

Body:
I'm trying to calculate how long a machine was in a specific state then sum by hour. The state is only recorded on change so we can assume it was in the same state until changed.

I was trying to use partition, but I don't think that is the correct approach.

My table structure ordered desc:

+----------+-------------------------+
| state_id |         t_stamp         |
+----------+-------------------------+
|        0 | 2020-06-01 10:44:06.663 |
|        2 | 2020-06-01 10:43:56.660 |
|        0 | 2020-06-01 10:43:06.653 |
|        2 | 2020-06-01 10:42:56.653 |
|        0 | 2020-06-01 10:41:36.643 |
|        3 | 2020-06-01 10:41:26.640 |
|        0 | 2020-06-01 10:41:16.640 |
|        2 | 2020-06-01 10:40:56.637 |
|        0 | 2020-06-01 10:40:06.630 |
|        3 | 2020-06-01 10:39:56.630 |
+----------+-------------------------+

What I'm trying to get to:

+----------+------------------+
| state_id | duration_seconds |
+----------+------------------+
|        2 |               10 |
|        0 |               50 |
+----------+------------------+

Body:
You can use window functions, then aggregation:

select
    state_id,
    sum(datediff(second, t_stamp, lead_t_stamp)) duration_second
from  (
    select
        t.*,
        lead(t_stamp) over(order by t_stamp) lead_t_stamp
    from mytable t
) t
where lead_t_stamp is not null
group by state_id
order by state_id

This demo on DB Fiddle with your uample data returns:

state_id | duration_second
-------: | --------------:
       0 |             190
       2 |              40
       3 |              20


问:
Flutter data to Json
How can I transfer QuerySnapshot object data from Firebase to JSON string?

Do I need to use

```<code> json.decode(qs)?
</code>```

Thank you

答:
1, Recommend you to use pkg: json_annotation to define model.

https://flutter.dev/docs/development/data-and-backend/json

2, When define model, let using bellow annotation for your model :

```<code>import 'package:json_annotation/json_annotation.dart';
part 'agent.g.dart';

@JsonSerializable(
    anyMap: true
)
class Agent {

  @JsonKey(
    ignore: true
  )
  String id;

  String name;

  String avatar;

  String email;

  String phone;

  String team;

  String password;

  Agent(this.name, this.avatar, this.email, this.phone, this.team, this.password);

  factory Agent.fromJson(Map<String, dynamic> json) => _$AgentFromJson(json);

  Map<String, dynamic> toJson() => _$AgentToJson(this);
}
</code>```

3, Parser model with documentSnapshot:

```<code>Agent.fromJson(documentSnapshot.data)
</code>```

Title: Flutter data to Json

Body:
How can I transfer QuerySnapshot object data from Firebase to JSON string?

Do I need to use

 json.decode(qs)?

Thank you

Body:
1, Recommend you to use pkg: json_annotation to define model.

https://flutter.dev/docs/development/data-and-backend/json

2, When define model, let using bellow annotation for your model :

import 'package:json_annotation/json_annotation.dart';
part 'agent.g.dart';

@JsonSerializable(
    anyMap: true
)
class Agent {

  @JsonKey(
    ignore: true
  )
  String id;

  String name;

  String avatar;

  String email;

  String phone;

  String team;

  String password;

  Agent(this.name, this.avatar, this.email, this.phone, this.team, this.password);

  factory Agent.fromJson(Map<String, dynamic> json) => _$AgentFromJson(json);

  Map<String, dynamic> toJson() => _$AgentToJson(this);
}

3, Parser model with documentSnapshot:

Agent.fromJson(documentSnapshot.data)


问:
Best way to test FileNotFound handling
I'm relatively new to testing and still getting my head around some of the fundamentals. I have a method that I would like to test which basically creates a different file name if the supplied already exists (I've pasted the code below).

I need a way of testing that the method returns a different (but also unique) name if the file already exists. What's the best way of testing this within Visual Studio's unit testing? Is it to create a file as part of the test and then delete it or is there a better way?

```<code>public static FileInfo SafeFileName(this FileInfo value)
{
    if (value == null) throw new ArgumentNullException("value");

    FileInfo fi = value;

    //Check the directory exists -if it doesn't create it as we won't move out of this dir
    if (!fi.Directory.Exists)
        fi.Directory.Create();

    //It does so create a new name
    int counter = 1;
    string pathStub = Path.Combine(fi.Directory.FullName, fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));

    // Keep renaming it until we have a safe filename
    while (fi.Exists)
        fi = new FileInfo(String.Concat(pathStub, "_", counter++, fi.Extension));

    return fi;
}
</code>```

答:
I think a better would be to use the .Net runtime:

```<code> System.IO.Path.GetRandomFileName()
</code>```

and get rid of the file name generation code all together.

GetRandomFileName

Title: Best way to test FileNotFound handling

Body:
I'm relatively new to testing and still getting my head around some of the fundamentals. I have a method that I would like to test which basically creates a different file name if the supplied already exists (I've pasted the code below).

I need a way of testing that the method returns a different (but also unique) name if the file already exists. What's the best way of testing this within Visual Studio's unit testing? Is it to create a file as part of the test and then delete it or is there a better way?

public static FileInfo SafeFileName(this FileInfo value)
{
    if (value == null) throw new ArgumentNullException("value");

    FileInfo fi = value;

    //Check the directory exists -if it doesn't create it as we won't move out of this dir
    if (!fi.Directory.Exists)
        fi.Directory.Create();

    //It does so create a new name
    int counter = 1;
    string pathStub = Path.Combine(fi.Directory.FullName, fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));

    // Keep renaming it until we have a safe filename
    while (fi.Exists)
        fi = new FileInfo(String.Concat(pathStub, "_", counter++, fi.Extension));

    return fi;
}

Body:
I think a better would be to use the .Net runtime:

 System.IO.Path.GetRandomFileName()

and get rid of the file name generation code all together.

GetRandomFileName


问:
EF Core: The instance of entity type cannot be tracked because another instance with the same key value
Assume we have the two following database tables:

```<code>Foo:
> FooId (PK)
> FooName

Bar:
> BarId (PK, FK)
> Comment
> Other columns...
</code>```

I have the following EF mapping:

```<code>[Table("Foo")]
public class Foo
{
    [Key]
    public long FooId { get; set; }

    public string FooName { get; set; }

    // (0-n) relation
    // public List<Bar> Bars { get; set; }
}

[Table("Bar")]
public class Bar
{
    // PK/FK
    [Key, ForeignKey("Foo")]
    public long BarId { get; set; }

    public string Comment { get; set; }
}
</code>```

The entity "Bar" has only a foreign key as primary key.
Whenever I try to insert new Bar entities like this:

```<code>var demoList = new List<Bar>();
// Populate demoList with random data
_context.Bars.AddRange(demoList);
_context.SaveChanges();
</code>```

I'm getting this exception:

```<code>'The instance of entity type 'Bar' cannot be tracked because another instance with the same key value for {'BarId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
</code>```

EF is considering that "BarId" must be unique as the property is marked as "Key", but it's a PK/FK in a one to many relation ("Foo" can have 0 or many "Bar"), what I'm missing here please?

答:
If Foo can have Zero or Many Bars it is a One-To-Many relationship. You would typically create a key as both PrimaryKey and ForiegnKey if the relationship is One-to-Zero-or-One. So per your requirement you models should be more like below:

```<code>[Table("Foo")]
public class Foo
{
    [Key]
    public long FooId { get; set; }

    public string FooName { get; set; }

    public virtual List<Bar> Bars { get; set; }
}

[Table("Bar")]
public class Bar
{

    [Key]
    public long BarId { get; set; }

    public long FooId { get; set; }

    [ForeignKey("FooId")]
    public virtual Foo Foo { get; set; }

    public string Comment { get; set; }
}
</code>```

Body:
Assume we have the two following database tables:

Foo:
> FooId (PK)
> FooName

Bar:
> BarId (PK, FK)
> Comment
> Other columns...

I have the following EF mapping:

[Table("Foo")]
public class Foo
{
    [Key]
    public long FooId { get; set; }

    public string FooName { get; set; }

    // (0-n) relation
    // public List<Bar> Bars { get; set; }
}

[Table("Bar")]
public class Bar
{
    // PK/FK
    [Key, ForeignKey("Foo")]
    public long BarId { get; set; }

    public string Comment { get; set; }
}

The entity "Bar" has only a foreign key as primary key.
Whenever I try to insert new Bar entities like this:

var demoList = new List<Bar>();
// Populate demoList with random data
_context.Bars.AddRange(demoList);
_context.SaveChanges();

I'm getting this exception:

'The instance of entity type 'Bar' cannot be tracked because another instance with the same key value for {'BarId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'

EF is considering that "BarId" must be unique as the property is marked as "Key", but it's a PK/FK in a one to many relation ("Foo" can have 0 or many "Bar"), what I'm missing here please?

Body:
If Foo can have Zero or Many Bars it is a One-To-Many relationship. You would typically create a key as both PrimaryKey and ForiegnKey if the relationship is One-to-Zero-or-One. So per your requirement you models should be more like below:

[Table("Foo")]
public class Foo
{
    [Key]
    public long FooId { get; set; }

    public string FooName { get; set; }

    public virtual List<Bar> Bars { get; set; }
}

[Table("Bar")]
public class Bar
{

    [Key]
    public long BarId { get; set; }

    public long FooId { get; set; }

    [ForeignKey("FooId")]
    public virtual Foo Foo { get; set; }

    public string Comment { get; set; }
}


问:
Add a custom column in django database
Iam little new to Django and Iam struggling to add column in Django Database.

I was working to create a subcategory for products, but the I want those subcategories to be predefined. That is for example "Fashion" category could have subcategory of 'Men', 'Women', 'Kids'.

I want a table in DB of these subcategories, without having the user or admin panel option to manipulate these field. User can only select article belong to which subcategory.

I go through a few documentation, but could understood much:
1. https://docs.djangoproject.com/en/3.0/howto/custom-model-fields/
2. Adding fields to an already existing database for Django (version < 1.7)

Please suggest me how to add these predefined table values.

答:
Create subcategories model and model admin then in model admin you can disable change permission like this

Subcategories admin model

```<code>def has_change_permission(self, request, obj=None):
    return False
</code>```

Now you can add,delete and view only permission. User and admin can't change them.

Title: Add a custom column in django database

Body:
Create subcategories model and model admin then in model admin you can disable change permission like this

Subcategories admin model

def has_change_permission(self, request, obj=None):
    return False

Now you can add,delete and view only permission. User and admin can't change them.


问:
Conceptual example of State Design Pattern in C#
I am currently studying the state Design Pattern and I think I pretty clear about how it works. I was looking at a conceptual example which I have posted below. There is just one part of the code that I don't quite understand.

```<code>using System;

namespace BranchingDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.ReadLine();
        }

    }
    // State Interface
    interface IAccountState
    {
        IAccountState Deposit(Action addToBalance);
        IAccountState Withdraw(Action subtractFromBalance);
        IAccountState Freeze();
        IAccountState HolderVerified();
        IAccountState Close();
    }

    //Context
    class Account
    {
        public decimal Balance { get; private set; }

        private IAccountState State { get; set; }

        public Account(Action onUnfreeze)
        {
            this.State = new NotVerified(onUnfreeze);
        }

        public void Deposit(decimal amount)
        {
            this.State = this.State.Deposit(() => { this.Balance += amount; });
        }

        public void Withdraw(decimal amount)
        {
            this.State = this.State.Withdraw(() => { this.Balance -= amount; });
        }

        public void HolderVerified()
        {
            this.State = this.State.HolderVerified();
        }

        public void Close()
        {
            this.State = this.State.Close();
        }

        public void Freeze()
        {
            this.State = this.State.Freeze();
        }

    }
    //Concrete State
    class Active : IAccountState
    {
        private Action OnUnfreeze { get; }

        public Active(Action onUnfreeze)
        {
            this.OnUnfreeze = onUnfreeze;
        }

        public IAccountState Deposit(Action addToBalance)
        {
            addToBalance();
            return this;
        }

        public IAccountState Withdraw(Action subtractFromBalance)
        {
            subtractFromBalance();
            return this;
        }

        public IAccountState Freeze() => new Frozen(this.OnUnfreeze);
        public IAccountState HolderVerified() => this;
        public IAccountState Close() => new Closed();
    }

    //Concrete State

    class Closed : IAccountState
    {
        public IAccountState Deposit(Action addToBalance) => this;
        public IAccountState Withdraw(Action subtractFromBalance) => this;
        public IAccountState Freeze() => this;
        public IAccountState HolderVerified() => this;
        public IAccountState Close() => this;
    }
}
</code>```

In the concrete class Active there is  property of type action delegate which is passed as a parameter in its constructor. Also in the constructor of the context class a delegate of type action is passed as a parameter. Now conceptually I understand this is done as this provides a backreference to the Context object (Account),with the State i.e. closed or Active. This backreference can be used by States to transition the Context to another State.
My first question is why a delegate was used?

However I was trying to get the code to run and debug to illustrate what was happening. Therefore my question is in the code  how do I need initialize a new Account? Accounts begin with a NotVerified state.  I tried this code.

```<code>Action initialState = () => { };
            Account account= new Account(initialState);
</code>```

If I then want to determine the state of the account how do I code that?

答:
I managed to get the State details by making the State attribute in the Account class public. Then in the program class I could execute the following:

```<code>Action initialState = () => { };
Account testAccount= new Account(initialState,0);
var currentState = testAccount.State;
Console.WriteLine(currentState.GetType().Name);
testAccount.HolderVerified();
currentState = testAccount.State;
Console.WriteLine(currentState.GetType().Name);
testAccount.Deposit(12);
currentState = testAccount.State;
Console.WriteLine(currentState.GetType().Name + $" Balance: {testAccount.Balance}");
testAccount.Close();
currentState = testAccount.State;
Console.WriteLine(currentState.GetType().Name);
Console.ReadLine();
</code>```

I also changed the Account constructor to take and initial amount for the balance.

Body:
I am currently studying the state Design Pattern and I think I pretty clear about how it works. I was looking at a conceptual example which I have posted below. There is just one part of the code that I don't quite understand.

using System;

namespace BranchingDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.ReadLine();
        }

    }
    // State Interface
    interface IAccountState
    {
        IAccountState Deposit(Action addToBalance);
        IAccountState Withdraw(Action subtractFromBalance);
        IAccountState Freeze();
        IAccountState HolderVerified();
        IAccountState Close();
    }

    //Context
    class Account
    {
        public decimal Balance { get; private set; }

        private IAccountState State { get; set; }

        public Account(Action onUnfreeze)
        {
            this.State = new NotVerified(onUnfreeze);
        }

        public void Deposit(decimal amount)
        {
            this.State = this.State.Deposit(() => { this.Balance += amount; });
        }

        public void Withdraw(decimal amount)
        {
            this.State = this.State.Withdraw(() => { this.Balance -= amount; });
        }

        public void HolderVerified()
        {
            this.State = this.State.HolderVerified();
        }

        public void Close()
        {
            this.State = this.State.Close();
        }

        public void Freeze()
        {
            this.State = this.State.Freeze();
        }

    }
    //Concrete State
    class Active : IAccountState
    {
        private Action OnUnfreeze { get; }

        public Active(Action onUnfreeze)
        {
            this.OnUnfreeze = onUnfreeze;
        }

        public IAccountState Deposit(Action addToBalance)
        {
            addToBalance();
            return this;
        }

        public IAccountState Withdraw(Action subtractFromBalance)
        {
            subtractFromBalance();
            return this;
        }

        public IAccountState Freeze() => new Frozen(this.OnUnfreeze);
        public IAccountState HolderVerified() => this;
        public IAccountState Close() => new Closed();
    }

    //Concrete State

    class Closed : IAccountState
    {
        public IAccountState Deposit(Action addToBalance) => this;
        public IAccountState Withdraw(Action subtractFromBalance) => this;
        public IAccountState Freeze() => this;
        public IAccountState HolderVerified() => this;
        public IAccountState Close() => this;
    }
}

In the concrete class Active there is  property of type action delegate which is passed as a parameter in its constructor. Also in the constructor of the context class a delegate of type action is passed as a parameter. Now conceptually I understand this is done as this provides a backreference to the Context object (Account),with the State i.e. closed or Active. This backreference can be used by States to transition the Context to another State.
My first question is why a delegate was used?

However I was trying to get the code to run and debug to illustrate what was happening. Therefore my question is in the code  how do I need initialize a new Account? Accounts begin with a NotVerified state.  I tried this code.

Action initialState = () => { };
            Account account= new Account(initialState);

If I then want to determine the state of the account how do I code that?

Body:
I managed to get the State details by making the State attribute in the Account class public. Then in the program class I could execute the following:

Action initialState = () => { };
Account testAccount= new Account(initialState,0);
var currentState = testAccount.State;
Console.WriteLine(currentState.GetType().Name);
testAccount.HolderVerified();
currentState = testAccount.State;
Console.WriteLine(currentState.GetType().Name);
testAccount.Deposit(12);
currentState = testAccount.State;
Console.WriteLine(currentState.GetType().Name + $" Balance: {testAccount.Balance}");
testAccount.Close();
currentState = testAccount.State;
Console.WriteLine(currentState.GetType().Name);
Console.ReadLine();

I also changed the Account constructor to take and initial amount for the balance.


问:
undefined C struct forward declaration
I have a header file port.h, port.c, and my main.c

I get the following error: 'ports' uses undefined struct 'port_t'

I thought as I have declared the struct in my .h file and having the actual structure in the .c file was ok.

I need to have the forward declaration as I want to hide some data in my port.c file.

In my port.h I have the following:

```<code>/* port.h */
struct port_t;
</code>```

port.c:

```<code>/* port.c */
#include "port.h"
struct port_t
{
    unsigned int port_id;
    char name;
};
</code>```

main.c:

```<code>/* main.c */
#include <stdio.h>
#include "port.h"

int main(void)
{
struct port_t ports;

return 0;
}
</code>```

Many thanks for any suggestions,

答: Unfortunately, the compiler needs to know the size of port_t (in bytes) while compiling main.c, so you need the full type definition in the header file.

OwnerDisplayName: robUK

ContentLicense: CC BY-SA 2.5

Title: undefined C struct forward declaration

Body:
I have a header file port.h, port.c, and my main.c

I get the following error: 'ports' uses undefined struct 'port_t'

I thought as I have declared the struct in my .h file and having the actual structure in the .c file was ok.

I need to have the forward declaration as I want to hide some data in my port.c file.

In my port.h I have the following:

/* port.h */
struct port_t;

port.c:

/* port.c */
#include "port.h"
struct port_t
{
    unsigned int port_id;
    char name;
};

main.c:

/* main.c */
#include <stdio.h>
#include "port.h"

int main(void)
{
struct port_t ports;

return 0;
}

Many thanks for any suggestions,

LastEditorDisplayName: Chris Young

OwnerDisplayName: Matthew

LastEditorDisplayName: Matthew


问:
notifydatasetchanged not working after app close?
My code is as follows. I have a couple of classes and when someone want to update it doesn't work.what could be the problem?
I checked it a lot and the application closes = arrayAdapter.notifyDataSetChanged();

```<code>public class CardArrayAdapter extends ArrayAdapter<Card> {

    public CardArrayAdapter(Context context, int resource,List<Card> objects) {
        super(context, resource, objects);
    }

    @NonNull
    @Override
    public View getView(int position,View convertView, ViewGroup parent) {
       Card card = getItem(position);
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.item,parent,false);
        TextView textView = convertView.findViewById(R.id.ItemTextView);
        ImageView imageView = convertView.findViewById(R.id.ItemImageView);
        textView.setText(card.name);
        Glide.with(getContext()).load(card.photoURL).into(imageView);
        return convertView;
    }
}
</code>```

Main class

```<code>ArrayList<Card> list;
CardArrayAdapter arrayAdapter;
public void loadsCards(){
        list=new ArrayList<Card>();
         String name = dataSnapshot.child("name").getValue().toString();
                                    String photoURL = dataSnapshot.child("photo").getValue().toString();
                                    String uid = dataSnapshot.getKey();
                                    Card card = new Card(uid,photoURL,name);
                                    Toast.makeText(getActivity(), "sonuc:"+card.name, Toast.LENGTH_LONG).show();
                                   list.add(card);
                       arrayAdapter.notifyDataSetChanged(); //closes here
                                  }
</code>```

答:
//I solved the problem.
list=new ArrayList<Card>();
//adding code
arrayAdapter=new CardArrayAdapter(this.getContext(),list.size(),list);

Body:
My code is as follows. I have a couple of classes and when someone want to update it doesn't work.what could be the problem?
I checked it a lot and the application closes = arrayAdapter.notifyDataSetChanged();

public class CardArrayAdapter extends ArrayAdapter<Card> {

    public CardArrayAdapter(Context context, int resource,List<Card> objects) {
        super(context, resource, objects);
    }

    @NonNull
    @Override
    public View getView(int position,View convertView, ViewGroup parent) {
       Card card = getItem(position);
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.item,parent,false);
        TextView textView = convertView.findViewById(R.id.ItemTextView);
        ImageView imageView = convertView.findViewById(R.id.ItemImageView);
        textView.setText(card.name);
        Glide.with(getContext()).load(card.photoURL).into(imageView);
        return convertView;
    }
}

Main class

ArrayList<Card> list;
CardArrayAdapter arrayAdapter;
public void loadsCards(){
        list=new ArrayList<Card>();
         String name = dataSnapshot.child("name").getValue().toString();
                                    String photoURL = dataSnapshot.child("photo").getValue().toString();
                                    String uid = dataSnapshot.getKey();
                                    Card card = new Card(uid,photoURL,name);
                                    Toast.makeText(getActivity(), "sonuc:"+card.name, Toast.LENGTH_LONG).show();
                                   list.add(card);
                       arrayAdapter.notifyDataSetChanged(); //closes here
                                  }


问:
Get Selected Value from Table using JQuery
I am using below code for getting check value from table which is printing all checked checkbox value.But i want to get only selected checkbox value not all checked value.

```<code>function clickedBoxAdd(checkBoxvalue) {
    var values = new Array();
    $.each($("input[name='" + checkBoxvalue + "']:checked").closest("td").next("td").next("td"),
           function () {
                values.push($(this).text());
           });
           alert(values);
           addVariablesRow1()

}

</code>```

For adding table row if i click checkbox using below code which is working.Can anyone please help how to delete rows as well when i unselect checkboxes.

```<code>function addVariablesRow1() {
            var $t = $("#addTable");
            var $row = $($t.find("tr")[1]);
            var r = $row.clone();
            r.find("input[type=text]").val("")
            r.find("input[type=checkbox]").attr('checked',  false)
            r[0].style.display = "";
            r.appendTo($t);
}

</code>```

HTML

```<code> <input type="checkbox" class="checkBox" name="checkBox_B[]" onclick="clickedBoxAdd(this.name)">

</code>```

Table

```<code>
        <table id="addTable" class="table table-bordered">
        <thead>
                <tbody class="snmp_oid_table">

        <tr class="info">
          <th>Oid</th>
          <th>Data Type</th>
          <th>Set Value</th>
        </tr>
        </thead>
  <tr style="display:none">

            <td>
              <input type="text" class="name" id="oids" name="oid">
            </td>

            <td>
              <input type="text" class="text" name="oid_description">
            </td>
            <td>
              <input type="text" class="expectedValue" name="expected_value">
            </td>
</tr>
          </tbody>
      </table>

</code>```

CheckBox

```<code>         <table id="addOidTable" class="table table-bordered">
           <thead>
         <tr class="info">
           <th style="width: 10px;">
           <input type="checkbox" id="checkBox_add_b[]" onclick="selectAddAll(this)"/>SA</th>
           <th>name</th>
           <th>Oid </th>
         </tr>
       </thead>
         <tbody class="oid_table">
             <% @all_b_oids.each do |oids| %>
                <tr id="tr_snmp_<%=oids['id'] %>">
                   <td>
                     <input type="checkbox" class="checkBox" name="checkBox_Oid_B[]" onclick="clickedBoxAddAll(this.name)">
                   </td>
                   <td style="word-break:break-all;">
                      <%= oids['name']%>
                    </td>
                     <td style="word-break:break-all;">
                         <%= oids['oid']%>
                     </td>
                 </tr>
                 <% end %>
           </tbody>
         </table>
</code>```

答:
You are actually getting all checkbox's values and pushing those in arrays by using '$.each'

Anyway, for the first part of your question, your checkbox should have a class e.g. chkbox, then you can get it's value in it's click handler:

```<code> $(".chkbox").click(function() {
$(this).closest('td').html()
});
</code>```

To delete a row from table, assign id to each tr once you create it:

```<code>r.attr("id", "rowid");
</code>```

Then once checkbox is unselected, you can remove row in checkbox's click handler:

```<code> $(".chkbox").click(function() {
    if(!$(this).is(':checked')) {
       $('#rowid').remove();

    }
 });
</code>```

Hope this helps.

Body:
I am using below code for getting check value from table which is printing all checked checkbox value.But i want to get only selected checkbox value not all checked value.

function clickedBoxAdd(checkBoxvalue) {
    var values = new Array();
    $.each($("input[name='" + checkBoxvalue + "']:checked").closest("td").next("td").next("td"),
           function () {
                values.push($(this).text());
           });
           alert(values);
           addVariablesRow1()

}

For adding table row if i click checkbox using below code which is working.Can anyone please help how to delete rows as well when i unselect checkboxes.

function addVariablesRow1() {
            var $t = $("#addTable");
            var $row = $($t.find("tr")[1]);
            var r = $row.clone();
            r.find("input[type=text]").val("")
            r.find("input[type=checkbox]").attr('checked',  false)
            r[0].style.display = "";
            r.appendTo($t);
}

HTML

 <input type="checkbox" class="checkBox" name="checkBox_B[]" onclick="clickedBoxAdd(this.name)">

Table

          Oid
          Data Type
          Set Value

              <input type="text" class="name" id="oids" name="oid">

              <input type="text" class="text" name="oid_description">

              <input type="text" class="expectedValue" name="expected_value">

CheckBox

           <input type="checkbox" id="checkBox_add_b[]" onclick="selectAddAll(this)"/>SA
           name
           Oid

             <% @all_b_oids.each do |oids| %>
                <tr id="tr_snmp_<%=oids['id'] %>">

                     <input type="checkbox" class="checkBox" name="checkBox_Oid_B[]" onclick="clickedBoxAddAll(this.name)">

                      <%= oids['name']%>

                         <%= oids['oid']%>

                 <% end %>

Body:
You are actually getting all checkbox's values and pushing those in arrays by using '$.each'

Anyway, for the first part of your question, your checkbox should have a class e.g. chkbox, then you can get it's value in it's click handler:

 $(".chkbox").click(function() {
$(this).closest('td').html()
});

To delete a row from table, assign id to each tr once you create it:

r.attr("id", "rowid");

Then once checkbox is unselected, you can remove row in checkbox's click handler:

 $(".chkbox").click(function() {
    if(!$(this).is(':checked')) {
       $('#rowid').remove();

    }
 });

Hope this helps.


问:
File Compare between files
I am planning to build a script for pre & post health check of my JVM & filesystem for that
I want to compare 2 files pre.txt & post.txt and want to ignore what are the common lines in file1 and file2 display only what are the lines exist in pre.txt apart from common as a file final.txt .

useing comm command but not working
Ex:--

pre.txt

```<code>Filesystem      Size  Used Avail Use% Mounted on
udev            966M     0  966M   0% /dev
tmpfs           200M  1.2M  199M   1% /run
/dev/sda2        20G  6.1G   13G  33% /
tmpfs           997M     0  997M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           997M     0  997M   0% /sys/fs/cgroup
/dev/loop1       90M   90M     0 100% /snap/core/8268
/dev/loop2       94M   94M     0 100% /snap/core/9066
tmpfs           200M     0  200M   0% /run/user/1000
</code>```

post.txt

```<code>/dev/loop1       90M   90M     0 100% /snap/core/8268
/dev/loop2       94M   94M     0 100% /snap/core/9066
</code>```

final.txt

```<code>Filesystem      Size  Used Avail Use% Mounted on
udev            966M     0  966M   0% /dev
tmpfs           200M  1.2M  199M   1% /run
/dev/sda2        20G  6.1G   13G  33% /
tmpfs           997M     0  997M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           997M     0  997M   0% /sys/fs/cgroup
tmpfs           200M     0  200M   0% /run/user/1000
</code>```

答:
You can use grep to exclude the lines from post.txt:

```<code>$ grep -vxFf post.txt pre.txt
Filesystem      Size  Used Avail Use% Mounted on
udev            966M     0  966M   0% /dev
tmpfs           200M  1.2M  199M   1% /run
/dev/sda2        20G  6.1G   13G  33% /
tmpfs           997M     0  997M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           997M     0  997M   0% /sys/fs/cgroup
tmpfs           200M     0  200M   0% /run/user/1000
</code>```

-v: inverts grep's matching behavior to exclude matching lines

-x: only match whole lines

-F: interpret the patterns as literal strings rather than regular expressions

-f: specifies a file (post.txt) containing the patterns to match

Title: File Compare between files

Body:
I am planning to build a script for pre & post health check of my JVM & filesystem for that
I want to compare 2 files pre.txt & post.txt and want to ignore what are the common lines in file1 and file2 display only what are the lines exist in pre.txt apart from common as a file final.txt .

useing comm command but not working
Ex:--

pre.txt

Filesystem      Size  Used Avail Use% Mounted on
udev            966M     0  966M   0% /dev
tmpfs           200M  1.2M  199M   1% /run
/dev/sda2        20G  6.1G   13G  33% /
tmpfs           997M     0  997M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           997M     0  997M   0% /sys/fs/cgroup
/dev/loop1       90M   90M     0 100% /snap/core/8268
/dev/loop2       94M   94M     0 100% /snap/core/9066
tmpfs           200M     0  200M   0% /run/user/1000

post.txt

/dev/loop1       90M   90M     0 100% /snap/core/8268
/dev/loop2       94M   94M     0 100% /snap/core/9066

final.txt

Filesystem      Size  Used Avail Use% Mounted on
udev            966M     0  966M   0% /dev
tmpfs           200M  1.2M  199M   1% /run
/dev/sda2        20G  6.1G   13G  33% /
tmpfs           997M     0  997M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           997M     0  997M   0% /sys/fs/cgroup
tmpfs           200M     0  200M   0% /run/user/1000

Body:
You can use grep to exclude the lines from post.txt:

$ grep -vxFf post.txt pre.txt
Filesystem      Size  Used Avail Use% Mounted on
udev            966M     0  966M   0% /dev
tmpfs           200M  1.2M  199M   1% /run
/dev/sda2        20G  6.1G   13G  33% /
tmpfs           997M     0  997M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           997M     0  997M   0% /sys/fs/cgroup
tmpfs           200M     0  200M   0% /run/user/1000

-v: inverts grep's matching behavior to exclude matching lines

-x: only match whole lines

-F: interpret the patterns as literal strings rather than regular expressions

-f: specifies a file (post.txt) containing the patterns to match