问:
Input from datepicker breaks inputs from dropdown lists
I created a filter for a table, which worked just fine at first, but as soon as I replaced the input form of the date with a datepicker I noticed that only the filter that involves the date works and the other are ignored and I can't see any reason why it behaves like this.

This is the part that creates the dropdown lists for the filter options:

```<code>        echo "<form action='listTimes.php' method='post'>

    <table>
    <caption><b>Filter By:</b></caption>
        <tr>
            <th>Task Name</th>
            <th>Task Stage</th>
            <th>Name</th>
            <th>Date</th>
        </tr>
        <tr>
            <td>";
        // first filter option - dropdown
        $sql = "SELECT DISTINCT taskName FROM tasks";
        $result = mysqli_query($link, $sql);
            echo "<select name='taskName'>";
            echo "<option selected='selected' value='' disabled='disabled'></option>";
            while ($row = mysqli_fetch_array($result)) {
            if (isset($row['taskName'])) {
            echo "<option value='" . $row['taskName'] . "'>" . $row['taskName'] . "</option>";
                }
            }
    echo "</select>
            </td>
            <td>";
            // second filter option - dropdown
            $sql = "SELECT DISTINCT taskStage FROM taskattributes";
            $result = mysqli_query($link, $sql);

            echo "<select name='taskStage'>
            <option selected='selected' value='' disabled='disabled'></option>";
            while ($row = mysqli_fetch_array($result)) {
            if (isset($row['taskStage'])) {
                echo "<option value='" . $row['taskStage'] . "'>" . $row['taskStage'] . "</option>";
                }
            }
            echo "</select>

            </td>
            <td>";
            // third filter option - dropdown
            $sql = "SELECT DISTINCT userName FROM users";
            $result = mysqli_query($link, $sql);

            echo "<select name='userName'>";
            echo "<option selected='selected' value='' disabled='disabled'></option>";
            while ($row = mysqli_fetch_array($result)) {
            if (isset($row['userName'])) {
                echo "<option value='" . $row['userName'] . "'>" . $row['userName'] . "</option>";
                }
            }
         /* fourth filter option, was just a simple text input at first. Now I changed it to a datepicker, which works, but the other three filter options stopped working at this point */
      echo "</select>
            </td>
            <td>

            <input type='text' class='datepicker' name='entryDate'>

            </td>
        </tr>
    </table>

   <div align='center'>  <input type='submit' value='Filter'></div>
    </form>
</code>```

The filter mechanism behind is very poorly written, but works just fine:

```<code>    if(!isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $sql = "SELECT * FROM timeEntry";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage' AND userName='$userName'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage' AND userName='$userName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
}
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage' AND userName='$userName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE userName='$userName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage'AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND userName='$userName'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND userName='$userName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $sql = "SELECT * FROM timeEntry WHERE userName='$userName'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage' AND userName='$userName'";
    $result = $link->query($sql);
    }

echo "<table class='top1' border='1'>

<tr>
<th>Entry No.</th>
<th>Task/Activity</th>
<th>Task Stage</th>
<th>User Name</th>
<th>Time Spent</th>
<th>Date</th>
<th>Edit Entry</th>
<th>Delete Entry</th>
</tr>";

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr>
        <td align='center'>"  . $row['timeId'] . "
        </td>";
        echo "<td>" . $row['taskName'] . "</td>";
        echo "<td>" . $row['taskStage'] . "</td>";
        echo "<td>" . $row['userName'] . "</td>";
        echo "<td align='center'>" . $row['timeSpent'] . "</td>";
        $originaldate = mysqli_real_escape_string($link, $row['entryDate']);
        $newdate = date("d/m/Y", strtotime($row['entryDate']));
        echo "<td align='center'>" . $newdate . "</td>";
        echo "<td align='center'><a href='editAllTimes.php?timeId=" . $row["timeId"] . "'>Edit</a></td>";
        echo "<td align='center'><a href='deleteAllTime.php?timeId=" . $row["timeId"] . "' onclick='return checkDelete()'>Delete</a></td>
        </tr>";
    }
    echo "</table>";
}
</code>```

This piece of code as bad as it looks, worked just fine before adding the date picker:

```<code><input type='text' class='datepicker' name='entryDate'>
</code>```

I have noticed a strange behavior:

If I delete the name attribute name='entryDate' the other filters work and the datepicker also, but the date is not recorded when I press filter and in consequence the date filter doesn't work.

If I leave the name attribute name='entryDate', the other three filters stop working, and only the date filter works.

Is there any reason for this behaviour? and any solution ?

答: I think the <input> element's values are always shown in $_POST despite of filled or not. You should try isset() and empty() check on the field.

Body:
I created a filter for a table, which worked just fine at first, but as soon as I replaced the input form of the date with a datepicker I noticed that only the filter that involves the date works and the other are ignored and I can't see any reason why it behaves like this.

This is the part that creates the dropdown lists for the filter options:

        echo "<form action='listTimes.php' method='post'>

Filter By:

            Task Name
            Task Stage
            Name
            Date

            ";
        // first filter option - dropdown
        $sql = "SELECT DISTINCT taskName FROM tasks";
        $result = mysqli_query($link, $sql);
            echo "<select name='taskName'>";
            echo "<option selected='selected' value='' disabled='disabled'></option>";
            while ($row = mysqli_fetch_array($result)) {
            if (isset($row['taskName'])) {
            echo "<option value='" . $row['taskName'] . "'>" . $row['taskName'] . "</option>";
                }
            }
    echo "</select>

            ";
            // second filter option - dropdown
            $sql = "SELECT DISTINCT taskStage FROM taskattributes";
            $result = mysqli_query($link, $sql);

            echo "<select name='taskStage'>
            <option selected='selected' value='' disabled='disabled'></option>";
            while ($row = mysqli_fetch_array($result)) {
            if (isset($row['taskStage'])) {
                echo "<option value='" . $row['taskStage'] . "'>" . $row['taskStage'] . "</option>";
                }
            }
            echo "</select>

            ";
            // third filter option - dropdown
            $sql = "SELECT DISTINCT userName FROM users";
            $result = mysqli_query($link, $sql);

            echo "<select name='userName'>";
            echo "<option selected='selected' value='' disabled='disabled'></option>";
            while ($row = mysqli_fetch_array($result)) {
            if (isset($row['userName'])) {
                echo "<option value='" . $row['userName'] . "'>" . $row['userName'] . "</option>";
                }
            }
         /* fourth filter option, was just a simple text input at first. Now I changed it to a datepicker, which works, but the other three filter options stopped working at this point */
      echo "</select>

            <input type='text' class='datepicker' name='entryDate'>

  <input type='submit' value='Filter'>

    </form>

