问:
Registration Form: function prepare() on null
I am trying to create a registration form (using an SQL database) that utilizes my
"register.inc.php" file, When I attempt to create an account (as a test) I get

THIS error:
"Fatal error: Call to a member function prepare() on null in /usr/www/world/includes/register.inc.php on line 30"

I've posted the code from my register.inc.php, any insight would be much appreciated.

```<code>    <?php
include_once 'loginhandler.php';
include_once 'DBclass.php';

$error_msg = "";

if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
    // Sanitize and validate the data passed in
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $email = filter_var($email, FILTER_VALIDATE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Not a valid email
        $error_msg .= '<p class="error">The email address you entered is not valid</p>';
    }

    $password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
    if (strlen($password) != 128) {
        // The hashed pwd should be 128 characters long.
        // If it's not, something really odd has happened
        $error_msg .= '<p class="error">Invalid password configuration.</p>';
    }

    // Username validity and password validity have been checked client side.
    // This should should be adequate as nobody gains any advantage from
    // breaking these rules.
    //

    $prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);

   // check existing email
    if ($stmt) {
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows == 1) {
            // A user with this email address already exists
            $error_msg .= '<p class="error">A user with this email address already exists.</p>';
            $stmt->close();
        }
    } else {
        $error_msg .= '<p class="error">Database error Line 39</p>';
        $stmt->close();
    }

    // check existing username
    $prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);

    if ($stmt) {
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows == 1) {
            // A user with this username already exists
            $error_msg .= '<p class="error">A user with this username already exists</p>';
            $stmt->close();
        }
    } else {
        $error_msg .= '<p class="error">Database error line 55</p>';
        $stmt->close();
    }

    // TODO:
    // We'll also have to account for the situation where the user doesn't have
    // rights to do registration, by checking what type of user is attempting to
    // perform the operation.

    if (empty($error_msg)) {

        // Create hashed password using the password_hash function.
        // This function salts it with a random salt and can be verified with
        // the password_verify function.
        $password = password_hash($password, PASSWORD_BCRYPT);

        // Insert the new user into the database
        if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password) VALUES (?, ?, ?)")) {
            $insert_stmt->bind_param('sss', $username, $email, $password);
            // Execute the prepared query.
            if (! $insert_stmt->execute()) {
                header('Location: ../error.php?err=Registration failure: INSERT');
            }
        }
        header('Location: ./register_success.php');
    }
}
?>
</code>```

答: I'm thinking that 'DBclass.php' contains an assignment to "$ mysqli" variable. It's correct? Because in your current script it does not contain any assigment to this variable. (So it's OK, it contains null value because it's never initialized)</p>

Body:
I am trying to create a registration form (using an SQL database) that utilizes my
"register.inc.php" file, When I attempt to create an account (as a test) I get

THIS error:
"Fatal error: Call to a member function prepare() on null in /usr/www/world/includes/register.inc.php on line 30"

I've posted the code from my register.inc.php, any insight would be much appreciated.

    <?php
include_once 'loginhandler.php';
include_once 'DBclass.php';

$error_msg = "";

if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
    // Sanitize and validate the data passed in
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $email = filter_var($email, FILTER_VALIDATE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Not a valid email
        $error_msg .= '
The email address you entered is not valid
';
    }

    $password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
    if (strlen($password) != 128) {
        // The hashed pwd should be 128 characters long.
        // If it's not, something really odd has happened
        $error_msg .= '
Invalid password configuration.
';
    }

    // Username validity and password validity have been checked client side.
    // This should should be adequate as nobody gains any advantage from
    // breaking these rules.
    //

    $prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);

   // check existing email
    if ($stmt) {
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows == 1) {
            // A user with this email address already exists
            $error_msg .= '
A user with this email address already exists.
';
            $stmt->close();
        }
    } else {
        $error_msg .= '
Database error Line 39
';
        $stmt->close();
    }

    // check existing username
    $prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);

    if ($stmt) {
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows == 1) {
            // A user with this username already exists
            $error_msg .= '
A user with this username already exists
';
            $stmt->close();
        }
    } else {
        $error_msg .= '
Database error line 55
';
        $stmt->close();
    }

    // TODO:
    // We'll also have to account for the situation where the user doesn't have
    // rights to do registration, by checking what type of user is attempting to
    // perform the operation.

    if (empty($error_msg)) {

        // Create hashed password using the password_hash function.
        // This function salts it with a random salt and can be verified with
        // the password_verify function.
        $password = password_hash($password, PASSWORD_BCRYPT);

        // Insert the new user into the database
        if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password) VALUES (?, ?, ?)")) {
            $insert_stmt->bind_param('sss', $username, $email, $password);
            // Execute the prepared query.
            if (! $insert_stmt->execute()) {
                header('Location: ../error.php?err=Registration failure: INSERT');
            }
        }
        header('Location: ./register_success.php');
    }
}
?>


来源: stackexchange

问:
Syntax highlighting of C function calls in emacs
I use a custom syntax highlighting theme for C in emacs, but I'm missing the possibility of highlighting function calls. For example:

```<code>int func(int foo)
{
    return foo;
}

void main()
{
    int bar = func(3);
}
</code>```

Is there any way to highlight the call to "func" in this example?
It doesn't matter if macros are highlighted too. Keywords like if, switch or sizeof should not match.

Thanks!

答:
```<code>(font-lock-add-keywords 'c-mode
                   '(("\\<\\([a-zA-Z_]*\\) *("  1 font-lock-keyword-face)))
</code>```

in your .emacs.  Replace font-lock-keyword-face by the one you want (M-X list-faces-display to get a list of predefined one).

ContentLicense: CC BY-SA 2.5

Body:
I use a custom syntax highlighting theme for C in emacs, but I'm missing the possibility of highlighting function calls. For example:

int func(int foo)
{
    return foo;
}

void main()
{
    int bar = func(3);
}

Is there any way to highlight the call to "func" in this example?
It doesn't matter if macros are highlighted too. Keywords like if, switch or sizeof should not match.

Thanks!