The filter mechanism behind is very poorly written, but works just fine:

    if(!isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $sql = "SELECT * FROM timeEntry";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage' AND userName='$userName'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage' AND userName='$userName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
}
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage' AND userName='$userName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE userName='$userName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage'AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND userName='$userName'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND userName='$userName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $sql = "SELECT * FROM timeEntry WHERE userName='$userName'";
    $result = $link->query($sql);
    }
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
    {
    $taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
    $entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
    $sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND entryDate='$entryDate'";
    $result = $link->query($sql);
    }
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && isset($_POST['userName']) && !isset($_POST['entryDate']))
    {
    $taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
    $userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
    $sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage' AND userName='$userName'";
    $result = $link->query($sql);
    }

echo "

Entry No.
Task/Activity
Task Stage
User Name
Time Spent
Date
Edit Entry
Delete Entry

";

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "

        "  . $row['timeId'] . "
        	";
        echo "" . $row['taskName'] . "	";
        echo "" . $row['taskStage'] . "	";
        echo "" . $row['userName'] . "	";
        echo "" . $row['timeSpent'] . "	";
        $originaldate = mysqli_real_escape_string($link, $row['entryDate']);
        $newdate = date("d/m/Y", strtotime($row['entryDate']));
        echo "" . $newdate . "	";
        echo "Edit	";
        echo "Delete

";
    }
    echo "
";
}

This piece of code as bad as it looks, worked just fine before adding the date picker:

<input type='text' class='datepicker' name='entryDate'>

I have noticed a strange behavior:

If I delete the name attribute name='entryDate' the other filters work and the datepicker also, but the date is not recorded when I press filter and in consequence the date filter doesn't work.

If I leave the name attribute name='entryDate', the other three filters stop working, and only the date filter works.

Is there any reason for this behaviour? and any solution ?


来源: stackexchange

问:
Best framework for developing real-time website?
The title may be misleading many, so let me rephrase. What is the best framework or language that is used for displaying real-time data, that requires a lot of UI/backend rendering?

Recently I was using mean stack with angular2 for a project and it was very cumbersome for always using two-way data-binding or using event emitters to watch any change.

Is there any language/framework that just renders UI based on what has been changed in backend or frontend?

Would reactjs or metoeorjs do the job?

Please enlighten me.

Thanks

答:
I'm unsure of what would have changed with Angular2 but Angular JS was developed to among other things, make something like that easy.

Since Angular 2 has added much more and streamlined how things are done I'm going to say you don't have a good grasp on what the capabilities are because that should be able to handle that. If not, then Angular JS(1) can for sure.

ContentLicense: CC BY-SA 3.0


问:
Use getters/setters in Svelte Custom methods
I am not able to compile my svelte component when using a get/set pair in custom methods. Is this not supported? Or am I doing something wrong?

Example:

Say I wanted to have a component that displays a name and I want to set the name using.

com.name = 'The new name';

However I only want the component to use the name if it has no spaces in the name.

```<code><h1>Hello {{name}}!</h1>

<script>
    export default {
        data () {
            return {
                name: 'The Name',
            }
        },
        methods: {
            get displayName() {
                return this.get('name');
            },
            set displayName(val) {
                if (val.indexOf(' ') < 0) {
                    this.set('name', val);
                }
            }
        }
    }
</script>
</code>```

The Issue is that when I try to compile this, it says there is a duplicate key.

```<code>    Duplicate property 'displayName'

    49:             return this.get('name');
    50:         },
    51:         set displayName(val) {
</code>```

Here is a REPL - https://svelte.technology/repl?version=1.13.2&gist=0eeab5717526694139ba73eae766bb30

I don't see anything in the documentation about this. I can just not use setters, but I would like to be able to.

答:
Edit: As Rich Harris pointed out in the comments below, getters and setters won't work within data because Svelte copies the properties to a plain JS object internally (thus ignoring getters and setters). I think the next best thing you can do is make a method name that can be called like name() as a getter, and name(value) as a setter.

Svelte Code:

```<code><h1>Hello {{_name}}!</h1>

<script>
  export default {
    data() {
      return {
        _name: 'The Name'
      }
    },
    methods: {
      name(value) {
        if (value === void 0) return this.get('_name')
        this.set('_name', value)
      }
    }
  }
</script>
</code>```

Original Post:

Your getter and setter should be in your data rather than your methods, because they create a property in the end. This property conflicts with the name you defined as equal to 'The Name' inside your original data method. I would suggest using a "private" property _name instead.

Svelte Code (REPL):

```<code><h1>Hello {{name}}!</h1>

<script>
  export default {
    data() {
      return {
        _name: 'The Name',
        get name() {
          return this._name
        },
        set name(value) {
          / /.test(this._name) || (this._name = value)
        }
      }
    }
  }
</script>
</code>```

Body:
I am not able to compile my svelte component when using a get/set pair in custom methods. Is this not supported? Or am I doing something wrong?

Example:

Say I wanted to have a component that displays a name and I want to set the name using.

com.name = 'The new name';

However I only want the component to use the name if it has no spaces in the name.

Hello {{name}}!

The Issue is that when I try to compile this, it says there is a duplicate key.

    Duplicate property 'displayName'

    49:             return this.get('name');
    50:         },
    51:         set displayName(val) {

Here is a REPL - https://svelte.technology/repl?version=1.13.2&gist=0eeab5717526694139ba73eae766bb30

I don't see anything in the documentation about this. I can just not use setters, but I would like to be able to.

Body:
Edit: As Rich Harris pointed out in the comments below, getters and setters won't work within data because Svelte copies the properties to a plain JS object internally (thus ignoring getters and setters). I think the next best thing you can do is make a method name that can be called like name() as a getter, and name(value) as a setter.

Svelte Code:

<h1>Hello {{_name}}!</h1>

<script>
  export default {
    data() {
      return {
        _name: 'The Name'
      }
    },
    methods: {
      name(value) {
        if (value === void 0) return this.get('_name')
        this.set('_name', value)
      }
    }
  }
</script>

Original Post:

Your getter and setter should be in your data rather than your methods, because they create a property in the end. This property conflicts with the name you defined as equal to 'The Name' inside your original data method. I would suggest using a "private" property _name instead.

Svelte Code (REPL):

<h1>Hello {{name}}!</h1>

<script>
  export default {
    data() {
      return {
        _name: 'The Name',
        get name() {
          return this._name
        },
        set name(value) {
          / /.test(this._name) || (this._name = value)
        }
      }
    }
  }
</script>


问:
Android Data Binding: Why doesn't passing in variable to ViewStubs work like include layouts?
With Android data binding it is possible to set a variable on a an included layout like so (from the documentation):

```<code>    <?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:bind="http://schemas.android.com/apk/res-auto">
   <data>
       <variable name="user" type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <include layout="@layout/name"
           bind:user="@{user}"/>
       <include layout="@layout/contact"
           bind:user="@{user}"/>
   </LinearLayout>
</layout>
</code>```

I've tried doing the same thing to pass in variables when using a ViewStub, but it doesn't work. Why don't ViewStubs work like include layouts?

答:
ViewStubs are called out as being different in the Data Binding Library documentation.

ViewStubs

ViewStubs are a little different from normal Views. They start off invisible and when they either are made visible or are explicitly told to inflate, they replace themselves in the layout by inflating another layout.

Because the ViewStub essentially disappears from the View hierarchy, the View in the binding object must also disappear to allow collection. Because the Views are final, a ViewStubProxy object takes the place of the ViewStub, giving the developer access to the ViewStub when it exists and also access to the inflated View hierarchy when the ViewStub has been inflated.

When inflating another layout, a binding must be established for the new layout. Therefore, the ViewStubProxy must listen to the ViewStub's ViewStub.OnInflateListener and establish the binding at that time. Since only one can exist, the ViewStubProxy allows the developer to set an OnInflateListener on it that it will call after establishing the binding.

Body:
With Android data binding it is possible to set a variable on a an included layout like so (from the documentation):

    <?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:bind="http://schemas.android.com/apk/res-auto">
   <data>
       <variable name="user" type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <include layout="@layout/name"
           bind:user="@{user}"/>
       <include layout="@layout/contact"
           bind:user="@{user}"/>
   </LinearLayout>
</layout>

I've tried doing the same thing to pass in variables when using a ViewStub, but it doesn't work. Why don't ViewStubs work like include layouts?


问:
rails - Devise - Handling - devise_error_messages
in my user edit page, there is a line as follows:

```<code><%= devise_error_messages! %>
</code>```

The problem is this does not output errors the standard way that the rest of the app does:

```<code><% flash.each do |key, value| %>
    <div class="flash <%= key %>"><%= value %></div>
<% end %>
</code>```

My question is, how do I get the devise error message to work like the others that use the flash.each?

Thanks.

答:
I'm trying to figure this out myself. I just found this issue logged on Github https://github.com/plataformatec/devise/issues/issue/504/#comment_574788

Jose is saying that devise_error_messsages! method is just a stub (though it contains implementation) and that we're supposed to override/replace it. It would have been nice if this was pointed out somewhere in the wiki, which is why i guess there are a few people like us that have been guessing.

So I'm going to try reopening the module and redefine the method, effectively overriding the default implementation. I'll let you know how it goes.

Update

Yep, that works. I created app/helpers/devise_helper.rb and overrode it like so:

```<code>module DeviseHelper
  def devise_error_messages!
    'KABOOM!'
  end
end
</code>```

So knowing this, I can modify the method to display error messages the way I want it to.

To help you solve your original problem: Here's the original devise_helper.rb on Github. Take a look at how the error messages are being traversed:

```<code>messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
</code>```

That should help you get started. :)

Another update

The resource object is actually the model that is being used by devise (go figure).

```<code>resource.class         #=> User
resource.errors.class  #=> ActiveModel::Error
</code>```

It also appears to be defined in a higher scope (probably coming from the controller), so it can be accessed in a variety of places.

Anywhere in your Helper

```<code>module DeviseHelper
  def devise_error_messages1!
    resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
  end

  def devise_error_messages2!
    resource.errors.full_messages.map { |msg| content_tag(:p, msg) }.join
  end
end
</code>```

Your View

```<code><div><%= resource.errors.inspect %></div>
</code>```

Body:
in my user edit page, there is a line as follows:

<%= devise_error_messages! %>

The problem is this does not output errors the standard way that the rest of the app does:

<% flash.each do |key, value| %>
    <div class="flash <%= key %>"><%= value %>

<% end %>

My question is, how do I get the devise error message to work like the others that use the flash.each?

Thanks.

Body:
I'm trying to figure this out myself. I just found this issue logged on Github https://github.com/plataformatec/devise/issues/issue/504/#comment_574788

Jose is saying that devise_error_messsages! method is just a stub (though it contains implementation) and that we're supposed to override/replace it. It would have been nice if this was pointed out somewhere in the wiki, which is why i guess there are a few people like us that have been guessing.

So I'm going to try reopening the module and redefine the method, effectively overriding the default implementation. I'll let you know how it goes.

Update

Yep, that works. I created app/helpers/devise_helper.rb and overrode it like so:

module DeviseHelper
  def devise_error_messages!
    'KABOOM!'
  end
end

So knowing this, I can modify the method to display error messages the way I want it to.

To help you solve your original problem: Here's the original devise_helper.rb on Github. Take a look at how the error messages are being traversed:

messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join

That should help you get started. :)

Another update

The resource object is actually the model that is being used by devise (go figure).

resource.class         #=> User
resource.errors.class  #=> ActiveModel::Error

It also appears to be defined in a higher scope (probably coming from the controller), so it can be accessed in a variety of places.

Anywhere in your Helper

module DeviseHelper
  def devise_error_messages1!
    resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
  end

  def devise_error_messages2!
    resource.errors.full_messages.map { |msg| content_tag(:p, msg) }.join
  end
end

Your View

<div><%= resource.errors.inspect %></div>


问:
Cant find a way to delete an item from sharedPreferences
I am trying to delete an item from taskList which is connected to sharedPreferences.
I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.