Body:
(font-lock-add-keywords 'c-mode
                   '(("\\<\\([a-zA-Z_]*\\) *("  1 font-lock-keyword-face)))

in your .emacs.  Replace font-lock-keyword-face by the one you want (M-X list-faces-display to get a list of predefined one).


问:
Specify maven profile to use by aether
I have packed karaf container in docker image, that should be used in test and production. There are different nexus repositories used (the artifacts for production repository are first deployed after successfull test) and I want to control, which repository to use through environment variables, because it's the most flexible solution (and also recommended way of configuring images in OpenShift etc.).

Is it possible to set maven profile that will be used by aether?

There is setting org.ops4j.pax.url.mvn.settings so I could deploy 2 setting.xml files and choose the correct one, but then the test could go through with even incorrect productive maven settings. Profiles seem to be more error-resistant way.

答:
Use Karaf-maven-plugin to build your Karaf distribution.

Define two profiles in the pom.xml of your Karaf distribution.

set the appropriate profile when building your Karaf :

mvn clean install -PprodProfile

mvn clean install -PtestProfile

Start the already builded Karaf assembly: it must point to the good repository.

ContentLicense: CC BY-SA 3.0

Title: Specify maven profile to use by aether


问:
Display ajax response inside table
I want to display data from ajax response inside table.

Here is my table:

```<code><table data-toggle="table" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" id="menu_table">
    <thead>
    <tr>
        <th class="centerText" data-field="item_id">ID</th>
        <th class="centerText" data-field="name">Name</th>
        <th class="centerText" data-field="price">Price</th>
        <th class="centerText" data-field="image">Image</th>
        <th class="centerText" data-field="edit">Edit</th>
    </tr>
    </thead>
    <tbody style="text-align:center;" id="menu_table_data"></tbody>
</table>
</code>```

This is menu_table.php which gets data from database and returns response to ajax :

```<code>$output = '';
$search = mysqli_query($link,"SELECT menu.id, menu.name, menu.price, menu.image ORDER BY menu.id ASC;");

while($data = mysqli_fetch_array($search))
{
    $output .= '<td>'.$data['id'].'</td>
                <td>'.$data['name'].'</td>
                <td>'.$data['price'].'</td>
                <td><div id="div_image">
                <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div></td>
                <td><a class="btn btn-primary glyphicon glyphicon-edit" role="button"></a></td>
                ';
}
echo $output;
</code>```

This is ajax function:

```<code>$(document).ready(function(){
    function fetch_data(){
        $.ajax({
            url: "menu_table.php",
            method: "POST",
            success: function(data){
                $('#menu_table_data').html(data);
            }
        });
    }
    fetch_data();
});
</code>```

$('#menu_table_data').html(data); is showing data but not like table data. How can i show it inside table properly?

答:
You have missed

.

try this:

```<code>$output = '';
$search = mysqli_query($link,"SELECT menu.id, menu.name, menu.price, menu.image ORDER BY menu.id ASC;");
while($data = mysqli_fetch_array($search)) {
    $output .= '
    <tr>
      <td>'.$data['id'].'</td>
      <td>'.$data['name'].'</td>
      <td>'.$data['price'].'</td>
      <td>
        <div id="div_image">
          <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div>
      </td>
      <td>
        <a class="btn btn-primary glyphicon glyphicon-edit" role="button"></a>
      </td>
    </tr>
    ';
}
echo $output;
</code>```

Title: Display ajax response inside table

Body:
I want to display data from ajax response inside table.

Here is my table:

        ID
        Name
        Price
        Image
        Edit

This is menu_table.php which gets data from database and returns response to ajax :

$output = '';
$search = mysqli_query($link,"SELECT menu.id, menu.name, menu.price, menu.image ORDER BY menu.id ASC;");

while($data = mysqli_fetch_array($search))
{
    $output .= ''.$data['id'].'
                '.$data['name'].'
                '.$data['price'].'

                ';
}
echo $output;

This is ajax function:

$(document).ready(function(){
    function fetch_data(){
        $.ajax({
            url: "menu_table.php",
            method: "POST",
            success: function(data){
                $('#menu_table_data').html(data);
            }
        });
    }
    fetch_data();
});

$('#menu_table_data').html(data); is showing data but not like table data. How can i show it inside table properly?

Body:
You have missed <tr></tr>.

try this:

$output = '';
$search = mysqli_query($link,"SELECT menu.id, menu.name, menu.price, menu.image ORDER BY menu.id ASC;");
while($data = mysqli_fetch_array($search)) {
    $output .= '
    <tr>
      <td>'.$data['id'].'</td>
      <td>'.$data['name'].'</td>
      <td>'.$data['price'].'</td>
      <td>
        <div id="div_image">
          <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div>
      </td>
      <td>
        <a class="btn btn-primary glyphicon glyphicon-edit" role="button"></a>
      </td>
    </tr>
    ';
}
echo $output;


问:
Python map function, passing by reference/value?
I have a question about the map function in Python.

From what I understand, the function does not mutate the list it's operating on, but rather create a new one and return it. Is this correct ?

Additionally, I have the following piece of code

```<code>def reflect(p,dir):
  if(dir == 'X'):
    func = lambda (a,b) : (a * -1, b)
   else:
    func = lambda (a,b) : (a, b * -1)
  p = map(func,p)
  print 'got', p
</code>```

points is an array of tuples such as: [(1, 1), (-1, 1), (-1, -1), (1, -1)]

If I call the above function in such a manner:

```<code>print points
reflect(points,'X')
print points
</code>```

the list points does not change. Inside the function though, the print function properly prints what I want.

Could someone maybe point me in some direction where I could learn how all this passing by value / reference etc works in python, and how I could fix the above ? Or maybe I'm trying too hard to emulate Haskell in python...

Thanks

edit:

Say instead of p = map(func,p) I do

```<code>for i in range(len(p)):
  p[i] = func(p[i])
</code>```

The value of the list is updated outside of the function, as if working by reference. Ugh, hope this is clear :S

答:
I want to bump this. The answers don't really answer the question - they disregard the fact that the OP was able to achieve the desired result by iterating. The question comes down to the behavior of map. Here is a more direct example:

```<code>f=(lambda pair: pair[0].append(pair[1]))
a = ([],1)
f(a)
print(a) #prints ([1],1)
a=([],1)
map(f,[a])
print(a) #prints ([0],1)
</code>```

So map isn't mutating objects in the way the OP is expecting. I have the same confusion.

Can anyone comment on exactly what is going on here? I think that'd be a good answer to the OP's question.

Note that we have different behavior if we assign the output of map as follows (as per Cat Plus Plus' answer)

```<code>f=(lambda pair: pair[0].append(pair[1]))
a = ([],1)
x = [a]
x[:] = map(f,x)
print(x) #prints None
print(a) # prints [1]
</code>```

Please note that in the first example, we simply called f(a), not a=f(a). Why do we need assignment when using map and not when working outside of map?

Body:
I have a question about the map function in Python.

From what I understand, the function does not mutate the list it's operating on, but rather create a new one and return it. Is this correct ?

Additionally, I have the following piece of code

def reflect(p,dir):
  if(dir == 'X'):
    func = lambda (a,b) : (a * -1, b)
   else:
    func = lambda (a,b) : (a, b * -1)
  p = map(func,p)
  print 'got', p

points is an array of tuples such as: [(1, 1), (-1, 1), (-1, -1), (1, -1)]

If I call the above function in such a manner:

print points
reflect(points,'X')
print points

the list points does not change. Inside the function though, the print function properly prints what I want.

Could someone maybe point me in some direction where I could learn how all this passing by value / reference etc works in python, and how I could fix the above ? Or maybe I'm trying too hard to emulate Haskell in python...

Thanks

edit:

Say instead of p = map(func,p) I do

for i in range(len(p)):
  p[i] = func(p[i])

The value of the list is updated outside of the function, as if working by reference. Ugh, hope this is clear :S

Body:
I want to bump this. The answers don't really answer the question - they disregard the fact that the OP was able to achieve the desired result by iterating. The question comes down to the behavior of map. Here is a more direct example:

f=(lambda pair: pair[0].append(pair[1]))
a = ([],1)
f(a)
print(a) #prints ([1],1)
a=([],1)
map(f,[a])
print(a) #prints ([0],1)

So map isn't mutating objects in the way the OP is expecting. I have the same confusion.

Can anyone comment on exactly what is going on here? I think that'd be a good answer to the OP's question.

Note that we have different behavior if we assign the output of map as follows (as per Cat Plus Plus' answer)

f=(lambda pair: pair[0].append(pair[1]))
a = ([],1)
x = [a]
x[:] = map(f,x)
print(x) #prints None
print(a) # prints [1]

Please note that in the first example, we simply called f(a), not a=f(a). Why do we need assignment when using map and not when working outside of map?


问:
Sorting the output of a foreach loop by size in java
I have a foreach loop which iterates through a series of words. It needs to print them out by size.

```<code>for (String word : words2) {
    maxLength = 1;
    if(words1.contains(word)&&word.length()>maxLength){
        ++maxLength;
    System.out.print(word + ",\r");
}
</code>```

My question is if there is any way to do this in java?

Thanks

答:
If I understood you correctly you want to sort array of words by word length. To do so you can use stream API of Java 8:

```<code>String arr[] = new String[] {"a", "asd", "as"};
String[] sorted = Arrays.stream(arr)
                      .sorted(Comparator.comparingInt(String::length))
                      .toArray(String[]::new);
</code>```

Or you can just print them straight away:

```<code>Arrays.stream(arr)
      .sorted(Comparator.comparingInt(String::length))
      .forEach(System.out::println);
</code>```

Body:
I have a foreach loop which iterates through a series of words. It needs to print them out by size.

for (String word : words2) {
    maxLength = 1;
    if(words1.contains(word)&&word.length()>maxLength){
        ++maxLength;
    System.out.print(word + ",\r");
}

My question is if there is any way to do this in java?

Thanks

Body:
If I understood you correctly you want to sort array of words by word length. To do so you can use stream API of Java 8:

String arr[] = new String[] {"a", "asd", "as"};
String[] sorted = Arrays.stream(arr)
                      .sorted(Comparator.comparingInt(String::length))
                      .toArray(String[]::new);

Or you can just print them straight away:

Arrays.stream(arr)
      .sorted(Comparator.comparingInt(String::length))
      .forEach(System.out::println);


问:
Posted ViewModel is always NULL
My ViewModel always returns null and don't know why. Can someone look at my code and check what is wrong here and why my filled model with data from view returns to controller as null?

```<code>public class PaintballWorkerCreateViewModel
{
    public PaintballWorker PaintballWorker { get; set; }
    public PaintballWorkerHourlyRate HourlyRate { get; set; }
}
</code>```

Controller

```<code>public ActionResult Create()
{
    PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
    {
        PaintballWorker = new PaintballWorker(),
        HourlyRate = new PaintballWorkerHourlyRate()
        {
            Date = DateTime.Now
        }
    };
    return View(model);
}

[HttpPost]
[PreventSpam(DelayRequest = 20)]
[ValidateAntiForgeryToken]
public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
{
    (...)
}
</code>```

View, even added HiddenFor IDs (which aren't created in GET function in controller).

```<code>@model WerehouseProject.ViewModels.PaintballWorkerCreateViewModel

@{
    ViewBag.Title = "Utwórz pracownika";
    Layout = "~/Views/Shared/_Layout_Paintball.cshtml";
}

<h2>Dodawanie pracownika</h2>

@using (Html.BeginForm("Create", "PaintballWorkers", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.PaintballWorker.Active)
        @Html.HiddenFor(model => model.PaintballWorker.MoneyGot)
        @Html.HiddenFor(model => model.PaintballWorker.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.Date)
        @Html.HiddenFor(model => model.HourlyRate.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.PWHourlyRateID)

        <div class="form-group">
            @Html.LabelFor(model => model.PaintballWorker.Imie, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PaintballWorker.Imie, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PaintballWorker.Imie, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PaintballWorker.Nazwisko, htmlAttributes: new { @class = "control-label col-md-2" })

(...)

        <div class="form-group">
            @Html.LabelFor(model => model.HourlyRate.HourlyRate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.HourlyRate.HourlyRate, new { htmlAttributes = new { @class = "form-control", @type = "number", @min = "0.1", @step = "0.1", @value = "10" } })
                @Html.ValidationMessageFor(model => model.HourlyRate.HourlyRate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Dodaj pracownika" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<div>
@Html.ActionLink("Powrót do listy", "Index", new object { }, new { @class = "btn btn-default" })
</div>
</code>```

答:
Your code looks fine.. looks like it's reference is being lost somewhere.. have you tried to remove the [PreventSpam(DelayRequest = 20)] attribute? So your controller would be like this:

```<code>public ActionResult Create()
    {
            PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
            {
                PaintballWorker = new PaintballWorker(),
                HourlyRate = new PaintballWorkerHourlyRate()
                {
                    Date = DateTime.Now
                }
            };
            return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
    {
        (...)
    }
</code>```

Title: Posted ViewModel is always NULL

Body:
My ViewModel always returns null and don't know why. Can someone look at my code and check what is wrong here and why my filled model with data from view returns to controller as null?

public class PaintballWorkerCreateViewModel
{
    public PaintballWorker PaintballWorker { get; set; }
    public PaintballWorkerHourlyRate HourlyRate { get; set; }
}

Controller

public ActionResult Create()
{
    PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
    {
        PaintballWorker = new PaintballWorker(),
        HourlyRate = new PaintballWorkerHourlyRate()
        {
            Date = DateTime.Now
        }
    };
    return View(model);
}

[HttpPost]
[PreventSpam(DelayRequest = 20)]
[ValidateAntiForgeryToken]
public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
{
    (...)
}

View, even added HiddenFor IDs (which aren't created in GET function in controller).

@model WerehouseProject.ViewModels.PaintballWorkerCreateViewModel

@{
    ViewBag.Title = "Utwórz pracownika";
    Layout = "~/Views/Shared/_Layout_Paintball.cshtml";
}

Dodawanie pracownika

@using (Html.BeginForm("Create", "PaintballWorkers", FormMethod.Post))
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.PaintballWorker.Active)
        @Html.HiddenFor(model => model.PaintballWorker.MoneyGot)
        @Html.HiddenFor(model => model.PaintballWorker.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.Date)
        @Html.HiddenFor(model => model.HourlyRate.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.PWHourlyRateID)

            @Html.LabelFor(model => model.PaintballWorker.Imie, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.PaintballWorker.Imie, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PaintballWorker.Imie, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.PaintballWorker.Nazwisko, htmlAttributes: new { @class = "control-label col-md-2" })

(...)

            @Html.LabelFor(model => model.HourlyRate.HourlyRate, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.HourlyRate.HourlyRate, new { htmlAttributes = new { @class = "form-control", @type = "number", @min = "0.1", @step = "0.1", @value = "10" } })
                @Html.ValidationMessageFor(model => model.HourlyRate.HourlyRate, "", new { @class = "text-danger" })

                <input type="submit" value="Dodaj pracownika" class="btn btn-primary" />

}

@Html.ActionLink("Powrót do listy", "Index", new object { }, new { @class = "btn btn-default" })

Body:
Your code looks fine.. looks like it's reference is being lost somewhere.. have you tried to remove the [PreventSpam(DelayRequest = 20)] attribute? So your controller would be like this:

public ActionResult Create()
    {
            PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
            {
                PaintballWorker = new PaintballWorker(),
                HourlyRate = new PaintballWorkerHourlyRate()
                {
                    Date = DateTime.Now
                }
            };
            return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
    {
        (...)
    }


问:
run selenium with chrome driver on heroku: `cannot find Chrome binary`
I'm a noob as it comes to linux setup (and heroku), so apologies if this question is basic.

I want to run selenium webkit (in ruby) on Heroku. I face a difficulty that my script cannot find Chrome binary file.

I actually got chrome to work by itself:

```<code>~ $ chromedriver
Starting ChromeDriver 2.22.397932 (282ed7cf89cf0053b6542e0d0f039d4123bbb6ad) on port 9515
Only local connections are allowed.
</code>```

chromedriver being a file that I copied from /app/vendor/bundle/bin/chromedriver, just to make it easier for now. chromedriver file there exists because I installed chromedriver-helper gem. The gem was supposed to make the binary file available for ruby processes but didn't.

I've also tried setting path explicitly, e.g. Selenium::WebDriver::Chrome.driver_path = 'chromedriver' in my ruby code, with the aforementioned file located in the root category.

It all works perfectly locally (with or without the driver_path)

What can be the cause? I've read this SO thread from years ago, but it seems outdated to me. Any ideas would be greatly appreciated!

error trace:

```<code>~ $ ruby bin/run.rb
/app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/response.rb:70:in `assert_ok': unknown error: cannot find Chrome binary (Selenium::WebDriver::Error::UnknownError)
  (Driver info: chromedriver=2.22.397932 (282ed7cf89cf0053b6542e0d0f039d4123bbb6ad),platform=Linux 3.13.0-91-generic x86_64)
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/common.rb:78:in `new'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/common.rb:78:in `create_response'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/default.rb:90:in `request'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/common.rb:59:in `call'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/bridge.rb:649:in `raw_execute'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/bridge.rb:123:in `create_session'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/bridge.rb:87:in `initialize'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/chrome/bridge.rb:48:in `initialize'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/common/driver.rb:64:in `new'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/common/driver.rb:64:in `for'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver.rb:84:in `for'
    from /app/lib/mealpass_orderer.rb:12:in `initialize'
    from /app/lib/mealpass_orderer.rb:8:in `new'
    from /app/lib/mealpass_orderer.rb:8:in `run'
    from bin/run.rb:3:in `<main>'
</code>```

UPDATE:

I tried the same with AWS EC2 server (launched instance, cloned git repo, installed all dependencies). The same happens there as well. That is, able to execute chromedriver from terminal, but seeing same error when run the script.

答:
Here's a minimal configuration that's worked for me.  You'll need to have the right buildpacks to install chrome too, it looks like you're only installing chromedriver which is a separate binary.

https://github.com/jormon/minimal-chrome-on-heroku-xvfb

You can test one-button deploy it to Heroku using the button on the README.md.

Let me know how it goes!

Body:
I'm a noob as it comes to linux setup (and heroku), so apologies if this question is basic.

I want to run selenium webkit (in ruby) on Heroku. I face a difficulty that my script cannot find Chrome binary file.

I actually got chrome to work by itself:

~ $ chromedriver
Starting ChromeDriver 2.22.397932 (282ed7cf89cf0053b6542e0d0f039d4123bbb6ad) on port 9515
Only local connections are allowed.

chromedriver being a file that I copied from /app/vendor/bundle/bin/chromedriver, just to make it easier for now. chromedriver file there exists because I installed chromedriver-helper gem. The gem was supposed to make the binary file available for ruby processes but didn't.

I've also tried setting path explicitly, e.g. Selenium::WebDriver::Chrome.driver_path = 'chromedriver' in my ruby code, with the aforementioned file located in the root category.

It all works perfectly locally (with or without the driver_path)

What can be the cause? I've read this SO thread from years ago, but it seems outdated to me. Any ideas would be greatly appreciated!

error trace:

~ $ ruby bin/run.rb
/app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/response.rb:70:in `assert_ok': unknown error: cannot find Chrome binary (Selenium::WebDriver::Error::UnknownError)
  (Driver info: chromedriver=2.22.397932 (282ed7cf89cf0053b6542e0d0f039d4123bbb6ad),platform=Linux 3.13.0-91-generic x86_64)
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/common.rb:78:in `new'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/common.rb:78:in `create_response'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/default.rb:90:in `request'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/common.rb:59:in `call'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/bridge.rb:649:in `raw_execute'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/bridge.rb:123:in `create_session'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/bridge.rb:87:in `initialize'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/chrome/bridge.rb:48:in `initialize'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/common/driver.rb:64:in `new'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/common/driver.rb:64:in `for'
    from /app/vendor/bundle/ruby/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver.rb:84:in `for'
    from /app/lib/mealpass_orderer.rb:12:in `initialize'
    from /app/lib/mealpass_orderer.rb:8:in `new'
    from /app/lib/mealpass_orderer.rb:8:in `run'
    from bin/run.rb:3:in `'

UPDATE:

I tried the same with AWS EC2 server (launched instance, cloned git repo, installed all dependencies). The same happens there as well. That is, able to execute chromedriver from terminal, but seeing same error when run the script.


问:
How do I get started using OpenSeadragon?
I was wondering how to get started with OpenSeadragon. I have it installed through node.js according to the repository readme on github. Then I was looking at the API and it looks like you have to use the OpenSeadragon.Viewer function. But that is as far as I got. I just want to create a simple page with one deep-zooming image using OpenSeadragon.</p>

答:
iangilman's answer is still relevant and useful today. One thing I would add... if you are using Microsoft's Deep Zoom Composer to create your DZI, check the XML file. If it contains DisplayRects, delete them. OpenSeaDragon does not handle them correctly (see https://github.com/openseadragon/openseadragon/issues/1081) and will not display the image at all. Delete the entire section from the XML and everything works fine. There is some conversation about a potential performance impact, but I have not seen that issue myself.

Also, it looks like the height and width are critical - I removed them at one point and the entire image disappeared (0 height and 0 width I presume).


问:
Route application root to /swagger
What is the correct way to redirect request from www.mysite.com to www.mysite.com/swagger?

I setup an index controller Decorated with Route("") and it works but seems like a Kludge. I assume there should be a way to specify it in the MVC routing in Startup.cs, I just can't figure it out.

```<code>// kludge code, how do I do this in app.UseMvc(route => route.MapRoute...
[ApiExplorerSettings(IgnoreApi = true)]
[Route("")]
public class IndexController : Controller
{
    public ActionResult Index()
    {
        return Redirect("/swagger");
    }
}
</code>```

答:
Try the following redirect rule:</p>

```<code>var option = new RewriteOptions();
option.AddRedirect("^$", "swagger");

app.UseRewriter(option);
</code>```

Title: Route application root to /swagger

Body:
What is the correct way to redirect request from www.mysite.com to www.mysite.com/swagger?

I setup an index controller Decorated with Route("") and it works but seems like a Kludge. I assume there should be a way to specify it in the MVC routing in Startup.cs, I just can't figure it out.

// kludge code, how do I do this in app.UseMvc(route => route.MapRoute...
[ApiExplorerSettings(IgnoreApi = true)]
[Route("")]
public class IndexController : Controller
{
    public ActionResult Index()
    {
        return Redirect("/swagger");
    }
}

Body:
Try the following redirect rule:

var option = new RewriteOptions();
option.AddRedirect("^$", "swagger");

app.UseRewriter(option);


问:
No package autocomplete in asp.net core .csproj?
Previously, we used the project.json to setup our projects dependencies. The Asp.net Core team moved away from that and went back to using .csproj. However, when trying to type in the name of a package, it no longer auto-completes like it used to.

For instance, typing in the following line would show intellisense when I typed the . after Microsoft, providing me with the packages within that namespace.

```<code><PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" PrivateAssets="All" />
</code>```

How do I get this functionality back?

答:
This will probably depend on which IDE you are using.

If you're using Visual Studio then you'd right click on dependencies or csproj then click "Manage Nuget Packages".

This will open a view where you can search for packages and install them.

If you're using Visual Studio Code, there are couple of plugins that'll help you search and add packages you're looking for.

https://marketplace.visualstudio.com/items?itemName=jmrog.vscode-nuget-package-manager

Lets you search package and add specific version.

Body:
Previously, we used the project.json to setup our projects dependencies. The Asp.net Core team moved away from that and went back to using .csproj. However, when trying to type in the name of a package, it no longer auto-completes like it used to.

For instance, typing in the following line would show intellisense when I typed the . after Microsoft, providing me with the packages within that namespace.

<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" PrivateAssets="All" />

How do I get this functionality back?


答:
If you have an array you could use Java 8 to sort them as follows:

```<code>String[] words = "This is the phrase I want to split by length".split(" ");
Arrays.sort(words, (word1, word2) -> Integer.compare(word1.length(), word2.length()));

for (String s : words) {
    System.out.println(s);
}
</code>```

Which produces the following output:

```<code>I
is
to
by
the
This
want
split
phrase
length
</code>```

OR a better approach as suggested by @Andreas in the comments below:

```<code>Arrays.sort(words, Comparator.comparingInt(String::length));
</code>```

Title: Sorting the output of a foreach loop by size in java

Body:
If you have an array you could use Java 8 to sort them as follows:

String[] words = "This is the phrase I want to split by length".split(" ");
Arrays.sort(words, (word1, word2) -> Integer.compare(word1.length(), word2.length()));

for (String s : words) {
    System.out.println(s);
}

Which produces the following output:

I
is
to
by
the
This
want
split
phrase
length

OR a better approach as suggested by @Andreas in the comments below:

Arrays.sort(words, Comparator.comparingInt(String::length));


问:
Reference HTML input text from control
Is there a way to reference the value of the current control if it an input text?

```<code>foreach (Control c in line1.Controls)
{
    if (c.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlInputText")
    {
        c.ID.Value() = "test";
    }
}
</code>```

I have a HTML page and I want to loop through the controls, and set their value in the loop. Am I going about this all wrong? I can't find a way to reference the HTmlInputText from a control?

答:
You can check the Control with is

```<code>foreach (Control c in line1.Controls)
{
    //check if the control is a textbox
    if (c is TextBox)
    {
        //cast it back to a textbox to access its properies
        TextBox tb = c as TextBox;
        tb.Text = "TextBox found";

        //or set the id
        c.ID = "test";
    }
}
</code>```

Or a generic control

```<code>foreach (Control c in line1.Controls)
{
    //check if the control is a HtmlInputControl
    if (c is HtmlInputControl)
    {
        //cast it back to a HtmlInputControl to access its properies
        HtmlInputControl hic = c as HtmlInputControl;
        hic.Value = "HTML TextBox found";

        //or set the id
        c.ID = "test";
    }
}
</code>```

Title: Reference HTML input text from control

Body:
Is there a way to reference the value of the current control if it an input text?

foreach (Control c in line1.Controls)
{
    if (c.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlInputText")
    {
        c.ID.Value() = "test";
    }
}

I have a HTML page and I want to loop through the controls, and set their value in the loop. Am I going about this all wrong? I can't find a way to reference the HTmlInputText from a control?

Body:
You can check the Control with is

foreach (Control c in line1.Controls)
{
    //check if the control is a textbox
    if (c is TextBox)
    {
        //cast it back to a textbox to access its properies
        TextBox tb = c as TextBox;
        tb.Text = "TextBox found";

        //or set the id
        c.ID = "test";
    }
}

Or a generic control

foreach (Control c in line1.Controls)
{
    //check if the control is a HtmlInputControl
    if (c is HtmlInputControl)
    {
        //cast it back to a HtmlInputControl to access its properies
        HtmlInputControl hic = c as HtmlInputControl;
        hic.Value = "HTML TextBox found";

        //or set the id
        c.ID = "test";
    }
}


问:
How to enforce a formal protocol with C++ templates?
When using the compile-time duck typing inherent with the template style, is there any way to enforce the requirement that the template argument implements certain methods with certain signatures?

```<code>struct ProtocolT {
  void g() const;
  void h();
}

// I want the compiler to check that T conforms to ProtocolT
// that is, T must implement g() and h() rather than just g()
template <typename T>
void f(const T& x) {
  x.g();
}
</code>```

Of course, even without this, there is perfect type safety: if the template argument  T does not have a method used in the template function implementation, the compiler will always complain.

But I find it appealing to state clearly that class T must have all the methods specified in some class ProtocolT. It would allow me to constrain the design earlier in the development process by requiring methods from T that I don't yet use in the template function implementation.

Even if I didn't include any unused methods in ProtocolT, I still think a verified protocol conformance would help when I need to write a class usable as T. (Of course, no one stops me from writing ProtocolT for documentation purposes, but then the compiler won't validate that ProtocolT includes at least all the required methods.)

答:
The feature you are looking for is known as concepts. They are currently a technical specification; GCC has an implementation of concepts lite.

Using concepts would look something like (I'm not too familiar with the syntax, so it would probably be slightly different):

```<code>template <typename T>
concept bool Protocol = requires(const T a, T b) {
  { a.g() } -> void;
  { b.h() } -> void;
};

void f(const Protocol& x) {
  x.g();
}
</code>```

However, if you want a solution you can use right now, you can emulate concepts with a variety of techniques.

You could write type-traits to detect if a function does what you want.

You could also use the detection idiom, which abstracts the previous technique, greatly reducing boilerplate. For your example:

```<code>template <typename T>
using g_t = decltype(std::declval<const T&>().g());

template <typename T>
using h_t = decltype(std::declval<T&>().h());

template <typename T>
constexpr bool meets_protocol_v = std::experimental::is_detected_exact_v<void, g_t, T>
            && std::experimental::is_detected_exact_v<void, h_t, T>;
</code>```

In using it, you could either be SFINAE friendly and SFINAE off of meets_protocol_v, or you could static assert:

```<code>template <typename T>
void f(const T& x) {
  static_assert(meets_protocol_v<T>, "Doesn't meet protocol");
  x.g();
}
</code>```

Body:
When using the compile-time duck typing inherent with the template style, is there any way to enforce the requirement that the template argument implements certain methods with certain signatures?

struct ProtocolT {
  void g() const;
  void h();
}

// I want the compiler to check that T conforms to ProtocolT
// that is, T must implement g() and h() rather than just g()
template <typename T>
void f(const T& x) {
  x.g();
}

Of course, even without this, there is perfect type safety: if the template argument  T does not have a method used in the template function implementation, the compiler will always complain.

But I find it appealing to state clearly that class T must have all the methods specified in some class ProtocolT. It would allow me to constrain the design earlier in the development process by requiring methods from T that I don't yet use in the template function implementation.

Even if I didn't include any unused methods in ProtocolT, I still think a verified protocol conformance would help when I need to write a class usable as T. (Of course, no one stops me from writing ProtocolT for documentation purposes, but then the compiler won't validate that ProtocolT includes at least all the required methods.)

Body:
The feature you are looking for is known as concepts. They are currently a technical specification; GCC has an implementation of concepts lite.

Using concepts would look something like (I'm not too familiar with the syntax, so it would probably be slightly different):

template <typename T>
concept bool Protocol = requires(const T a, T b) {
  { a.g() } -> void;
  { b.h() } -> void;
};

void f(const Protocol& x) {
  x.g();
}

However, if you want a solution you can use right now, you can emulate concepts with a variety of techniques.

You could write type-traits to detect if a function does what you want.

You could also use the detection idiom, which abstracts the previous technique, greatly reducing boilerplate. For your example:

template <typename T>
using g_t = decltype(std::declval<const T&>().g());

template <typename T>
using h_t = decltype(std::declval<T&>().h());

template <typename T>
constexpr bool meets_protocol_v = std::experimental::is_detected_exact_v<void, g_t, T>
            && std::experimental::is_detected_exact_v<void, h_t, T>;

In using it, you could either be SFINAE friendly and SFINAE off of meets_protocol_v, or you could static assert:

template <typename T>
void f(const T& x) {
  static_assert(meets_protocol_v<T>, "Doesn't meet protocol");
  x.g();
}


问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答:
I suggest PHP as a good starting framework for many small hobby web apps:

It is simple and easy to learn

It is well documented and mature

It takes virtually no time to save changes and see them in the browser

There are lots of inexpensive hosting options

Your development environment is free and quick to setup

OwnerDisplayName: nagul

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic


问:
Detect undefined symbols in C header file
Suposse I coded a C library which provides a bunch of "public" functions, declared in a mylib.h header file. Those functions are supposedly implemented in (say) a mylib.c file which is compiled to a (say) static lib mylib.c -> mylib.o -> mylib.a.

Is there some way to detect that I forgot to provide the implementation of some declared function in mylib.h? (Yes, I know about unit testing, good practices, etc - and, yes, I understand the meaning of a plain function declaration in C).

Suppose mylib.h declares a void func1(); and this function was not coded in the provided library. This will trigger an error only  if the linker needs to use that function. Otherwise, it will compile ok and even without warnings - AFAIK. Is there a way (perhaps compiler dependent) to trigger a warning for declared but not implemented functions, or there is any other way to deal with this issue?

BTW: nm -u lists not all undefined declared functions, but only those "used" by the library, i.e., those functions that will trigger an error in the linking phase if not declared somewhere. (Which makes sense, the library object file does not know about header files, of course.)

答:
Basically, the most reliable way is to have a program (or possibly a series of programs) which formally exercise each and every one of the functions.  If one of the programs fails to link because of a missing symbol, you've goofed.

I suppose you could try to do something by editing a copy of the header into a source file (as in, file ending .c), converting the function declarations into dummy function definitions:

Original:

```<code>extern int somefunc(void);
</code>```

Revised:

```<code>extern int somefunc(void){}
</code>```

Then compile the modified source with minimum warnings - and ignore anything to do with "function that is supposed to return a value doesn't".  Then compare the defined symbols in the object file from the revised source with the defined symbols in the library (using nm -g on Unix-like systems).  Anything present in the object file that isn't present in the library is missing and should be supplied.

Note: if your header includes other headers of your own which define functions, you need to process all of those.  If your header includes standard headers such as <stdio.h>, then clearly you won't be defining functions such as fopen() or printf() in the ordinary course of events.  So, choose the headers you reprocess into source code carefully.

Body:
Basically, the most reliable way is to have a program (or possibly a series of programs) which formally exercise each and every one of the functions.  If one of the programs fails to link because of a missing symbol, you've goofed.

I suppose you could try to do something by editing a copy of the header into a source file (as in, file ending .c), converting the function declarations into dummy function definitions:

Original:

extern int somefunc(void);

Revised:

extern int somefunc(void){}

Then compile the modified source with minimum warnings - and ignore anything to do with "function that is supposed to return a value doesn't".  Then compare the defined symbols in the object file from the revised source with the defined symbols in the library (using nm -g on Unix-like systems).  Anything present in the object file that isn't present in the library is missing and should be supplied.

Note: if your header includes other headers of your own which define functions, you need to process all of those.  If your header includes standard headers such as <stdio.h>, then clearly you won't be defining functions such as fopen() or printf() in the ordinary course of events.  So, choose the headers you reprocess into source code carefully.


问:
localhost does not process php script correctly
I am learning about databases and GUI to make database management more user friendly. I successfully downloaded wampserver (3.0) and mysql (5.7). To test if the php prints "Hello world" (see PHP script below).

Script (saved as name.php)

```<code>>?
echo "Hello world";
?<
</code>```

My output in the browser is:

```<code>>?
echo "Hello world";
?<
</code>```

Can someone give advise me on what the problem is, and how I can fix it?

答:
If you want to work with your databases using a web GUI once you have installed WAMP you can open up any web browser (be it firefox or chrome or whatever) and in he address bar write http://localhost/phpmyadmin or simply localhost/phpmyadmin . If you did not set any password during setup for your database the default credentials are user 'root' and no password. Phpmyadmin is a very user friendly web GUI for managing mysql databases that comes with basic setups of wamp and xampp

Also if you want to verify if php was installed correctly from a console window you can type php -i which would display info aboout your current version/setup/extensions installed/etc.

Body:
I am learning about databases and GUI to make database management more user friendly. I successfully downloaded wampserver (3.0) and mysql (5.7). To test if the php prints "Hello world" (see PHP script below).

Script (saved as name.php)

>?
echo "Hello world";
?<

My output in the browser is:

>?
echo "Hello world";
?<

Can someone give advise me on what the problem is, and how I can fix it?


问:
GoJS undo a change of category property that is binding to the shape fill property
I need to change the category value dinamically.

The code:

```<code>diagram.startTransaction('changing state: ' + node.data.text);
model.setDataProperty(node.data, 'category', 'stateInitial');
diagram.commitTransaction('changing state: ' + node.data.text);
</code>```

Node Template:

```<code>$(go.Shape, 'RoundedRectangle',
    { stroke: null , strokeWidth: 0 },
    new go.Binding("fill", "category", function(category){

         if( category == 'stateInitial'){
              return '#99AE3B';
          }
          else if(category == 'stateFinal'){
              return '#E53935';
          }
          return '#6699CC';
      })
    ), . . .
</code>```

This works OK, the node change its colour dinamcally.

But, After doing this:

```<code>diagram.undoManager.undo();
</code>```

The node switch to previous category in the model (this is OK) but I don't see the change of colour back to the previous colour.
Only diagram.rebuildParts() method works, but I can't use it.

Any idea?

答:
Categories (templates) are special. Try using Model.setCategoryForNodeData instead when changing node categories.

If you are not changing node templates, pick a different data property name than "category", since it has other meanings in GoJS models.

Body:
I need to change the category value dinamically.

The code:

diagram.startTransaction('changing state: ' + node.data.text);
model.setDataProperty(node.data, 'category', 'stateInitial');
diagram.commitTransaction('changing state: ' + node.data.text);

Node Template:

$(go.Shape, 'RoundedRectangle',
    { stroke: null , strokeWidth: 0 },
    new go.Binding("fill", "category", function(category){

         if( category == 'stateInitial'){
              return '#99AE3B';
          }
          else if(category == 'stateFinal'){
              return '#E53935';
          }
          return '#6699CC';
      })
    ), . . .

This works OK, the node change its colour dinamcally.

But, After doing this:

diagram.undoManager.undo();

The node switch to previous category in the model (this is OK) but I don't see the change of colour back to the previous colour.
Only diagram.rebuildParts() method works, but I can't use it.

Any idea?


问:
How to get access token for google oauth?
I am using C# (ASP.NET). I want to use Google OAuth for accessing the user profile detail in my app. I successfully got the authorization code but having a problem in getting the access token.
I prefer the Google tutorials. In tutorial, I read that I have to send the request and get the response from google. For that, I use System.Net.HttpWebRequest/HttpWebResponse (am I going in the right way). I have used this code...

```<code>byte[] buffer = Encoding.ASCII.GetBytes("?code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://accounts.google.com");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buffer.Length;

Stream strm = req.GetRequestStream();
strm.Write(buffer, 0, buffer.Length);
strm.Close();

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Response.Write(((HttpWebResponse)resp).StatusDescription);
</code>```

But, I got the error:

The remote server returned an error: (405) Method Not Allowed.

Update: Here variable code is authorization code.

答:
```<code>public string ReceiveTokenGmail(string code, string GoogleWebAppClientID, string GoogleWebAppClientSecret, string RedirectUrl)
{
    string postString = "code=" + code + "&client_id=" + GoogleWebAppClientID + @"&client_secret=" + GoogleWebAppClientSecret  + "&redirect_uri=" + RedirectUrl;

    string url = "https://accounts.google.com/o/oauth2/token";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    UTF8Encoding utfenc = new UTF8Encoding();
    byte[] bytes = utfenc.GetBytes(postString);
    Stream os = null;
    try
    {
        request.ContentLength = bytes.Length;
        os = request.GetRequestStream();
        os.Write(bytes, 0, bytes.Length);
    }
    catch
    { }
    string result = "";

    HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
    Stream responseStream = webResponse.GetResponseStream();
    StreamReader responseStreamReader = new StreamReader(responseStream);
    result = responseStreamReader.ReadToEnd();

    return result;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using C# (ASP.NET). I want to use Google OAuth for accessing the user profile detail in my app. I successfully got the authorization code but having a problem in getting the access token.
I prefer the Google tutorials. In tutorial, I read that I have to send the request and get the response from google. For that, I use System.Net.HttpWebRequest/HttpWebResponse (am I going in the right way). I have used this code...

byte[] buffer = Encoding.ASCII.GetBytes("?code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://accounts.google.com");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buffer.Length;

Stream strm = req.GetRequestStream();
strm.Write(buffer, 0, buffer.Length);
strm.Close();

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Response.Write(((HttpWebResponse)resp).StatusDescription);

But, I got the error:

The remote server returned an error: (405) Method Not Allowed.

Update: Here variable code is authorization code.


问:
Regex capture consecutive numbers in a pattern
Trying to extract the numbers from a string of pattern:
<Some Alphanumeric> <numbers> X <numbers> <Some Alphanumeric>

e.g.
I 00 Crazy 060 X 0140 08 Dance 47

should extract the numbers 060 and 0140 and the text I 00 Crazy and 08 Dance 47

I'm using the following Regex:
(.*)(\d{1,3})\s*(x|X)\s*(\d{1,4})(.*)

However this isn't working on the first number preceding the X, it's only capturing 0 instead of 060 but captures the second number 0140 correctly.

\d{1,3} should be a greedy capture of digits between 1 and 3 in length - so what am I missing here?

答:
This should work,

```<code>(.*)\b(\d{1,3})\s*(x|X)\s*(\d{1,4})(.*)
</code>```

Here, \b asserts position at a word boundary (^\w|\w$|\W\w|\w\W)

Body:
This should work,

(.*)\b(\d{1,3})\s*(x|X)\s*(\d{1,4})(.*)

Here, \b asserts position at a word boundary (^\w|\w$|\W\w|\w\W)


问:
C++ a class to be used only by another class
I'm building a class (class A) which needs to be able to create a number of instances of another class (class B) in the course of its operation, but class B is only used by a few member functions of class A, and never used outside of the class. How should class B best be defined? Is it practical / reasonable to make it a private member of Class A? Is this the intended purpose of nested classes, or am I parting with the spirit of the construct?

Thanks,
Wyatt

EDIT: On further consideration, I'm not really asking about best practice, as this is for a personal project. I want to include class B as a member of class A from an encapsulation standpoint - it just seems reasonable that a class which is wholly subordinate should in fact be a part of its owning class.

What I'm wondering is whether or not this is a reasonable use-case for nested classes? If not, what is the purpose of nested classes?

答:
A general rule of thumb for me is that if I find I have a difficult problem with inheritance then I've probably looked at the problem in the wrong way.

Is there a way you can restructure your program so the classes are less "coupled"?
I.E. Can you move the functions out of class A that reference class B (and place them in B)?


问:
Actionscript: BlitMask stopping mouse event listeners from working, how to fix?
I have a button class which contains event listeners to trigger an animation of the button on click.

I used many instances of this class to form a list which the user can scroll through. I have implemented BlitMask, this works, however the mouse event listeners in the button class no longer work. This code

```<code>_blit = new BlitMask(_mc, _obounds.x, _bounds.y, _bounds.width, _bounds.height, false);
</code>```

Is what stops the button class.

How can I get the behaviour pre blitmark?

My code which creates the bottom is

```<code>var tf:TextField = new TextField(text);
tf.x = 70;
tf.y = 20;
_btn.addChild(tf);
_btn.addEventListener(MouseEvent.CLICK, click);
</code>```

click is never called.

答:
The blitmask causes the movieclip to be nothing more than an image of clip.

bitmapMode must be set to false to correct this.

```<code>_blitMask.bitmapMode = false;
</code>```

EDIT: To expand on a further issue that implementing this solution causes, turning bitmapMode on only when needed causes the bitmap to not reflect changes in the classes that changed while bitmapMode was off. So you must set

```<code>_blitMask.update(null, true);
</code>```

To force a full update when you use

```<code>_blitMask.bitmapMode = true;
</code>```

Body:
I have a button class which contains event listeners to trigger an animation of the button on click.

I used many instances of this class to form a list which the user can scroll through. I have implemented BlitMask, this works, however the mouse event listeners in the button class no longer work. This code

_blit = new BlitMask(_mc, _obounds.x, _bounds.y, _bounds.width, _bounds.height, false);

Is what stops the button class.

How can I get the behaviour pre blitmark?

My code which creates the bottom is

var tf:TextField = new TextField(text);
tf.x = 70;
tf.y = 20;
_btn.addChild(tf);
_btn.addEventListener(MouseEvent.CLICK, click);

click is never called.

Body:
The blitmask causes the movieclip to be nothing more than an image of clip.

bitmapMode must be set to false to correct this.

_blitMask.bitmapMode = false;

EDIT: To expand on a further issue that implementing this solution causes, turning bitmapMode on only when needed causes the bitmap to not reflect changes in the classes that changed while bitmapMode was off. So you must set

_blitMask.update(null, true);

To force a full update when you use

_blitMask.bitmapMode = true;


问:
Python Formatting Output
I have the following code:

```<code>import options
import random

class Player():
    def __init__(self):
        self.name = None
        self.gold = 100
        self.maxhealth = 100
        self.health = self.maxhealth
        self.level = 1
        self.exp = 0
        self.levelUp = 50
        self.gainedexp = self.levelUp - self.exp

    def get_name(self):
        self.name = input("Hey there, traveller! What's your name?\n~~>")
        print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))

    def gold_counter(self):
        print("You currently have {} gold!".format(player.gold))

class Dragon():
    def __init__(self):
        self.name = "Dragon"
        self.dropgold = random.randint(13,20)
        self.minexp = int(15 * round(player.level * 1.5))
        self.maxexp = int(30 * round(player.level * 1.5))
        self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
        self.maxhealth = 80
        self.health = self.maxhealth

def intro():
    wrong_input = 0
    nar_name = "Narrator"
    print("{}: Uhhhm...".format(nar_name))
    print("{}: Let me check my list...".format(nar_name))
    print("{0}: Ah! Yes! {1}, that's right. I heard you were supposed to be arriving today.".format(nar_name, player.name))
</code>```

I am also using two other modules, but I'm 99% sure they don't affect this. I get the following output:

```<code>Hey there, traveller! What's your name?
~~>Savage Potato
Since you are new around here, 100 gold doubloons have been given to you, Savage Potato!
Do you want to see your balance?
~~> Yes
You currently have 100 gold.
Narrator: Uhhhm...
Narrator: Let me check my list...
Narrator: Ah! Yes! None, that's right. I heard you were supposed to be arriving today.
</code>```

In the last line, it is printing out the Narrator's name, but not the user's inputted name. I also looked at the python documents on their website, but I couldn't find a fix. Any ideas on how I could stop it from outputting None as the user's name?

EDIT #1: I have player = Player() written later in the module.

EDIT #2: This is all the code I used:

 Module 1 (main.py)

```<code>import prints
import random

class Player():
    def __init__(self):
        self.name = None
        self.gold = 100
        self.maxhealth = 100
        self.health = self.maxhealth
        self.level = 1
        self.exp = 0
        self.levelUp = 50
        self.gainedexp = self.levelUp - self.exp

    def get_name(self):
        self.name = input("Hey there, traveller! What's your name?\n~~>")
        print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))

class Dragon():
    def __init__(self):
        self.name = "Dragon"
        self.dropgold = random.randint(13,20)
        self.minexp = int(15 * round(player.level * 1.5))
        self.maxexp = int(30 * round(player.level * 1.5))
        self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
        self.maxhealth = 80
        self.health = self.maxhealth

#while player.exp >= player.levelUp:
    #player.levelUp += 1
    #player.exp = player.exp - player.levelUp
    #player.levelUp = round(player.levelUp * 1.5)
    #print("Congrats! You just levelled up to level {} by gaining {} experience!".format(player.level, player.gainedexp))

def start():
    player.get_name()
    prints.gold_counter()
    prints.intro()
    prints.encounter()

player = Player()

start()
</code>```

 Module 2 (prints.py)

```<code>import options
import random

class Player():
    def __init__(self):
        self.name = None
        self.gold = 100
        self.maxhealth = 100
        self.health = self.maxhealth
        self.level = 1
        self.exp = 0
        self.levelUp = 50
        self.gainedexp = self.levelUp - self.exp

    def get_name(self):
        self.name = input("Hey there, traveller! What's your name?\n~~>")
        print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))

    def gold_counter(self):
        print("You currently have {} gold!".format(player.gold))

class Dragon():
    def __init__(self):
        self.name = "Dragon"
        self.dropgold = random.randint(13,20)
        self.minexp = int(15 * round(player.level * 1.5))
        self.maxexp = int(30 * round(player.level * 1.5))
        self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
        self.maxhealth = 80
        self.health = self.maxhealth

def intro():
    wrong_input = 0
    nar_name = "Narrator"
    print("{}: Uhhhm...".format(nar_name))
    print("{}: Let me check my list...".format(nar_name))
    print("{0}: Ah! Yes! {1}, that's right. I heard you were supposed to be arriving today.".format(nar_name, player.name))
    print("{}: Welcome to... THE DRAGON FIGHTER GAME!".format(nar_name))
    print("{}: I know, it isn't the most imaginative name.".format(nar_name))
    print("{}: Don't look at me like that, I tried my hardest!".format(nar_name))
    print("{}: Anyhoo, let's carry on.".format(nar_name))
    print("{}: For some stupid reason, the creator of this game didn't give me an actual name, so\nmy name is just \"Narrator\" or \"N\", but you can call me Larry.".format(nar_name))
    while True:
        option = input("Narrator: Actually, which name would you prefer to call me?\n").upper()
        if option in options.nar_larry_opt:
            nar_name = "Larry"
        elif option in options.nar_narrator_opt:
            nar_name = "Narrator"
            while True:
                ask = input("{}: Maybe \"N\" for short?".format(nar_name)).upper()
                if ask in options.inp_yes_opt:
                    nar_name = "N"
                elif ask in options.inp_no_opt:
                    break
                else:
                    wrong_input += 1
                    if wrong_input == 1:
                        print("Please try again.")
                    elif wrong_input == 2:
                        print("Try to not put the same thing in next time.")
                    elif wrong_input == 3:
                        print("This isn't funny.")
                    elif wrong_input == 4:
                        print("Seriously.")
                    elif wrong_input == 5:
                        print("OKAY! THIS IS IT! GO BACK TO THE BEGINNING!")
                        intro()

                    continue
                break
        else:
            print("Please try again.")
            continue
        break
    print("{}: So, as I was saying, this game is basically just some dragon quest thingy.".format(nar_name))
    print("{}: You'll probably get tips from me every now and again if I can be bothered.".format(nar_name))
    print("{}: I'll get an test encounter ready.".format(nar_name))

def gold_counter():
    while True:
        option = input("Do you want to see your balance?\n~~> ").upper()
        if option in options.inp_yes_opt:
            print("You currently have {} gold.".format(player.gold))
        elif option in options.inp_no_opt:
            print("You can check your balance later in the game.")
        else:
            print("Please try again.")
            continue
        break

def encounter():
    while True:
        dragon_appear = random.randint(1,2)
        if dragon_appear == 1:
            print("What's that? Looks like a huge bir... \nA DRAGON! A MAJESTIC DRAGON JUST FLEW DOWN FROM THE SKY!")
        else:
            print("What's that? Looks like a huge bir... \n Yeah. Just a giganta-bird.")

    while encounter().dragon_appear != 2:
        print("So that's the message you'll get when a dragon appears.")
        print("And you will be prompted whether you want to run or fight, like so:")
        while True:
            wrong_input = 0
            ask = input("Run away like a coward, or fight the majestic beast?")
            if ask in options.enc_run_opt:
                escape = random.randint(1,2)
                if escape == 1:
                    print("You managed to get away!")
                else:
                    print("You didn't get away. Better luck next time!")
            elif ask in options.enc_attack_opt:
                pass
            else:
                wrong_input += 1
                if wrong_input == 1:
                    print("Please try again.")
                elif wrong_input == 2:
                    print("Try to not put the same thing in next time.")
                elif wrong_input == 3:
                    print("This isn't funny.")
                elif wrong_input == 4:
                    print("Seriously.")
                continue
            break

player = Player()
</code>```

 Module 3 (options.py)

```<code>inp_yes_opt = {"Y", "YE", "YES", "YEAH", "PLEASE", "YES PLEASE"}
inp_no_opt = {"N", "NO", "NOPE", "NAH"}

nar_larry_opt = {"LARRY", "LARR", "LAR", "LA", "L", "LARRY PLEASE"}
nar_narrator_opt = {"NARRATOR", "NARR", "N", "NAR", "NARRATE", "NOT LARRY"}

enc_run_opt = {"RUN", "RU", "R", "SCRAM", "RUN AWAY", "RUUUUN"}
enc_attack_opt = {"ATTACK", "ATTAK", "A", "FIGHT", "F", "ATTACK", ""}
</code>```

答:
If you want to print out the name of the player , you need to pass in the player object to the intro function as a parameter. That assumes intro is not capturing the player object and the player object is not global

At the moment , it seems there is no player object accessible to the scope of the function which is why it outputs None

Title: Python Formatting Output

Body:
I have the following code:

import options
import random

class Player():
    def __init__(self):
        self.name = None
        self.gold = 100
        self.maxhealth = 100
        self.health = self.maxhealth
        self.level = 1
        self.exp = 0
        self.levelUp = 50
        self.gainedexp = self.levelUp - self.exp

    def get_name(self):
        self.name = input("Hey there, traveller! What's your name?\n~~>")
        print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))

    def gold_counter(self):
        print("You currently have {} gold!".format(player.gold))

class Dragon():
    def __init__(self):
        self.name = "Dragon"
        self.dropgold = random.randint(13,20)
        self.minexp = int(15 * round(player.level * 1.5))
        self.maxexp = int(30 * round(player.level * 1.5))
        self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
        self.maxhealth = 80
        self.health = self.maxhealth

def intro():
    wrong_input = 0
    nar_name = "Narrator"
    print("{}: Uhhhm...".format(nar_name))
    print("{}: Let me check my list...".format(nar_name))
    print("{0}: Ah! Yes! {1}, that's right. I heard you were supposed to be arriving today.".format(nar_name, player.name))

I am also using two other modules, but I'm 99% sure they don't affect this. I get the following output:

Hey there, traveller! What's your name?
~~>Savage Potato
Since you are new around here, 100 gold doubloons have been given to you, Savage Potato!
Do you want to see your balance?
~~> Yes
You currently have 100 gold.
Narrator: Uhhhm...
Narrator: Let me check my list...
Narrator: Ah! Yes! None, that's right. I heard you were supposed to be arriving today.

In the last line, it is printing out the Narrator's name, but not the user's inputted name. I also looked at the python documents on their website, but I couldn't find a fix. Any ideas on how I could stop it from outputting None as the user's name?

EDIT #1: I have player = Player() written later in the module.

EDIT #2: This is all the code I used:

 Module 1 (main.py)

import prints
import random

class Player():
    def __init__(self):
        self.name = None
        self.gold = 100
        self.maxhealth = 100
        self.health = self.maxhealth
        self.level = 1
        self.exp = 0
        self.levelUp = 50
        self.gainedexp = self.levelUp - self.exp

    def get_name(self):
        self.name = input("Hey there, traveller! What's your name?\n~~>")
        print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))

class Dragon():
    def __init__(self):
        self.name = "Dragon"
        self.dropgold = random.randint(13,20)
        self.minexp = int(15 * round(player.level * 1.5))
        self.maxexp = int(30 * round(player.level * 1.5))
        self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
        self.maxhealth = 80
        self.health = self.maxhealth

#while player.exp >= player.levelUp:
    #player.levelUp += 1
    #player.exp = player.exp - player.levelUp
    #player.levelUp = round(player.levelUp * 1.5)
    #print("Congrats! You just levelled up to level {} by gaining {} experience!".format(player.level, player.gainedexp))

def start():
    player.get_name()
    prints.gold_counter()
    prints.intro()
    prints.encounter()

player = Player()

start()

 Module 2 (prints.py)

import options
import random

class Player():
    def __init__(self):
        self.name = None
        self.gold = 100
        self.maxhealth = 100
        self.health = self.maxhealth
        self.level = 1
        self.exp = 0
        self.levelUp = 50
        self.gainedexp = self.levelUp - self.exp

    def get_name(self):
        self.name = input("Hey there, traveller! What's your name?\n~~>")
        print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))

    def gold_counter(self):
        print("You currently have {} gold!".format(player.gold))

class Dragon():
    def __init__(self):
        self.name = "Dragon"
        self.dropgold = random.randint(13,20)
        self.minexp = int(15 * round(player.level * 1.5))
        self.maxexp = int(30 * round(player.level * 1.5))
        self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
        self.maxhealth = 80
        self.health = self.maxhealth

def intro():
    wrong_input = 0
    nar_name = "Narrator"
    print("{}: Uhhhm...".format(nar_name))
    print("{}: Let me check my list...".format(nar_name))
    print("{0}: Ah! Yes! {1}, that's right. I heard you were supposed to be arriving today.".format(nar_name, player.name))
    print("{}: Welcome to... THE DRAGON FIGHTER GAME!".format(nar_name))
    print("{}: I know, it isn't the most imaginative name.".format(nar_name))
    print("{}: Don't look at me like that, I tried my hardest!".format(nar_name))
    print("{}: Anyhoo, let's carry on.".format(nar_name))
    print("{}: For some stupid reason, the creator of this game didn't give me an actual name, so\nmy name is just \"Narrator\" or \"N\", but you can call me Larry.".format(nar_name))
    while True:
        option = input("Narrator: Actually, which name would you prefer to call me?\n").upper()
        if option in options.nar_larry_opt:
            nar_name = "Larry"
        elif option in options.nar_narrator_opt:
            nar_name = "Narrator"
            while True:
                ask = input("{}: Maybe \"N\" for short?".format(nar_name)).upper()
                if ask in options.inp_yes_opt:
                    nar_name = "N"
                elif ask in options.inp_no_opt:
                    break
                else:
                    wrong_input += 1
                    if wrong_input == 1:
                        print("Please try again.")
                    elif wrong_input == 2:
                        print("Try to not put the same thing in next time.")
                    elif wrong_input == 3:
                        print("This isn't funny.")
                    elif wrong_input == 4:
                        print("Seriously.")
                    elif wrong_input == 5:
                        print("OKAY! THIS IS IT! GO BACK TO THE BEGINNING!")
                        intro()

                    continue
                break
        else:
            print("Please try again.")
            continue
        break
    print("{}: So, as I was saying, this game is basically just some dragon quest thingy.".format(nar_name))
    print("{}: You'll probably get tips from me every now and again if I can be bothered.".format(nar_name))
    print("{}: I'll get an test encounter ready.".format(nar_name))

def gold_counter():
    while True:
        option = input("Do you want to see your balance?\n~~> ").upper()
        if option in options.inp_yes_opt:
            print("You currently have {} gold.".format(player.gold))
        elif option in options.inp_no_opt:
            print("You can check your balance later in the game.")
        else:
            print("Please try again.")
            continue
        break

def encounter():
    while True:
        dragon_appear = random.randint(1,2)
        if dragon_appear == 1:
            print("What's that? Looks like a huge bir... \nA DRAGON! A MAJESTIC DRAGON JUST FLEW DOWN FROM THE SKY!")
        else:
            print("What's that? Looks like a huge bir... \n Yeah. Just a giganta-bird.")

    while encounter().dragon_appear != 2:
        print("So that's the message you'll get when a dragon appears.")
        print("And you will be prompted whether you want to run or fight, like so:")
        while True:
            wrong_input = 0
            ask = input("Run away like a coward, or fight the majestic beast?")
            if ask in options.enc_run_opt:
                escape = random.randint(1,2)
                if escape == 1:
                    print("You managed to get away!")
                else:
                    print("You didn't get away. Better luck next time!")
            elif ask in options.enc_attack_opt:
                pass
            else:
                wrong_input += 1
                if wrong_input == 1:
                    print("Please try again.")
                elif wrong_input == 2:
                    print("Try to not put the same thing in next time.")
                elif wrong_input == 3:
                    print("This isn't funny.")
                elif wrong_input == 4:
                    print("Seriously.")
                continue
            break

player = Player()

 Module 3 (options.py)

inp_yes_opt = {"Y", "YE", "YES", "YEAH", "PLEASE", "YES PLEASE"}
inp_no_opt = {"N", "NO", "NOPE", "NAH"}

nar_larry_opt = {"LARRY", "LARR", "LAR", "LA", "L", "LARRY PLEASE"}
nar_narrator_opt = {"NARRATOR", "NARR", "N", "NAR", "NARRATE", "NOT LARRY"}

enc_run_opt = {"RUN", "RU", "R", "SCRAM", "RUN AWAY", "RUUUUN"}
enc_attack_opt = {"ATTACK", "ATTAK", "A", "FIGHT", "F", "ATTACK", ""}


问:
CGImage, NSArray and Memory
This is a multiple part question, mostly because my ignorance on the matter has multiple layers.

First, I put together a caching system for caching CGImageRef objects. I keep it at the CGImageRef level (rather than UIImage) as I am loading images in background threads. When an image is loaded I put it into a NSMutableDictionary. I had to do a bit of arm twisting to get CGImageRef's into the array:

```<code>//Bunch of stuff drawing into a context
CGImageRef imageRef = CGBitmapContextCreateImage(context);

CGContextRelease(context);
[(id)imageRef autorelease];
[self.cache setObject:(id)imageRef forKey:@"SomeKey"];
</code>```

So, as you can see, I'm trying to treat the Image Ref as an NSObject, setting it to autorelease then placing it in the dictionary. My expectation is this will allow the image to be cleaned up after being removed from the dictionary. Now, I am beginning to have my doubts.

My application clears the cache array when the user "restarts" to play with different images. Running the application in Instruments shows that the memory is not dropping back to the "start" level on restart, but instead remains steady. My gut tells me that when the array has all objects removed the CGImageRef is not being cleared.

However, I'm unable to confirm this as I don't quite know how to track down the actual source of the memory in instruments. It's just a list of (Malloc 16 Bytes, Malloc 32 Bytes, etc), drilling into them just show a list of dyld callers. Not sure how to properly read it.

So, first question, is my way of caching CGImageRef objects completely flawed? And is there a better way to confirm such things in instruments?

答:
Why not just cache UIImage objects; you can make them fine on a background thread?

It's UIImageView objects that you have to be more careful with and even they are OK for most operations in the background.

Title: CGImage, NSArray and Memory

Body:
This is a multiple part question, mostly because my ignorance on the matter has multiple layers.

First, I put together a caching system for caching CGImageRef objects. I keep it at the CGImageRef level (rather than UIImage) as I am loading images in background threads. When an image is loaded I put it into a NSMutableDictionary. I had to do a bit of arm twisting to get CGImageRef's into the array:

//Bunch of stuff drawing into a context
CGImageRef imageRef = CGBitmapContextCreateImage(context);

CGContextRelease(context);
[(id)imageRef autorelease];
[self.cache setObject:(id)imageRef forKey:@"SomeKey"];

So, as you can see, I'm trying to treat the Image Ref as an NSObject, setting it to autorelease then placing it in the dictionary. My expectation is this will allow the image to be cleaned up after being removed from the dictionary. Now, I am beginning to have my doubts.

My application clears the cache array when the user "restarts" to play with different images. Running the application in Instruments shows that the memory is not dropping back to the "start" level on restart, but instead remains steady. My gut tells me that when the array has all objects removed the CGImageRef is not being cleared.

However, I'm unable to confirm this as I don't quite know how to track down the actual source of the memory in instruments. It's just a list of (Malloc 16 Bytes, Malloc 32 Bytes, etc), drilling into them just show a list of dyld callers. Not sure how to properly read it.

So, first question, is my way of caching CGImageRef objects completely flawed? And is there a better way to confirm such things in instruments?


问:
Installing NodeJS on Ubuntu 16.04 Server with the Package manager installs only the distro version (v.4) instead of LTS
I have this odd problem that when I try to install NodeJS on a fresh Ubuntu Server VM.

I execute the two simple steps from the official instruction but somehow I manage to fail.

In the home directory of my user I execute curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - which ends successfully and then sudo apt-get install -y nodejs but this results in the installation of v.4.2.6.

Output can be seen below:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  nodejs
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/3161 kB of archives.
After this operation, 13,2 MB of additional disk space will be used.
Selecting previously unselected package nodejs.
(Reading database ... 97187 files and directories currently installed.)
Preparing to unpack .../nodejs_4.2.6~dfsg-1ubuntu4.1_amd64.deb ...
Unpacking nodejs (4.2.6~dfsg-1ubuntu4.1) ...
Processing triggers for man-db (2.7.5-1) ...
Setting up nodejs (4.2.6~dfsg-1ubuntu4.1) ...
update-alternatives: using /usr/bin/nodejs to provide /usr/bin/js (js) in auto mode
</code>```

Please help.

答: You probably have to run sudo apt-get update before sudo apt-get install to update the local package lists after adding the sources for 6.x. If you do that, you should see version 6 being installed.

Body:
I have this odd problem that when I try to install NodeJS on a fresh Ubuntu Server VM.

I execute the two simple steps from the official instruction but somehow I manage to fail.

In the home directory of my user I execute curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - which ends successfully and then sudo apt-get install -y nodejs but this results in the installation of v.4.2.6.

Output can be seen below:

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  nodejs
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/3161 kB of archives.
After this operation, 13,2 MB of additional disk space will be used.
Selecting previously unselected package nodejs.
(Reading database ... 97187 files and directories currently installed.)
Preparing to unpack .../nodejs_4.2.6~dfsg-1ubuntu4.1_amd64.deb ...
Unpacking nodejs (4.2.6~dfsg-1ubuntu4.1) ...
Processing triggers for man-db (2.7.5-1) ...
Setting up nodejs (4.2.6~dfsg-1ubuntu4.1) ...
update-alternatives: using /usr/bin/nodejs to provide /usr/bin/js (js) in auto mode

Please help.