```<code>public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;

//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
    this.context = context;
    this.userName = userName;
    //go to user shared preferences and fill the list
    getData();
    notifyDataSetChanged();

}
//how many item to display
@Override
public int getCount() {
    //return the myTasks size....
    return myTasks.size();
}

//return a specific item by index
@Override
public Object getItem(int i) {
    return myTasks.get(i);
}

//return index number
@Override
public long getItemId(int i) {
    return i;
}

//create our view
@Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
    //inflate the view inside view object -> viewInflated
    final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
    //set our inflated view behavior

    //set pointer for our inflated view

    //set pointer for task name....
    final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
    //set pointer for taskInfo
    final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
    //set pointer for task status....
    final Switch swTask = (Switch) viewInflated.findViewById(taskDone);

    //set task name, by the index of my myTasks collection
    txtTaskName.setText(myTasks.get(index).taskName);
    //set task info, by index of myTasks collection
    txtTaskInfo.setText(myTasks.get(index).taskInfo);
    //set task status , switch is getting true/false
    swTask.setChecked(myTasks.get(index).taskStatus);

    //show date and time dialog
    final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
    dtPicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final AlertDialog.Builder ad = new AlertDialog.Builder(context);
            final AlertDialog aDialog = ad.create();
            final LinearLayout adLayout = new LinearLayout(context);
            adLayout.setOrientation(LinearLayout.VERTICAL);
            TextView txtTime = new TextView(context);
            txtTime.setText("Choose time");
            adLayout.addView(txtTime);

            final TimePicker tp = new TimePicker(context);
            adLayout.addView(tp);
            final DatePicker dp = new DatePicker(context);
            tp.setVisibility(View.GONE);
            adLayout.addView(dp);

            final Button btnNext = new Button(context);
            btnNext.setText("Next>");
            adLayout.addView(btnNext);
            btnNext.setGravity(1);

            Button btnCancel = new Button(context);
            btnCancel.setText("Cancel");
            adLayout.addView(btnCancel);
            btnCancel.setGravity(1);

            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    aDialog.cancel();
                }
            });
            btnNext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final int hour = tp.getHour();
                    final int min = tp.getMinute();

                    final String myHour = String.valueOf(hour);
                    final String myMin = String.valueOf(min);

                    calendar.set(Calendar.MONTH, dp.getMonth());
                    calendar.set(Calendar.YEAR, dp.getYear());
                    calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
                    dp.setVisibility(View.GONE);
                    tp.setVisibility(View.VISIBLE);
                    btnNext.setText("Finish");
                    btnNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                            calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
                            calendar.set(Calendar.MINUTE, tp.getMinute());
                            Intent my_intent = new Intent(context, RingtonePlayingService.class);
                            pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
                            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                            if(hour > 12){
                                String myHour = String.valueOf(hour - 12);
                            }

                            if(min < 10)
                            {
                                String myMin = "0"+String.valueOf(min);
                            }

                            Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
                            aDialog.cancel();
                        }
                    });
                }
            });
            aDialog.setView(adLayout);
            aDialog.show();
        }
    });

    //create listener event, when switch is pressed
    swTask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //we using utlShared to update task status
            //create instance of utlShared
            utlShared myShared = new utlShared(context);
            //calling method of task, and giving userName(shared preferences, taskName, taskStatus)
            myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
            //we sending a message to the user, and inform him/her about the change
            Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();

        }
    });

    //return the view with the behavior.....
    return viewInflated;
}

private void getData() {
    //go to specific shared preferences by user name.....
    SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
    //create instance of our myTasks list
    myTasks = new ArrayList<>();

        Map<String, ?> tasks = taskPref.getAll();
        for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
            //insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
            for(int pos=0 ; pos<myTasks.size() ; pos++){
                myTasks.get(pos);
            }
            String[] str = oneTask.getValue().toString().split(",");
            myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
        }

}
</code>```

}

And my utlShared class is

```<code>public class utlShared {

//context to use later

Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;

public utlShared() {}

public utlShared(Context context)
{
    //get context to use it
    this.context=context;
    //declaretion of shared preferences with file name and file mode (private,public)
   userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
    //declaration of editor
   editor=userPref.edit();

}

//get user and password
public void addUser(String userName, String password)
{

    //stores in the phone device under data\data\package name
    //put in shared preferences user name and password
    editor.putString(userName,password);
    //commit (save/apply) the changes.
    editor.commit();
}

public boolean checkUser(String userName)
{
    //get name by key->userName
    String checkString = userPref.getString(userName,"na");
    //print to logcat a custom message.....
    Log.e("checkUser", "checkUser: "+checkString );
    //check if userName equals to responded data, if it's na, we don't have the user...
    return !checkString.equals("na");

}

public boolean checkUserPassword(String userName, String userPassword)
{
    String checkString = userPref.getString(userName,"na");
    return checkString.equals(userPassword);
}

public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
    //pointer to user task shared preferences
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    //create editor to change the specific shared preferences
    SharedPreferences.Editor taskEditor=taskPref.edit();

    //add new task -> if true write 1 else write 0
    if(!taskDone){
        String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
        taskEditor.putString(taskName,myData);
        //apply the changes
        taskEditor.commit();
    }

}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    SharedPreferences.Editor tskEditor=taskPref.edit();
        tskEditor.clear();
        tskEditor.commit();

}
</code>```

}

This method is called from my Welcome class which is

```<code>public class Welcome extends AppCompatActivity {

String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    setPointer();

}

private void setPointer()
{

    this.context=this;
    userName=getIntent().getStringExtra("userName");
    myUtl = new utlShared(context);
    taskList=(ListView)findViewById(R.id.taskList);
    setListData();
    alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
    Button btnBack = (Button)findViewById(R.id.btnBack);
    FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);

    btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
            setListData();
        }
    });

    btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, MainActivity.class);
            startActivity(intent);
            finish();
        }
    });

}

private void setListData() {
    final TaskAdapter adapter = new TaskAdapter(context, userName);
    taskList.setAdapter(adapter);
}

public void addCustomTask(View view)
{
    //create builder
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    //set title
    builder.setTitle("Add new task!");

    //inflate view from layout ->custom layout,null,false as defualt values
    View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);

    final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
    final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });

    builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();

            String myTaskCustom = txtCustomTask.getText().toString();
            String myTaskLine = txtCustomLine.getText().toString();
                myUtl.task(userName, myTaskCustom, myTaskLine, false);
                setListData();
        }
    });

    //display our inflated view in screen
    builder.setView(viewInflated);
    //show the dialog
    builder.show();

}
</code>```

}

Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...

Thanks in advance guys, much appreciated!

答:
Guess my question wasnt clear enough but I have found a way to do that.

```<code>if(!taskDone){
        String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
        taskEditor.putString(taskName,myData);
        //apply the changes
        taskEditor.commit();
    }
    else
    {
        taskEditor.remove(taskName);
        taskEditor.commit();
        adapter.notifyDataSetChanged();
    }
</code>```

Eventhough its not perfect because I can refresh the view after I update the Editor and only after I restart the app my last deleted tasks disappear.

Cheers and thanks a lot guys!

Body:
I am trying to delete an item from taskList which is connected to sharedPreferences.
I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.

public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;

//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
    this.context = context;
    this.userName = userName;
    //go to user shared preferences and fill the list
    getData();
    notifyDataSetChanged();

}
//how many item to display
@Override
public int getCount() {
    //return the myTasks size....
    return myTasks.size();
}

//return a specific item by index
@Override
public Object getItem(int i) {
    return myTasks.get(i);
}

//return index number
@Override
public long getItemId(int i) {
    return i;
}

//create our view
@Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
    //inflate the view inside view object -> viewInflated
    final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
    //set our inflated view behavior

    //set pointer for our inflated view

    //set pointer for task name....
    final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
    //set pointer for taskInfo
    final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
    //set pointer for task status....
    final Switch swTask = (Switch) viewInflated.findViewById(taskDone);

    //set task name, by the index of my myTasks collection
    txtTaskName.setText(myTasks.get(index).taskName);
    //set task info, by index of myTasks collection
    txtTaskInfo.setText(myTasks.get(index).taskInfo);
    //set task status , switch is getting true/false
    swTask.setChecked(myTasks.get(index).taskStatus);

    //show date and time dialog
    final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
    dtPicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final AlertDialog.Builder ad = new AlertDialog.Builder(context);
            final AlertDialog aDialog = ad.create();
            final LinearLayout adLayout = new LinearLayout(context);
            adLayout.setOrientation(LinearLayout.VERTICAL);
            TextView txtTime = new TextView(context);
            txtTime.setText("Choose time");
            adLayout.addView(txtTime);

            final TimePicker tp = new TimePicker(context);
            adLayout.addView(tp);
            final DatePicker dp = new DatePicker(context);
            tp.setVisibility(View.GONE);
            adLayout.addView(dp);

            final Button btnNext = new Button(context);
            btnNext.setText("Next>");
            adLayout.addView(btnNext);
            btnNext.setGravity(1);

            Button btnCancel = new Button(context);
            btnCancel.setText("Cancel");
            adLayout.addView(btnCancel);
            btnCancel.setGravity(1);

            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    aDialog.cancel();
                }
            });
            btnNext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final int hour = tp.getHour();
                    final int min = tp.getMinute();

                    final String myHour = String.valueOf(hour);
                    final String myMin = String.valueOf(min);

                    calendar.set(Calendar.MONTH, dp.getMonth());
                    calendar.set(Calendar.YEAR, dp.getYear());
                    calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
                    dp.setVisibility(View.GONE);
                    tp.setVisibility(View.VISIBLE);
                    btnNext.setText("Finish");
                    btnNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                            calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
                            calendar.set(Calendar.MINUTE, tp.getMinute());
                            Intent my_intent = new Intent(context, RingtonePlayingService.class);
                            pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
                            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                            if(hour > 12){
                                String myHour = String.valueOf(hour - 12);
                            }

                            if(min < 10)
                            {
                                String myMin = "0"+String.valueOf(min);
                            }

                            Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
                            aDialog.cancel();
                        }
                    });
                }
            });
            aDialog.setView(adLayout);
            aDialog.show();
        }
    });

    //create listener event, when switch is pressed
    swTask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //we using utlShared to update task status
            //create instance of utlShared
            utlShared myShared = new utlShared(context);
            //calling method of task, and giving userName(shared preferences, taskName, taskStatus)
            myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
            //we sending a message to the user, and inform him/her about the change
            Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();

        }
    });

    //return the view with the behavior.....
    return viewInflated;
}

private void getData() {
    //go to specific shared preferences by user name.....
    SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
    //create instance of our myTasks list
    myTasks = new ArrayList<>();

        Map<String, ?> tasks = taskPref.getAll();
        for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
            //insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
            for(int pos=0 ; pos<myTasks.size() ; pos++){
                myTasks.get(pos);
            }
            String[] str = oneTask.getValue().toString().split(",");
            myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
        }

}

}

And my utlShared class is

public class utlShared {

//context to use later

Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;

public utlShared() {}

public utlShared(Context context)
{
    //get context to use it
    this.context=context;
    //declaretion of shared preferences with file name and file mode (private,public)
   userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
    //declaration of editor
   editor=userPref.edit();

}

//get user and password
public void addUser(String userName, String password)
{

    //stores in the phone device under data\data\package name
    //put in shared preferences user name and password
    editor.putString(userName,password);
    //commit (save/apply) the changes.
    editor.commit();
}

public boolean checkUser(String userName)
{
    //get name by key->userName
    String checkString = userPref.getString(userName,"na");
    //print to logcat a custom message.....
    Log.e("checkUser", "checkUser: "+checkString );
    //check if userName equals to responded data, if it's na, we don't have the user...
    return !checkString.equals("na");

}

public boolean checkUserPassword(String userName, String userPassword)
{
    String checkString = userPref.getString(userName,"na");
    return checkString.equals(userPassword);
}

public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
    //pointer to user task shared preferences
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    //create editor to change the specific shared preferences
    SharedPreferences.Editor taskEditor=taskPref.edit();

    //add new task -> if true write 1 else write 0
    if(!taskDone){
        String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
        taskEditor.putString(taskName,myData);
        //apply the changes
        taskEditor.commit();
    }

}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    SharedPreferences.Editor tskEditor=taskPref.edit();
        tskEditor.clear();
        tskEditor.commit();

}

}

This method is called from my Welcome class which is

public class Welcome extends AppCompatActivity {

String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    setPointer();

}

private void setPointer()
{

    this.context=this;
    userName=getIntent().getStringExtra("userName");
    myUtl = new utlShared(context);
    taskList=(ListView)findViewById(R.id.taskList);
    setListData();
    alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
    Button btnBack = (Button)findViewById(R.id.btnBack);
    FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);

    btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
            setListData();
        }
    });

    btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, MainActivity.class);
            startActivity(intent);
            finish();
        }
    });

}

private void setListData() {
    final TaskAdapter adapter = new TaskAdapter(context, userName);
    taskList.setAdapter(adapter);
}

public void addCustomTask(View view)
{
    //create builder
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    //set title
    builder.setTitle("Add new task!");

    //inflate view from layout ->custom layout,null,false as defualt values
    View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);

    final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
    final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });

    builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();

            String myTaskCustom = txtCustomTask.getText().toString();
            String myTaskLine = txtCustomLine.getText().toString();
                myUtl.task(userName, myTaskCustom, myTaskLine, false);
                setListData();
        }
    });

    //display our inflated view in screen
    builder.setView(viewInflated);
    //show the dialog
    builder.show();

}

}

Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...

Thanks in advance guys, much appreciated!

Body:
Guess my question wasnt clear enough but I have found a way to do that.

if(!taskDone){
        String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
        taskEditor.putString(taskName,myData);
        //apply the changes
        taskEditor.commit();
    }
    else
    {
        taskEditor.remove(taskName);
        taskEditor.commit();
        adapter.notifyDataSetChanged();
    }

Eventhough its not perfect because I can refresh the view after I update the Editor and only after I restart the app my last deleted tasks disappear.

Cheers and thanks a lot guys!


问:
How do I create a pub package that works with Flutter?
pub is Dart's package manager. Flutter is a mobile app SDK that uses Dart. How can I create a package that depends on, or targets, Flutter?</p>

答:
To declare a dependency on Flutter, from a pub package, add this to your pubspec.yaml:

```<code>dependencies:
  flutter:
    sdk: flutter
</code>```

You must use flutter packages get instead of pub get, because Flutter needs to set the appropriate environment variables to map the sdk: flutter to a location.

To easily and quickly create a new pub package, use the stagehand tool. After you install stagehand, follow these instructions:

```<code>$ mkdir fancy_project
$ cd fancy_project
$ stagehand package-simple
</code>```

After you create your new package, edit the pubspec.yaml and add the sdk:flutter as shown above.

Body:
To declare a dependency on Flutter, from a pub package, add this to your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter

You must use flutter packages get instead of pub get, because Flutter needs to set the appropriate environment variables to map the sdk: flutter to a location.

To easily and quickly create a new pub package, use the stagehand tool. After you install stagehand, follow these instructions:

$ mkdir fancy_project
$ cd fancy_project
$ stagehand package-simple

After you create your new package, edit the pubspec.yaml and add the sdk:flutter as shown above.


问:
Editing a row in DB
In my RAdGrid that I am using there's this edit button to edit a Question in the list. When I click on edit, it is ALWAYS the
first row data that is fetched from Ques table..like it is always the first ques that gets filled when Edit button is clicked
no matter what question's edit button I click. I am using Telerik's RADgrid so cannot pass CommandArgument to Edit button..what's wrong ??</p>

```<code>            if (e.CommandName == "Edit")
            {
                Common com = new Common();
                Int32 ID = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["QuesID"].ToString());

                Response.Redirect(http://localhost/myweb/ + "editques/" + "QuesID/" + QuesID + "/" + PID);
            }

   ALTER PROC [Admin].[sp_Ques]
(
 @QuesID bigint =null
 )
AS
BEGIN
........
END
</code>```

答: You are not sending any parameters to your [Admin].[sp_Ques] and since it has a default null value, you dont get any error message about it either

ContentLicense: CC BY-SA 2.5

Title: Editing a row in DB

Body:
In my RAdGrid that I am using there's this edit button to edit a Question in the list. When I click on edit, it is ALWAYS the
first row data that is fetched from Ques table..like it is always the first ques that gets filled when Edit button is clicked
no matter what question's edit button I click. I am using Telerik's RADgrid so cannot pass CommandArgument to Edit button..what's wrong ??

            if (e.CommandName == "Edit")
            {
                Common com = new Common();
                Int32 ID = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["QuesID"].ToString());

                Response.Redirect(http://localhost/myweb/ + "editques/" + "QuesID/" + QuesID + "/" + PID);
            }

   ALTER PROC [Admin].[sp_Ques]
(
 @QuesID bigint =null
 )
AS
BEGIN
........
END


问:
unable to update textview immideately
i'm making a translation app in which i want to update a textview but it is not doing as i want.

```<code>final audioTranslate at[] = new audioTranslate[1];
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio_translate);
    tv = (TextView) findViewById(R.id.textView11);
    spokentext = (TextView) findViewById(R.id.textView12);
    translatedtext = (TextView) findViewById(R.id.textView13);
    at[0] = this;
    start = (Button) findViewById(R.id.Start);
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Button b = (Button) v;
            if (b.getText().toString().equals("Start")) {
                //code
            }
            else{
                tv.setText("");  //these all 3 operations are happening after transfer method is finished.
                b.setText("Wait");
                b.setEnabled(false);
                transfer();
            }
        }
    });
}

void transfer() {
    Thread t = new Thread() {
        public void run() {
            //socket connection
            //it is giving exception on below line too.
            //Only the original thread that created a view hierarchy can touch its views.
            //java.lang.RuntimeException
            at[0].spokentext.setText(spoken);
        }
    };
t.start();
}
</code>```

this is my layout file for reference:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_audio_translate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="diverse.technologies.transcriber.audioTranslate">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal">

            <Button
                android:text="Start"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/Start" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:gravity="center_horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView11"
                android:textColor="@color/colorAccent"
                android:textSize="24sp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView12"
                android:textSize="26sp"
                android:fontFamily="serif-monospace"
                android:textStyle="normal|bold" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView13"
                android:textSize="24sp"/>
        </TableRow>

    </TableLayout>
</ScrollView>

</RelativeLayout>
</code>```

I'm not getting what is wrong with above exception i'm getting. i'm using the object of the view that is having the textview. please help.

答:
Like what @Pavneet_Singh said, you cannot update your UI from another thread. Instead of calling transfer(), you probably want to do it like this.

```<code>public class YourActivity {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Button b = (Button) v;
                if (b.getText().toString().equals("Start")) {
                    //code
                } else {
                    tv.setText("");  //these all 3 operations are happening after transfer method is finished.
                    b.setText("Wait");
                    b.setEnabled(false);
                    new RetrieveSpokenTextTask().execute();
                }
            }
        });
    }

    private class RetrieveSpokenTextTask extends AsyncTask<Void,Void,String> {
        @Override
        public String doInBackground(Void... params) {
            String spoken = "the value you would like to assign to the TextView";
            return spoken;
        }

        @Override
        public void postExecute(String text) {
            // the `text` variable has now the string you returned in `doInBackground`
            spokentext.setText(text);
        }
    }
}
</code>```

Title: unable to update textview immideately

Body:
i'm making a translation app in which i want to update a textview but it is not doing as i want.

final audioTranslate at[] = new audioTranslate[1];
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio_translate);
    tv = (TextView) findViewById(R.id.textView11);
    spokentext = (TextView) findViewById(R.id.textView12);
    translatedtext = (TextView) findViewById(R.id.textView13);
    at[0] = this;
    start = (Button) findViewById(R.id.Start);
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Button b = (Button) v;
            if (b.getText().toString().equals("Start")) {
                //code
            }
            else{
                tv.setText("");  //these all 3 operations are happening after transfer method is finished.
                b.setText("Wait");
                b.setEnabled(false);
                transfer();
            }
        }
    });
}

void transfer() {
    Thread t = new Thread() {
        public void run() {
            //socket connection
            //it is giving exception on below line too.
            //Only the original thread that created a view hierarchy can touch its views.
            //java.lang.RuntimeException
            at[0].spokentext.setText(spoken);
        }
    };
t.start();
}

this is my layout file for reference:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_audio_translate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="diverse.technologies.transcriber.audioTranslate">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal">

            <Button
                android:text="Start"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/Start" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:gravity="center_horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView11"
                android:textColor="@color/colorAccent"
                android:textSize="24sp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView12"
                android:textSize="26sp"
                android:fontFamily="serif-monospace"
                android:textStyle="normal|bold" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView13"
                android:textSize="24sp"/>
        </TableRow>

    </TableLayout>
</ScrollView>

</RelativeLayout>

I'm not getting what is wrong with above exception i'm getting. i'm using the object of the view that is having the textview. please help.

Body:
Like what @Pavneet_Singh said, you cannot update your UI from another thread. Instead of calling transfer(), you probably want to do it like this.

public class YourActivity {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Button b = (Button) v;
                if (b.getText().toString().equals("Start")) {
                    //code
                } else {
                    tv.setText("");  //these all 3 operations are happening after transfer method is finished.
                    b.setText("Wait");
                    b.setEnabled(false);
                    new RetrieveSpokenTextTask().execute();
                }
            }
        });
    }

    private class RetrieveSpokenTextTask extends AsyncTask<Void,Void,String> {
        @Override
        public String doInBackground(Void... params) {
            String spoken = "the value you would like to assign to the TextView";
            return spoken;
        }

        @Override
        public void postExecute(String text) {
            // the `text` variable has now the string you returned in `doInBackground`
            spokentext.setText(text);
        }
    }
}


问:
ChromeOptions AddUserProfilePreference
I am using Webdriver 3.3.1 with Java. I am trying to disable the pop-up asking to save passwords. Based on search results I need to use
ChromOptions.AddUserProfilePreference("","")
However, there is no AddUserProfilePreference
the only add method is addArguments.

I am using Eclipse Neon.2 and Java 1.8

答:
Add the below chrome options:</p>

```<code>Map<String, Object> prefs =new HashMap<String, Object>();
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-extensions");
prefs .put("credentials_enable_service", false);
prefs .put("profile.password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);
</code>```

Title: ChromeOptions AddUserProfilePreference

Body:
Add the below chrome options:

Map<String, Object> prefs =new HashMap<String, Object>();
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-extensions");
prefs .put("credentials_enable_service", false);
prefs .put("profile.password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);


问:
Swift/Firebase : Access and store data to array
I'm trying to access all the questions in the tree that starts from

var ref = FIRDatabase.database().reference().child("trivia")

and when I print the contents with the following function

```<code>func observeQuestion(completion: @escaping (Trivia) -> Void) {
    ref.observe(.value, with: { snapshot in
        if let dict = snapshot.value {
            print("\(dict)")
        }
    })
}
</code>```

I get the tree as follows

But I can't figure out how to access the Question and print that out, it always comes out as nil. I want to access all the questions value and store them in an array. How should I approach this?

答:
Try this:</p>

   ```<code>let questions = snapshot.value as! [[String: Any]]
for question in questions {
    let title = question["Question"]!
    print("Question: \(title)")
}
</code>```

Body:
I'm trying to access all the questions in the tree that starts from

var ref = FIRDatabase.database().reference().child("trivia")

and when I print the contents with the following function

func observeQuestion(completion: @escaping (Trivia) -> Void) {
    ref.observe(.value, with: { snapshot in
        if let dict = snapshot.value {
            print("\(dict)")
        }
    })
}

I get the tree as follows

But I can't figure out how to access the Question and print that out, it always comes out as nil. I want to access all the questions value and store them in an array. How should I approach this?

Body:
Try this:

let questions = snapshot.value as! [[String: Any]]
for question in questions {
    let title = question["Question"]!
    print("Question: \(title)")
}


问:
Array.push performs deep copy instead of shallow copy
Context

I'm using Typescript/Angular2 RC1 for my webapp and I have two classes. In class1 (Angular2 service), I have a variable myVar = [obj1, obj2, obj3] and in class2 (Angular2 component), I get myLocalVar = class1.myVar in the constructor using viewInjector to inject the service.

Problem

In class2, I copy myVar with a push (shallow copy because it copies objects) so myLocalVar is equal to [obj1, obj2, obj3] (such that objX={number:X}). When I change one item such as: myVar[0]={number:5} in class1 the change won't appear in my class2 myLocalVar and myLocalVar[0].number will be equal to 1. However, myVar of class2 changes... It seems that the this.myLocalVar.push(this.myVar[int]); created a deep copy instead of a shallow copy.

Is Typescript changing the behavior of a push in Javascript? If yes, what should I do to keep the reference and do a shallow copy?

Code Sample

```<code>@Injectable()

export class Class1{

    public myVar:any[];

    constructor(){
        this.myVar = [{number: 1}, {number: 2}, {number: 3}];
    }

    changeVar(newVar):void{
        this.myVar[0] = newVar; // newVar = {number: 5}
    }
}
</code>```

```<code>@Component({
    selector: 'class2',
    viewInjector: [Class1],
    templateUrl: 'someURL'
})
export class Class2{

    private myLocalVar:any[] = [];

    constructor(class1: Class1){
        this.myVar = class1.myVar;
    }

    showVars():void{
        console.log(this.myLocalVar[0]);
        console.log(this.myVar[0]);
    }

    ngOnInit(){
        for(let int = 0; int < this.myVar.length; int++){
            this.myLocalVar.push(this.myVar[int]);
        }
    }
}
</code>```

The console.log will print two different values: console.log(this.myLocalVar[0]) prints 1 and console.log(this.myVar[0]); prints 5 after changeVar() has been called by a third party!

Edit

Here is a plunker that demonstrates the problem:

Click on show, check your console and you will see the same values

Click on change

Click on show again and you will see two different values for myVar and myLocalVar

What I need is each time I change myVar[x]=newObj I want myLocalVar to reflect that change. Please include a solution to that problem if you want your answer to be validated.

答:
"Object.assign" does the shallow copy.</p>

```<code>(<any>Object).assign(this.shallowCopyObject, this.myObject);
</code>```

Body:
Context

I'm using Typescript/Angular2 RC1 for my webapp and I have two classes. In class1 (Angular2 service), I have a variable myVar = [obj1, obj2, obj3] and in class2 (Angular2 component), I get myLocalVar = class1.myVar in the constructor using viewInjector to inject the service.

Problem

In class2, I copy myVar with a push (shallow copy because it copies objects) so myLocalVar is equal to [obj1, obj2, obj3] (such that objX={number:X}). When I change one item such as: myVar[0]={number:5} in class1 the change won't appear in my class2 myLocalVar and myLocalVar[0].number will be equal to 1. However, myVar of class2 changes... It seems that the this.myLocalVar.push(this.myVar[int]); created a deep copy instead of a shallow copy.

Is Typescript changing the behavior of a push in Javascript? If yes, what should I do to keep the reference and do a shallow copy?

Code Sample

@Injectable()

export class Class1{

    public myVar:any[];

    constructor(){
        this.myVar = [{number: 1}, {number: 2}, {number: 3}];
    }

    changeVar(newVar):void{
        this.myVar[0] = newVar; // newVar = {number: 5}
    }
}

@Component({
    selector: 'class2',
    viewInjector: [Class1],
    templateUrl: 'someURL'
})
export class Class2{

    private myLocalVar:any[] = [];

    constructor(class1: Class1){
        this.myVar = class1.myVar;
    }

    showVars():void{
        console.log(this.myLocalVar[0]);
        console.log(this.myVar[0]);
    }

    ngOnInit(){
        for(let int = 0; int < this.myVar.length; int++){
            this.myLocalVar.push(this.myVar[int]);
        }
    }
}

The console.log will print two different values: console.log(this.myLocalVar[0]) prints 1 and console.log(this.myVar[0]); prints 5 after changeVar() has been called by a third party!

Edit

Here is a plunker that demonstrates the problem:

Click on show, check your console and you will see the same values

Click on change

Click on show again and you will see two different values for myVar and myLocalVar

What I need is each time I change myVar[x]=newObj I want myLocalVar to reflect that change. Please include a solution to that problem if you want your answer to be validated.

Body:
"Object.assign" does the shallow copy.

(<any>Object).assign(this.shallowCopyObject, this.myObject);


问:
Java: How to get the last word of the dynamic string
I have below string which I need to capture last word.

Below is my code but its not getting the last word.

The string at below location is dynamic and is not static string.

```<code>String secques1 = driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText();

String lastWord = secques1.substring(secques1.lastIndexOf(" ")+1);`
</code>```

答:
This should work:</p>

```<code>String secques1 = " " + driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText();
String lastWord = secques1.substring(secques1.lastIndexOf(" ")+1);
</code>```

Body:
I have below string which I need to capture last word.

Below is my code but its not getting the last word.

The string at below location is dynamic and is not static string.

String secques1 = driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText();

String lastWord = secques1.substring(secques1.lastIndexOf(" ")+1);`

Body:
This should work:

String secques1 = " " + driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText();
String lastWord = secques1.substring(secques1.lastIndexOf(" ")+1);


问:
Creating objects in Python way
I'm learning Python and recently started with the OOP part.
I know there are different ways to create objects but I do not know what way I should aim at.

Create objects with arguments or without arguments?
Then I do understand the best way to change the attributes is with method calls.

Code:

```<code>class Human(object):
    def __init__(self):
        self.name = ''
        self.age = 0

    def set_name(self, name):
        self.name = name

    def set_age(self, age):
        self.age = age

class Humans(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def set_names(self, name):
        self.name = name

    def set_ages(self, age):
        self.age = age

# Create object without arguments
boy = Human()
boy.set_name('Peter')
boy.set_age(30)

# Or create object with arguments
girl = Humans('Sandra', 40)
</code>```

答:
An object should be in an usable state after creation. That said, a human with no name and no age is not useful. So the second implemention is preferred. Another thing is, that you don't need setters in python, which reduces the class to</p>

```<code>class Humans(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
</code>```

Title: Creating objects in Python way

Body:
I'm learning Python and recently started with the OOP part.
I know there are different ways to create objects but I do not know what way I should aim at.

Create objects with arguments or without arguments?
Then I do understand the best way to change the attributes is with method calls.

Code:

class Human(object):
    def __init__(self):
        self.name = ''
        self.age = 0

    def set_name(self, name):
        self.name = name

    def set_age(self, age):
        self.age = age

class Humans(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def set_names(self, name):
        self.name = name

    def set_ages(self, age):
        self.age = age

# Create object without arguments
boy = Human()
boy.set_name('Peter')
boy.set_age(30)

# Or create object with arguments
girl = Humans('Sandra', 40)

Body:
An object should be in an usable state after creation. That said, a human with no name and no age is not useful. So the second implemention is preferred. Another thing is, that you don't need setters in python, which reduces the class to

class Humans(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age