问:
Converting user input to uppercase
I am attempting to create a program in Unix that accesses a data file, adding, deleting, and searching within the file for names and usernames. With this if statement, I am attempting to allow the user to search for data in the file by the first field.

All of the data in the file uses uppercase letters, so I first must convert any text the user input from lowercase to uppercase letters. For some reason, this code is not working with both converting to uppercase and searching and printing the data.

How can I fix it?

```<code>if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
        tput cup 3 12
        echo "Enter the first name of the user you would like to search for: "
        tput cup 4 12; read search | tr '[a-z]' '[A-Z]'
        echo "$search"
        awk -F ":" '$1 == "$search" {print $3 " " $1 " " $2 }'
        capstonedata.txt
fi
</code>```

答:
If you use Bash, you can declare a variable to convert to uppercase:

```<code>$ declare -u search
$ read search <<< 'lowercase'
$ echo "$search"
LOWERCASE
</code>```

As for your code, read doesn't have any output, so piping to tr doesn't do anything, and you can't have a newline before the file name in the awk statement.

Edited version of your code, minus all the tput stuff:

```<code># [[ ]] to enable pattern matching, no need to quote here
if [[ $choice = [Ss] ]]; then

    # Declare uppercase variable
    declare -u search

    # Read with prompt
    read -p "Enter the first name of the user you would like to search for: " search
    echo "$search"

    # Proper way of getting variable into awk
    awk -F ":" -v s="$search" '$1 == s {print $3 " " $1 " " $2 }' capstonedata.txt
fi
</code>```

Alternatively, if you want to use only POSIX shell constructs:

```<code>case $choice in
    [Ss] )
        printf 'Enter the first name of the user you would like to search for: '
        read input
        search=$(echo "$input" | tr '[[:lower:]]' '[[:upper:]]')
        awk -F ":" -v s="$search" '$1 == s {print $3 " " $1 " " $2 }' capstonedata.txt
    ;;
esac
</code>```

Title: Converting user input to uppercase

Body:
I am attempting to create a program in Unix that accesses a data file, adding, deleting, and searching within the file for names and usernames. With this if statement, I am attempting to allow the user to search for data in the file by the first field.

All of the data in the file uses uppercase letters, so I first must convert any text the user input from lowercase to uppercase letters. For some reason, this code is not working with both converting to uppercase and searching and printing the data.

How can I fix it?

if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
        tput cup 3 12
        echo "Enter the first name of the user you would like to search for: "
        tput cup 4 12; read search | tr '[a-z]' '[A-Z]'
        echo "$search"
        awk -F ":" '$1 == "$search" {print $3 " " $1 " " $2 }'
        capstonedata.txt
fi

Body:
If you use Bash, you can declare a variable to convert to uppercase:

$ declare -u search
$ read search <<< 'lowercase'
$ echo "$search"
LOWERCASE

As for your code, read doesn't have any output, so piping to tr doesn't do anything, and you can't have a newline before the file name in the awk statement.

Edited version of your code, minus all the tput stuff:

# [[ ]] to enable pattern matching, no need to quote here
if [[ $choice = [Ss] ]]; then

    # Declare uppercase variable
    declare -u search

    # Read with prompt
    read -p "Enter the first name of the user you would like to search for: " search
    echo "$search"

    # Proper way of getting variable into awk
    awk -F ":" -v s="$search" '$1 == s {print $3 " " $1 " " $2 }' capstonedata.txt
fi

Alternatively, if you want to use only POSIX shell constructs:

case $choice in
    [Ss] )
        printf 'Enter the first name of the user you would like to search for: '
        read input
        search=$(echo "$input" | tr '[[:lower:]]' '[[:upper:]]')
        awk -F ":" -v s="$search" '$1 == s {print $3 " " $1 " " $2 }' capstonedata.txt
    ;;
esac


来源: stackexchange

问:
I get an error that looks like this : parse error: syntax error, unexpected ';' on line 18
i am getting this error :
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\loginsystem\includes\signup.inc.php on line 18

```<code>        <?php

    if (isset($_POST['Submit'])) {

        include_once 'dbh.inc.php';

        $first = mysqli_real_escape_string($conn, $_POST['first']);
        $last = mysqli_real_escape_string($conn, $_POST['last']);
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $uid = mysqli_real_escape_string($conn, $_POST['uid']);
        $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

        //error handlers
        // check for empty fields

        if (empty($first)) (empty($last)) (empty($email)) (empty($uid)) (empty($pwd)) {

            header ("location: ../signup.php?signup=empty");
            exit();

        } else {
            //check if input characters are valid
            if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last) {

                header("location: ../signup.php?signup=invalid");
                exit();

            } else {
            // check if eimal is valid
                if (!filter_var($email, FILTER_VALIDATE_EMAIL))

                    header("location: ../signup.php?Signup=email");
                    exit();
            } else {
                $sql = "SELECT * FROM users WHERE user_uid='$uid'";
                $result = mysqli_query($conn, $sql);
                $resultCheck = mysqli_num_rows($result);

                if ($resultCheck > 0) {

                    header("location: ../signup.php?signup=usernametaken");
                    exit();
                } else {
                    //Hashing th password
                    $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);

                    //Insert the user into the database
                    $sq l= "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$emial', '$uid','$hashedPwd');";

                    mysqli_query($conn, $sql);
                    header("location: ../signup.php?signup=success");
                    exit();
                }
            }
        }

    }   else {
        header("location: ../signup.php");
        exit();
</code>```

when i take the semicolon away i get this error:
Parse error: syntax error, unexpected 'exit' (T_EXIT) in C:\xampp\htdocs\loginsystem\includes\signup.inc.php on line 19

If somone can please help me i would appreciate it.

thanks

答:
Your code is full of syntax errors in your IF statements.

Change them to this:

```<code>if ((empty($first))  (empty($last))  (empty($email))  (empty($uid))  (empty($pwd))) {
</code>```

AND

```<code>if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
</code>```

AND

```<code> if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
</code>```

AND HERE - you're assignment has a space in the name..

```<code> $sq l= "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$emial', '$uid','$hashedPwd');";
</code>```

SHOULD BE

```<code>$sql = "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$emial', '$uid','$hashedPwd');";
</code>```

There are probably other syntax errors too...

Good Luck.

ContentLicense: CC BY-SA 3.0

Body:
i am getting this error :
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\loginsystem\includes\signup.inc.php on line 18

        <?php

    if (isset($_POST['Submit'])) {

        include_once 'dbh.inc.php';

        $first = mysqli_real_escape_string($conn, $_POST['first']);
        $last = mysqli_real_escape_string($conn, $_POST['last']);
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $uid = mysqli_real_escape_string($conn, $_POST['uid']);
        $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

        //error handlers
        // check for empty fields

        if (empty($first)) (empty($last)) (empty($email)) (empty($uid)) (empty($pwd)) {

            header ("location: ../signup.php?signup=empty");
            exit();

        } else {
            //check if input characters are valid
            if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last) {

                header("location: ../signup.php?signup=invalid");
                exit();

            } else {
            // check if eimal is valid
                if (!filter_var($email, FILTER_VALIDATE_EMAIL))

                    header("location: ../signup.php?Signup=email");
                    exit();
            } else {
                $sql = "SELECT * FROM users WHERE user_uid='$uid'";
                $result = mysqli_query($conn, $sql);
                $resultCheck = mysqli_num_rows($result);

                if ($resultCheck > 0) {

                    header("location: ../signup.php?signup=usernametaken");
                    exit();
                } else {
                    //Hashing th password
                    $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);

                    //Insert the user into the database
                    $sq l= "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$emial', '$uid','$hashedPwd');";

                    mysqli_query($conn, $sql);
                    header("location: ../signup.php?signup=success");
                    exit();
                }
            }
        }

    }   else {
        header("location: ../signup.php");
        exit();

when i take the semicolon away i get this error:
Parse error: syntax error, unexpected 'exit' (T_EXIT) in C:\xampp\htdocs\loginsystem\includes\signup.inc.php on line 19

If somone can please help me i would appreciate it.

thanks

Body:
Your code is full of syntax errors in your IF statements.

Change them to this:

if ((empty($first))  (empty($last))  (empty($email))  (empty($uid))  (empty($pwd))) {

AND

if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {

AND

 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

AND HERE - you're assignment has a space in the name..

 $sq l= "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$emial', '$uid','$hashedPwd');";

SHOULD BE

$sql = "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$emial', '$uid','$hashedPwd');";

There are probably other syntax errors too...

Good Luck.


问:
Isometric offset and mouse positioning

I'm in the process of building a isometric framework so far I've got the physical tile mapping algorithm down.

The thing is I don't want per tile collision, as in looping through all the tiles to check if my mouse is selecting a specific tile.
What I tried to accomplish is get cell index from the mouse using this.

```<code>int col = (int)(((double)mouse_x / (double)tileWidth) - ((double)mouse_y / (double)tileHeight) - 0.5);
int row = (int)(((double)mouse_y / (double)tileHeight) + ((double)mouse_x / (double)tileWidth) - 0.5);
</code>```

But using this method my 0,15 is the 0,0 according to the mouse and the 0,0 is the 0,15.
So my question is how can I swap that around by editing the mouse code perhaps using offset?
Even so I wouldn't know how, so my question is how.

答:
From isometric coordinates to screen coordinates:

```<code>screenX = (isoX - isoY + isoMapMaxY) * (tileWidth / 2);
screenY = (isoX + isoY) * (tileHeight / 2);
</code>```

From screen coordinates to isometric coordinates:

```<code>isoX = ( ((screenY + scrollY) / tileHeight) + ((screenX + scrollX) - (isoMapMaxY * tileWidth/2)) / tileWidth )
isoY = ( ((screenY + scrollY) / tileHeight) - ((screenX + scrollX) - (isoMapMaxY * tileWidth/2)) / tileWidth )

isoX = (screenY / 32) + (screenX - 320) / 64
isoY = (screenY / 32) - (screenX - 320) / 64
</code>```

Title: Isometric offset and mouse positioning

Body:
I'm in the process of building a isometric framework so far I've got the physical tile mapping algorithm down.

The thing is I don't want per tile collision, as in looping through all the tiles to check if my mouse is selecting a specific tile.
What I tried to accomplish is get cell index from the mouse using this.

int col = (int)(((double)mouse_x / (double)tileWidth) - ((double)mouse_y / (double)tileHeight) - 0.5);
int row = (int)(((double)mouse_y / (double)tileHeight) + ((double)mouse_x / (double)tileWidth) - 0.5);

But using this method my 0,15 is the 0,0 according to the mouse and the 0,0 is the 0,15.
So my question is how can I swap that around by editing the mouse code perhaps using offset?
Even so I wouldn't know how, so my question is how.

Body:
From isometric coordinates to screen coordinates:

screenX = (isoX - isoY + isoMapMaxY) * (tileWidth / 2);
screenY = (isoX + isoY) * (tileHeight / 2);

From screen coordinates to isometric coordinates:

isoX = ( ((screenY + scrollY) / tileHeight) + ((screenX + scrollX) - (isoMapMaxY * tileWidth/2)) / tileWidth )
isoY = ( ((screenY + scrollY) / tileHeight) - ((screenX + scrollX) - (isoMapMaxY * tileWidth/2)) / tileWidth )

isoX = (screenY / 32) + (screenX - 320) / 64
isoY = (screenY / 32) - (screenX - 320) / 64


问:
Python 3.x A program thats control if some requirments true
My purpose with this program is to take input from student and make sure that
he/she typed 3 digit number. Neither less than 3 or greater than 3 and it shouldnt be string. All this above  if something wrong, program should ask again until its become true </p>

```<code>def studentID():
       try:
           number=int(input("sutedent IDS:"))
           try:
                assert len(number)==3

           except AssertionError:
               print("Must be 3 digit number.")
               studentID()

       except ValueError:
           print("Please enter an integer.")
           studentID()

       except TypeError:
           print("What is wrong with you?")
           studentID()
</code>```

答:
to add to Patrick's comment, i would prefer range(len(3)), it's clear and it's also more efficient.
How I would do tho</p>

```<code>def studentID():
       number=int(input("sutedent IDS:"))
       if range(len(number)) == 3:
           return studentID()
        elif number is not int or range(len(number)) > 3 :
             print('please enter a valid number')
             return studentID()
        else:
             raise ValueError
             return studentID()
</code>```

Body:
My purpose with this program is to take input from student and make sure that
he/she typed 3 digit number. Neither less than 3 or greater than 3 and it shouldnt be string. All this above  if something wrong, program should ask again until its become true

def studentID():
       try:
           number=int(input("sutedent IDS:"))
           try:
                assert len(number)==3

           except AssertionError:
               print("Must be 3 digit number.")
               studentID()

       except ValueError:
           print("Please enter an integer.")
           studentID()

       except TypeError:
           print("What is wrong with you?")
           studentID()

Body:
to add to Patrick's comment, i would prefer range(len(3)), it's clear and it's also more efficient.
How I would do tho

def studentID():
       number=int(input("sutedent IDS:"))
       if range(len(number)) == 3:
           return studentID()
        elif number is not int or range(len(number)) > 3 :
             print('please enter a valid number')
             return studentID()
        else:
             raise ValueError
             return studentID()


问:
Value cannot be null. Parameter name: items (in Dropdown List) ASP.NET MVC5
I have problem in my code. I'm using the registration form which comes with MVC5 , I added a field "Role" as a Dropdownlist to assign a role to the user while creating a new user. like in the below image:

Now in order to do that, I modified the "RegisterViewModel" and added the following properties:

        public IdentityRole Role { get; set; }

        [Required]
        [Display(Name = "Roles List")]
        public IEnumerable<IdentityRole> RolesList { get; set; }
```

<p>In "AccountController", I changed the Register action, that gets the registration form, to become like this:</p>

<pre class="lang-C# prettyprint-override"><code>// GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {

            var _context = new ApplicationDbContext();
            var roles = _context.Roles.ToList();

            var viewModel = new RegisterViewModel
            {
                RolesList = roles
            };
            return View(viewModel);

        }
</code>```

In the view "Register.cshtml" I added this Dropdownlist to load roles in the view and to post the role to the controller:

        @Html.LabelFor(m => m.Role.Id, new { @class = "col-md-2 control-label" })

            @Html.DropDownListFor(m => m.Role, new SelectList(Model.RolesList, "Name", "Name"), "Select Role", new { @class = "form-control" })

```

<p>in the Register controller, in the the registration form post, I added this</p>

<pre class="lang-C# prettyprint-override"><code>// POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName , centerName = model.centerName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var role = new IdentityRole(model.Role.Name);

                    //I added this line to store the user and its roles in AspNetUserRoles table:
                    await UserManager.AddToRoleAsync(user.Id, role.Name);

                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }
</code>```

Now when I try to register the user and post the form, I get following error:

Server Error in '/' Application.

Value cannot be null.
Parameter name: items

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: items

Source Error:

Line 41:         @Html.LabelFor(m => m.Role.Name, new { @class = "col-md-2 control-label" })
Line 42:

Line 43:             @Html.DropDownListFor(m => m.Role, new SelectList(Model.RolesList, "Name", "Name"), "Select Role", new { @class = "form-control" })
Line 44:

Line 45:

Source File: c:..\TransactionsSystem\Views\Account\Register.cshtml    Line: 43
```

I tried different solutions to solve it, but nothing worked, can anybody please help or advise?

答:
The solution that worked for me in MVC5 for editing an existing user

Model (part of)

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

View

```<code>@Html.DropDownListFor(model => model.UserRole, new SelectList(Model.Roles, Model.UserRole), new { @class = "form-control" })
</code>```

Controller (Get)

```<code> var model = new EditUserViewModel()
        {
            UserName = user.UserName,
            Email = user.Email,
            IsEnabled = user.IsEnabled,
            Id = user.Id,
            PhoneNumber = user.PhoneNumber,
            UserRole = userRoleName,

            // a list of all roles
            Roles = from r in RoleManager.Roles orderby r.Name select r.Name
        };
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have problem in my code. I'm using the registration form which comes with MVC5 , I added a field "Role" as a Dropdownlist to assign a role to the user while creating a new user. like in the below image:

Now in order to do that, I modified the "RegisterViewModel" and added the following properties:

        public IdentityRole Role { get; set; }

        [Required]
        [Display(Name = "Roles List")]
        public IEnumerable<IdentityRole> RolesList { get; set; }

In "AccountController", I changed the Register action, that gets the registration form, to become like this:

// GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {

            var _context = new ApplicationDbContext();
            var roles = _context.Roles.ToList();

            var viewModel = new RegisterViewModel
            {
                RolesList = roles
            };
            return View(viewModel);

        }

In the view "Register.cshtml" I added this Dropdownlist to load roles in the view and to post the role to the controller:

        @Html.LabelFor(m => m.Role.Id, new { @class = "col-md-2 control-label" })

            @Html.DropDownListFor(m => m.Role, new SelectList(Model.RolesList, "Name", "Name"), "Select Role", new { @class = "form-control" })

in the Register controller, in the the registration form post, I added this

// POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName , centerName = model.centerName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var role = new IdentityRole(model.Role.Name);

                    //I added this line to store the user and its roles in AspNetUserRoles table:
                    await UserManager.AddToRoleAsync(user.Id, role.Name);

                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

Now when I try to register the user and post the form, I get following error:

Server Error in '/' Application.

Value cannot be null.
Parameter name: items

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: items

Source Error:

Line 41:         @Html.LabelFor(m => m.Role.Name, new { @class = "col-md-2 control-label" })
Line 42:

Line 43:             @Html.DropDownListFor(m => m.Role, new SelectList(Model.RolesList, "Name", "Name"), "Select Role", new { @class = "form-control" })
Line 44:

Line 45:

Source File: c:..\TransactionsSystem\Views\Account\Register.cshtml    Line: 43

I tried different solutions to solve it, but nothing worked, can anybody please help or advise?

Body:
The solution that worked for me in MVC5 for editing an existing user

Model (part of)

public IEnumerable<string> Roles { get; set; }

View

@Html.DropDownListFor(model => model.UserRole, new SelectList(Model.Roles, Model.UserRole), new { @class = "form-control" })

Controller (Get)

 var model = new EditUserViewModel()
        {
            UserName = user.UserName,
            Email = user.Email,
            IsEnabled = user.IsEnabled,
            Id = user.Id,
            PhoneNumber = user.PhoneNumber,
            UserRole = userRoleName,

            // a list of all roles
            Roles = from r in RoleManager.Roles orderby r.Name select r.Name
        };


问:
Why does this function result in ['h', '-', '-', '-', '-']?
The function hangman_guessed(guessed, secret) is supposed to take a string of guessed characters and a list of "secret" characters.

The function checks every character in the secret list and compares it with each character in the guessed character string to check if the character is in both. If the characters are not the same then the function places a - in a temporary list equal to the secret list (so that we can still compare other characters in the guessed list to the original secret list later).

```<code>def hangman_guessed(guessed, secret):
    modified = secret
    for i1 in range(len(secret)):
        for i2 in range(len(guessed)):
            if secret[i1] == guessed[i2]:
                modified[i1] = secret[i1]
                break
            else:
                modified[i1] = '-'
    return modified
</code>```

For example, when I run hangman_guessed('hl', ['h','e','l','l','o']), it should return ['h', '-', 'l', 'l', '-'], but currently it returns ['h', '-', '-', '-', '-'].

The problem here is that only the first character in the guessed list is considered, but I do not know why. It this case, it is expected that the program checks over the 'l' characters in ['h','e','l','l','o']) and sets the corresponding characters in the temporary list modified to -, but to my understanding after the for loop runs again and checks the original secret list for l characters it should overwrite the - in the modified list and the result should have the 'l' characters rather than the - characters.

答:
A list-comprehension is perfectly suited to what you want to do. We want to create a list of each character (let this be i) in secret if i is in guessed else we want to have a hyphen ("-").

```<code>def hangman_guessed(guessed, secret):
    return [i if i in guessed else "-" for i in secret]
</code>```

and a test to show it works:

```<code>>>> hangman_guessed('hl', ['h','e','l','l','o'])
['h', '-', 'l', 'l', '-']
</code>```

As you get more used to the flow of Python, you will find that comprehensions in general are extremely useful as well as being very readable for a whole variety of things.

If for some reason however, you had to use nested for-loops and weren't allowed to use the really simple in operator, then you need to / can make a couple of corrections to your current code:

make a copy of the secret list first

iterate through the characters in guessed, rather than the indexes

After making these two corrections, the function will look something like:

```<code>def hangman_guessed(guessed, secret):
    modified = secret[:]
    for i in range(len(secret)):
        for g in guessed:
            if secret[i] == g:
                modified[i] = secret[i]
                break
            else:
                modified[i] = '-'
    return modified
</code>```

which now works:

```<code>>>> hangman_guessed('hl', ['h','e','l','l','o'])
['h', '-', 'l', 'l', '-']
</code>```

Body:
The function hangman_guessed(guessed, secret) is supposed to take a string of guessed characters and a list of "secret" characters.

The function checks every character in the secret list and compares it with each character in the guessed character string to check if the character is in both. If the characters are not the same then the function places a - in a temporary list equal to the secret list (so that we can still compare other characters in the guessed list to the original secret list later).

def hangman_guessed(guessed, secret):
    modified = secret
    for i1 in range(len(secret)):
        for i2 in range(len(guessed)):
            if secret[i1] == guessed[i2]:
                modified[i1] = secret[i1]
                break
            else:
                modified[i1] = '-'
    return modified

For example, when I run hangman_guessed('hl', ['h','e','l','l','o']), it should return ['h', '-', 'l', 'l', '-'], but currently it returns ['h', '-', '-', '-', '-'].

The problem here is that only the first character in the guessed list is considered, but I do not know why. It this case, it is expected that the program checks over the 'l' characters in ['h','e','l','l','o']) and sets the corresponding characters in the temporary list modified to -, but to my understanding after the for loop runs again and checks the original secret list for l characters it should overwrite the - in the modified list and the result should have the 'l' characters rather than the - characters.

Body:
A list-comprehension is perfectly suited to what you want to do. We want to create a list of each character (let this be i) in secret if i is in guessed else we want to have a hyphen ("-").

def hangman_guessed(guessed, secret):
    return [i if i in guessed else "-" for i in secret]

and a test to show it works:

>>> hangman_guessed('hl', ['h','e','l','l','o'])
['h', '-', 'l', 'l', '-']

As you get more used to the flow of Python, you will find that comprehensions in general are extremely useful as well as being very readable for a whole variety of things.

If for some reason however, you had to use nested for-loops and weren't allowed to use the really simple in operator, then you need to / can make a couple of corrections to your current code:

make a copy of the secret list first

iterate through the characters in guessed, rather than the indexes

After making these two corrections, the function will look something like:

def hangman_guessed(guessed, secret):
    modified = secret[:]
    for i in range(len(secret)):
        for g in guessed:
            if secret[i] == g:
                modified[i] = secret[i]
                break
            else:
                modified[i] = '-'
    return modified

which now works:

>>> hangman_guessed('hl', ['h','e','l','l','o'])
['h', '-', 'l', 'l', '-']


问:
onMetadataChanged MediaControllerCompat.Callback never called
I'm developing a simple Audio Player app for a radio station.

I have successfully made a MediaBrowser and registered a callback to listen for playBack- or metadata changes.

```<code>var mediaBrowser : MediaBrowserCompat by Delegates.notNull()
mediaBrowser = MediaBrowserCompat(
        activity,
        ComponentName(activity, MediaPlaybackService::class.java),
        object : MediaBrowserCompat.ConnectionCallback() {
            override fun onConnected() {
                val mediaController = MediaControllerCompat(activity, mediaBrowser.sessionToken)
                MediaControllerCompat.setMediaController(activity, mediaController)
                mediaController.registerCallback(ControllerCallback)
                mediaControllerFunc()
            }
        },
        null
)

object ControllerCallback : MediaControllerCompat.Callback() {
    override fun onMetadataChanged(metadata: MediaMetadataCompat) {
        //TODO: Never called
    }

    override fun onPlaybackStateChanged(state: PlaybackStateCompat) {
        //Called
    }
}
</code>```

The playback changes are received when I call

```<code>mediaSession.setPlaybackState(
    PlaybackStateCompat.Builder()
            .setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE)
            .setState(STATE_PLAYING, DEFAULT_PLAYBACK_POSITION, DEFAULT_PLAYBACK_SPEED)
            .build()
)
</code>```

However metadata changes are not.

Even though I call

```<code>mediaSession.setMetadata(
    MediaMetadataCompat.Builder()
        .putLong(METADATA_KEY_DURATION, -1)
        .putString(METADATA_KEY_TITLE, title)
        .putString(METADATA_KEY_ARTIST, artist)
        .putBitmap(METADATA_KEY_ALBUM_ART, albumCover)
        .putString(METADATA_KEY_ALBUM_ART_URI, albumCoverUrl)
        .build()
)
</code>```

What am I missing to receive metadata changes?

If it can help the complete repository is available on Github

Thanks in advance

答:
My solution for anybody experiencing the same problem.

It turned out I was mixing compat (service layer responsible for starting the audio service and connection to metadata) and non compat (UI layer) variants of the API.

In particular the activity.

Since I am targeting Lollipop and higher I decided to use Activity instead of the AppCompatActivity.

This apparently silently breaks the MediaControllerCompat.Callback for onMetadataChanged(), but not for onPlaybackStateChanged().

Can't seem to find why?!

In code it is as simple as changing:

class PlayableActivity : Activity() { ... }

to:

class PlayableActivity : AppCompatActivity() { ... }

Body:
I'm developing a simple Audio Player app for a radio station.

I have successfully made a MediaBrowser and registered a callback to listen for playBack- or metadata changes.

var mediaBrowser : MediaBrowserCompat by Delegates.notNull()
mediaBrowser = MediaBrowserCompat(
        activity,
        ComponentName(activity, MediaPlaybackService::class.java),
        object : MediaBrowserCompat.ConnectionCallback() {
            override fun onConnected() {
                val mediaController = MediaControllerCompat(activity, mediaBrowser.sessionToken)
                MediaControllerCompat.setMediaController(activity, mediaController)
                mediaController.registerCallback(ControllerCallback)
                mediaControllerFunc()
            }
        },
        null
)

object ControllerCallback : MediaControllerCompat.Callback() {
    override fun onMetadataChanged(metadata: MediaMetadataCompat) {
        //TODO: Never called
    }

    override fun onPlaybackStateChanged(state: PlaybackStateCompat) {
        //Called
    }
}

The playback changes are received when I call

mediaSession.setPlaybackState(
    PlaybackStateCompat.Builder()
            .setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE)
            .setState(STATE_PLAYING, DEFAULT_PLAYBACK_POSITION, DEFAULT_PLAYBACK_SPEED)
            .build()
)

However metadata changes are not.

Even though I call

mediaSession.setMetadata(
    MediaMetadataCompat.Builder()
        .putLong(METADATA_KEY_DURATION, -1)
        .putString(METADATA_KEY_TITLE, title)
        .putString(METADATA_KEY_ARTIST, artist)
        .putBitmap(METADATA_KEY_ALBUM_ART, albumCover)
        .putString(METADATA_KEY_ALBUM_ART_URI, albumCoverUrl)
        .build()
)

What am I missing to receive metadata changes?

If it can help the complete repository is available on Github

Thanks in advance


问:
Java Decimal to binary using toBinaryString() method
I want to convert decimal number to binary, but this code doesn't work.</p>

```<code>class DecimalToBinary{

public static void main(String a[]){
    System.out.println("Binary: ");
    System.out.println(Integer.toBinaryChar(200));
    System.out.println("\nBinary: ");
    System.out.println(Integer.toBinaryChar(500));
    System.out.println("\nBinary: ");
    System.out.println(Integer.toBinaryChar(3400));
    }
}
</code>```

答:
You should use Integer.toBinaryString(200) instead of System.out.println(Integer.toBinaryChar(200));.

```<code>public class DecimalToBinary{

        public static void main(String a[]){
            System.out.println("Binary: ");
            System.out.println(Integer.toBinaryString(200));
            System.out.println("\nBinary: ");
            System.out.println(Integer.toBinaryString(500));
            System.out.println("\nBinary: ");
            System.out.println(Integer.toBinaryString(3400));
        }
}
</code>```

Body:
I want to convert decimal number to binary, but this code doesn't work.

class DecimalToBinary{

public static void main(String a[]){
    System.out.println("Binary: ");
    System.out.println(Integer.toBinaryChar(200));
    System.out.println("\nBinary: ");
    System.out.println(Integer.toBinaryChar(500));
    System.out.println("\nBinary: ");
    System.out.println(Integer.toBinaryChar(3400));
    }
}

Body:
You should use Integer.toBinaryString(200) instead of System.out.println(Integer.toBinaryChar(200));.

public class DecimalToBinary{

        public static void main(String a[]){
            System.out.println("Binary: ");
            System.out.println(Integer.toBinaryString(200));
            System.out.println("\nBinary: ");
            System.out.println(Integer.toBinaryString(500));
            System.out.println("\nBinary: ");
            System.out.println(Integer.toBinaryString(3400));
        }
}


问:
How to Render Two Components Conditionally?

How can I render these two components conditionally?

import React, { Component } from 'react';
import { Container, Header, Content, Card, CardItem, Text, Body } from 'native-base';
export default class CardHeaderFooterExample extends Component {
  render() {

    return (
      <Card>
        <CardItem header>
          <Text>NativeBase</Text>
        </CardItem>
        <CardItem>

            <Text>
              //Your text here
            </Text>

        </CardItem>
        <CardItem footer>
          <Text>GeekyAnts</Text>
        </CardItem>
      </Card>
```

<p>lets say:  </p>

<pre class="lang-js prettyprint-override"><code>if logedin={true}
  return
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>
        <Body>
          <Text>
            //Your text here
          </Text>
        </Body>
      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

else return

  <Text> signup to access this content </Text>
</code>```

How can be this conditional rendering be done for this situation? Those components should be rendered based on boolean logedin.

答:
You can achieve this in multiple ways.

Using multiple returns

```<code>render()
{
  if(!logedin){
    return <Text> Signup to access this content </Text>;
  }

  return( <CardComponent/> );
}
</code>```

Using ternary operator

condition ? statement to execute if condition is true : statement to execute if condition is false

```<code>    render()
    {
       return islogedin ? <CardComponent/> : <Text> Signup to access this content </Text>;
    }
</code>```

Body:
How can I render these two components conditionally?

import React, { Component } from 'react';
import { Container, Header, Content, Card, CardItem, Text, Body } from 'native-base';
export default class CardHeaderFooterExample extends Component {
  render() {

    return (
      <Card>
        <CardItem header>
          <Text>NativeBase</Text>
        </CardItem>
        <CardItem>

            <Text>
              //Your text here
            </Text>

        </CardItem>
        <CardItem footer>
          <Text>GeekyAnts</Text>
        </CardItem>
      </Card>

lets say:

if logedin={true}
  return
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>

          <Text>
            //Your text here
          </Text>

      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

else return

  <Text> signup to access this content </Text>

How can be this conditional rendering be done for this situation? Those components should be rendered based on boolean logedin.

Body:
You can achieve this in multiple ways.

Using multiple returns

render()
{
  if(!logedin){
    return <Text> Signup to access this content </Text>;
  }

  return( <CardComponent/> );
}

Using ternary operator

condition ? statement to execute if condition is true : statement to execute if condition is false

    render()
    {
       return islogedin ? <CardComponent/> : <Text> Signup to access this content </Text>;
    }


问:
My website is generating too many redirects errors in chrome. Why is this and how can I fix it?
I wrote a game and put it online, and at the end of the game, there is a "restart" button. Rather than dealing with resetting the game state, I have it reload the page. However, after a few times of doing this, I get this screen in chrome:

The reload code I'm using is:

```<code><img id="restart-button" class="pointer" src="./img/restart.png"  onclick="location.reload()"/>
</code>```

I'm also doing quite a lot of preloading for the game, I have 46 image/audio files that I load in the cache at the start of the game.

My best guesses are:

the "location.reload()" is actually loading it a ton of times

it doesn't like the amount of stuff I'm asking it to cache and re-cache

Do I need to redo this with a simple init function? That'd be a huge pain based on the way I wrote the game. what's going on here?

The url of the game is http://secretmommymakeover.com/

答:
Your site has DNS issue, not code related issues. That's good news for you :)

When I did dig A secretmommymakeover.com I get three IP addreses back, like this:

```<code>secretmommymakeover.com. 1725   IN  A   162.255.119.154
secretmommymakeover.com. 1724   IN  A   192.30.252.154
secretmommymakeover.com. 1724   IN  A   193.30.252.154
</code>```

and that confuses the browser every n-th reload and tries to pull resourses or page from diff IP addresses...

Remove uncorrect IP address, and leave only correct one.

Also you have www subdomain redirect to and from naked domain name switched on, so try to switch if off if IP address didn't work.

Body:
I wrote a game and put it online, and at the end of the game, there is a "restart" button. Rather than dealing with resetting the game state, I have it reload the page. However, after a few times of doing this, I get this screen in chrome:

The reload code I'm using is:

I'm also doing quite a lot of preloading for the game, I have 46 image/audio files that I load in the cache at the start of the game.

My best guesses are:

the "location.reload()" is actually loading it a ton of times

it doesn't like the amount of stuff I'm asking it to cache and re-cache

Do I need to redo this with a simple init function? That'd be a huge pain based on the way I wrote the game. what's going on here?

The url of the game is http://secretmommymakeover.com/

Body:
Your site has DNS issue, not code related issues. That's good news for you :)

When I did dig A secretmommymakeover.com I get three IP addreses back, like this:

secretmommymakeover.com. 1725   IN  A   162.255.119.154
secretmommymakeover.com. 1724   IN  A   192.30.252.154
secretmommymakeover.com. 1724   IN  A   193.30.252.154

and that confuses the browser every n-th reload and tries to pull resourses or page from diff IP addresses...

Remove uncorrect IP address, and leave only correct one.

Also you have www subdomain redirect to and from naked domain name switched on, so try to switch if off if IP address didn't work.


问:
Does the Node --inspect flag have any notable performance impact?
Not much to expand on beyond the title. I'm considering leaving the --inspect flag on my Node EC2 instances for debugging purposes at will, and I just want to check if there are any notable performance concerns (or security holes) from doing so.</p>

答:
Performance: To let you know that having a "debugger" statement in your Node.js source code has a bad impact on performance. So I assume that running the node.js programme in debug-mode has the same bad performance impact. Read more at
https://medium.com/the-node-js-collection/get-ready-a-new-v8-is-coming-node-js-performance-is-changing-46a63d6da4de

Secure: by default the node.js process can only be debugged from the same localhost and on a specific port 9229 so that is secure. If you use something like 'node --inspect-brk=myhost.example.com:9229 ./index.js' for remote debugging then the debugger is exposed to the outside world (if that port is opened in the [Linux] firewall and if the DNS name is public).


问:
Rails scan for forward slash
I am looking to find forward slash tags in posts to my website. How can I use scan in Rails to do this? This should get the / then the words following. For instance it would be "This is my message /slash" and I am looking to scan for /slash.

```<code>@forward_slashes ||= message.scan( )
</code>```

ContentLicense: CC BY-SA 2.5

Title: Rails scan for forward slash

Body:
I am looking to find forward slash tags in posts to my website. How can I use scan in Rails to do this? This should get the / then the words following. For instance it would be "This is my message /slash" and I am looking to scan for /slash.

@forward_slashes ||= message.scan( )

Body: message.scan /\/\w+/ #=> ["/slash"]


问:
LocalDate to java.util.Date and vice versa simplest conversion?
Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object?

By 'simple', I mean simpler than this:

```<code>Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
</code>```

which seems a bit awkward to me.

Since we are interested only in the date portion and there is no timezone information in neither of the objects, why introduce time zones explicitly? The midnight time and the system default timezone should be taken implicitly for the conversion.

答:
Date to LocalDate

```<code>Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
</code>```

LocalDate to Date

```<code>LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
</code>```

Body:
Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object?

By 'simple', I mean simpler than this:

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

which seems a bit awkward to me.

Since we are interested only in the date portion and there is no timezone information in neither of the objects, why introduce time zones explicitly? The midnight time and the system default timezone should be taken implicitly for the conversion.

Body:
Date to LocalDate

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

LocalDate to Date

LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());


问:
Can you use auto with a comma
Can you use an auto deduced type where you have a comma to indicate initialization of two or more variables. Like this:

```<code> auto p = c.begin(), e = c.end();
</code>```

Or is the presence of two initializations  (potentially) too confusing for a compiler? What does the C++ standard allow?

答:
Can you use an auto deduced type where you have a comma operator to indicate initialization of two or more variables.

Yes.

Or is the presence of two initialization too confusing for a compiler?

No, it is not. As long as the auto deduction does not result in inconsistent types declaring multiple variables in the same statement using auto is fine.

From the C++11 Standard/7.1.6.4 auto specifier/3:

```<code>auto x = 5;                 // OK: x has type int
const auto *v = &x, u = 6;  // OK: v has type const int*, u has type const int
</code>```

However, you may not use:

```<code>const auto *v = &x, u = 6.0;
</code>```

and hope for the type of v to be deduced as const int* and the type of u to be deduced as const double.

Title: Can you use auto with a comma

Body:
Can you use an auto deduced type where you have a comma to indicate initialization of two or more variables. Like this:

 auto p = c.begin(), e = c.end();

Or is the presence of two initializations  (potentially) too confusing for a compiler? What does the C++ standard allow?

Body:
Can you use an auto deduced type where you have a comma operator to indicate initialization of two or more variables.

Yes.

Or is the presence of two initialization too confusing for a compiler?

No, it is not. As long as the auto deduction does not result in inconsistent types declaring multiple variables in the same statement using auto is fine.

From the C++11 Standard/7.1.6.4 auto specifier/3:

auto x = 5;                 // OK: x has type int
const auto *v = &x, u = 6;  // OK: v has type const int*, u has type const int

However, you may not use:

const auto *v = &x, u = 6.0;

and hope for the type of v to be deduced as const int* and the type of u to be deduced as const double.


问:
Check if date is a valid one
Following is the scenario:

I have a String date and a date format which is different. Ex.:

date: 2016-10-19

dateFormat: "DD-MM-YYYY".

I need to check if this date is a valid date.

I have tried following things

```<code>var d = moment("2016-10-19",dateFormat);
</code>```

d.isValid() is returning false every time. Does not Moment.js parse the date in the given format?

Then I tried to format the date in DD-MM-YYYY first and then pass it to Moment.js:

```<code>var d = moment("2016-10-19").format(dateFormat);
var date = moment(d, dateFormat);
</code>```

Now date.isValid() is giving me the desired result, but here the Moment.js date object is created twice. How can I avoid this? Is there a better solution?

FYI I am not allowed to change the dateFormat.

答:
var date = moment('2016-10-19', 'DD-MM-YYYY', true);

You should add a third argument when invoking moment that enforces strict parsing.  Here is the relevant portion of the moment documentation http://momentjs.com/docs/#/parsing/string-format/ It is near the end of the section.

Title: Check if date is a valid one

Body:
Following is the scenario:

I have a String date and a date format which is different. Ex.:

date: 2016-10-19

dateFormat: "DD-MM-YYYY".

I need to check if this date is a valid date.

I have tried following things

var d = moment("2016-10-19",dateFormat);

d.isValid() is returning false every time. Does not Moment.js parse the date in the given format?

Then I tried to format the date in DD-MM-YYYY first and then pass it to Moment.js:

var d = moment("2016-10-19").format(dateFormat);
var date = moment(d, dateFormat);

Now date.isValid() is giving me the desired result, but here the Moment.js date object is created twice. How can I avoid this? Is there a better solution?

FYI I am not allowed to change the dateFormat.


问:
SQL comparing a few values in select
so i have 2 tables in SQL, Patients and Patients_Treatments which are connected with patient.id as main key
what i wanna do is take a specific patient and see what treatments he has done so i have this code:

```<code>SELECT (Treatment_code)
FROM Patients_Treatments
Where Patient_ID = '999999999'
</code>```

now what i want do is take all the patients from Patient tabel that have had the same treatments code (or more treatments) just as patient '99999999'

so if patient '9999999' had treatments 111,222,333
and i have a patient that had treatment 111,222,555 - it wont show him
but if had had treatments 111,222,333 or 111,222,333,444 - it will show him

im having problem with how to do a loop so i make sure it check that all the treatments that patient 99999999 has done, also the person im checking has done as well

thanks!

答:
Try this one</p>

```<code>SELECT P.*
  FROM Patients P JOIN
       Patients_Treatments PT
       ON (P.Patient_ID = PT.Patient_ID)
 WHERE PT.Treatment_code IN ( SELECT Treatment_code
                                FROM Patients_Treatments
                               WHERE Patient_ID = '999999999');
</code>```

Title: SQL comparing a few values in select

Body:
so i have 2 tables in SQL, Patients and Patients_Treatments which are connected with patient.id as main key
what i wanna do is take a specific patient and see what treatments he has done so i have this code:

SELECT (Treatment_code)
FROM Patients_Treatments
Where Patient_ID = '999999999'

now what i want do is take all the patients from Patient tabel that have had the same treatments code (or more treatments) just as patient '99999999'

so if patient '9999999' had treatments 111,222,333
and i have a patient that had treatment 111,222,555 - it wont show him
but if had had treatments 111,222,333 or 111,222,333,444 - it will show him

im having problem with how to do a loop so i make sure it check that all the treatments that patient 99999999 has done, also the person im checking has done as well

thanks!

Body:
Try this one

SELECT P.*
  FROM Patients P JOIN
       Patients_Treatments PT
       ON (P.Patient_ID = PT.Patient_ID)
 WHERE PT.Treatment_code IN ( SELECT Treatment_code
                                FROM Patients_Treatments
                               WHERE Patient_ID = '999999999');


问:
Need help translating this JQuery code back to raw Javascript
I'm currently having trouble understanding what's going on with this code

```<code> $("#table").on("click", ".plusRow", function(event){
            var name = this.getAttribute("table-data");
            tableData.addData(name, 0, 1);
            displayTable();
        });
</code>```

I understand that the first part should go something along the lines of

```<code>document.getElementById("table").addEventListener("click", function(event)
</code>```

but im having trouble understanding where the ".plusRow" class should go, is it added onto the eventlistener? or how would this code be better translated back to regular Javascript.

答:
So I've come up with a dummy possible solution example using querySelector and querySelectorAll.  Let me know if anyone sees an issue with the suggested solution.

function delegate(parentSelector, eventType, childSelector, callback) {
  //lookup the parent element
  var parent = document.querySelector(parentSelector);

  //put the event listener for the event on the parent
  parent.addEventListener(eventType, function(event) {
    //get the element that caused the event
    var element = event.target;
    //find all the children in the parent that match the child selector,
    //at this point in time
    var children = parent.querySelectorAll(childSelector);

    //if the element matches a child of the parent that matched the
    //childSelector, we want to do our callback
    for (var i = 0; i < children.length; i++) {
      if (children[i] === element) {
        callback();
        break;
      }
    }
  });
}

delegate('#table', 'click', '.addRow', function() {
  document.querySelector('#table').innerHTML += `

      Something
      <button class="addRow">Add Row</button>

  `;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table">
  <tr>
    <td>Something</td>
    <td><button class="addRow">Add Row</button></td>
  </tr>
</table></code>```

Body:
I'm currently having trouble understanding what's going on with this code

 $("#table").on("click", ".plusRow", function(event){
            var name = this.getAttribute("table-data");
            tableData.addData(name, 0, 1);
            displayTable();
        });

I understand that the first part should go something along the lines of

document.getElementById("table").addEventListener("click", function(event)

but im having trouble understanding where the ".plusRow" class should go, is it added onto the eventlistener? or how would this code be better translated back to regular Javascript.

Body:
So I've come up with a dummy possible solution example using querySelector and querySelectorAll.  Let me know if anyone sees an issue with the suggested solution.

function delegate(parentSelector, eventType, childSelector, callback) {
  //lookup the parent element
  var parent = document.querySelector(parentSelector);

  //put the event listener for the event on the parent
  parent.addEventListener(eventType, function(event) {
    //get the element that caused the event
    var element = event.target;
    //find all the children in the parent that match the child selector,
    //at this point in time
    var children = parent.querySelectorAll(childSelector);

    //if the element matches a child of the parent that matched the
    //childSelector, we want to do our callback
    for (var i = 0; i < children.length; i++) {
      if (children[i] === element) {
        callback();
        break;
      }
    }
  });
}

delegate('#table', 'click', '.addRow', function() {
  document.querySelector('#table').innerHTML += `
    <tr>
      <td>Something</td>
      <td><button class="addRow">Add Row</button></td>
    </tr>
  `;
});

<table id="table">
  <tr>
    <td>Something</td>
    <td><button class="addRow">Add Row</button></td>
  </tr>
</table>


问:
Deap python package: create individuals with different ranges and mix of integers and floats
I am trying to use DEAP to maximise a function.

I understand how to do it with the basic example:

```<code>toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual,
    toolbox.attr_bool, 100)
</code>```

which creates  100 random values or either 0 or 1. You then go on and create a population and mutate ...

How do you build a population when you have for example two parameters:

```<code>parameter 1 integer with range [0,1]
parameter 2 float with range [0,2]
</code>```

Then create an individual combining both randomly sampled parameters? or for parameter 2 sample with an arbitary step value , for example 0.25.

答:
You can simply do as follows to create chromosomes of multiple types:

```<code>toolbox.register("attr_int", random.randint, 0, 1)
toolbox.register("attr_flt", random.uniform, 0, 2)
toolbox.register("individual", tools.initCycle, creator.Individual,
             (toolbox.attr_int, toolbox.attr_flt),
             n=1)
</code>```

and then create a population of size 100:

```<code>toolbox.register("population", tools.initRepeat, list, toolbox.individual)
population = toolbox.population(n=100)
</code>```

Body:
I am trying to use DEAP to maximise a function.

I understand how to do it with the basic example:

toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual,
    toolbox.attr_bool, 100)

which creates  100 random values or either 0 or 1. You then go on and create a population and mutate ...

How do you build a population when you have for example two parameters:

parameter 1 integer with range [0,1]
parameter 2 float with range [0,2]

Then create an individual combining both randomly sampled parameters? or for parameter 2 sample with an arbitary step value , for example 0.25.

Body:
You can simply do as follows to create chromosomes of multiple types:

toolbox.register("attr_int", random.randint, 0, 1)
toolbox.register("attr_flt", random.uniform, 0, 2)
toolbox.register("individual", tools.initCycle, creator.Individual,
             (toolbox.attr_int, toolbox.attr_flt),
             n=1)

and then create a population of size 100:

toolbox.register("population", tools.initRepeat, list, toolbox.individual)
population = toolbox.population(n=100)


问:
Redux-Form v7 Field component typescript errors
Here's my code where I'm using the Field component:

    interface EditProfileFormProps extends FormProps {
        defaults: object;
        submit: () => {};
        initialValues: object;
        roles: object[];
        specialties: object[];
    }

const EditProfileForm: React.StatelessComponent<EditProfileFormProps> = (props: EditProfileFormProps) => {
    return (
        <Form onSubmit={props.submit}>

              <Field name="firstName" component={FirstName} type="text" />

              <Field name="lastName" component={LastName} type="text" />

              <Field name="role" props={{ roles: props.roles }} component={Role} type="select" />

        </Form>
    );
};

//FirstName.tsx
export const FirstName: React.StatelessComponent<React.InputHTMLAttributes<HTMLInputElement>> = ({
    input,
}: React.InputHTMLAttributes<HTMLInputElement> & WrappedFieldProps) => (
    <FormGroup>
     First Name
     <Input {...input} type="text" name="firstName" id="firstName" />
    </FormGroup>
);```
</div>
</div>
</p>
<p>And here's the TS error that I'm seeing:</p>
```[ts]
Type '{ name: "firstName"; component: StatelessComponent<InputHTMLAttributes<HTMLInputElement>>; type: ...' is not assignable to type '(IntrinsicAttributes & IntrinsicClassAttributes<Field<GenericFieldHTMLAttributes>> & Readonly<{ c...'.
  Type '{ name: "firstName"; component: StatelessComponent<InputHTMLAttributes<HTMLInputElement>>; type: ...' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Field<GenericFieldHTMLAttributes>> & Readonly<{ ch...'.
    Type '{ name: "firstName"; component: StatelessComponent<InputHTMLAttributes<HTMLInputElement>>; type: ...' is not assignable to type 'Readonly<BaseFieldProps<GenericFieldHTMLAttributes> & TextareaHTMLAttributes<HTMLTextAreaElement>>'.
     Types of property 'component' are incompatible.
        Type 'StatelessComponent<InputHTMLAttributes<HTMLInputElement>>' is not assignable to type '"input" | "select" | "textarea" | ComponentClass<GenericFieldHTMLAttributes> | StatelessComponent...'.
          Type 'StatelessComponent<InputHTMLAttributes<HTMLInputElement>>' is not assignable to type 'StatelessComponent<GenericFieldHTMLAttributes>'.
            Type 'React.ReactElement<any> | null' is not assignable to type 'React.ReactElement<any> | null'. Two different types with this name exist, but they are unrelated.
              Type 'ReactElement<any>' is not assignable to type 'ReactElement<any> | null'.
                Type 'React.ReactElement<any>' is not assignable to type 'React.ReactElement<any>'. Two different types with this name exist, but they are unrelated.
                  Types of property 'type' are incompatible.
                    Type 'string | React.ComponentClass<any> | React.StatelessComponent<any>' is not assignable to type 'string | React.ComponentClass<any> | React.StatelessComponent<any>'. Two different types with this name exist, but they are unrelated.
                      Type 'ComponentClass<any>' is not assignable to type 'string | ComponentClass<any> | StatelessComponent<any>'.
                        Type 'ComponentClass<any>' is not assignable to type 'StatelessComponent<any>'.
                          Type 'ComponentClass<any>' provides no match for the signature '(props: any, context?: any): ReactElement<any> | null'.
```

Does anyone see what I'm doing wrong?

答: Not sure if this is your issue, but when we make a stateless component, our signature looks like this React.SFC not React.StatelessComponent.

Body:
Here's my code where I'm using the Field component:

    interface EditProfileFormProps extends FormProps {
        defaults: object;
        submit: () => {};
        initialValues: object;
        roles: object[];
        specialties: object[];
    }

const EditProfileForm: React.StatelessComponent<EditProfileFormProps> = (props: EditProfileFormProps) => {
    return (
        <Form onSubmit={props.submit}>

              <Field name="firstName" component={FirstName} type="text" />

              <Field name="lastName" component={LastName} type="text" />

              <Field name="role" props={{ roles: props.roles }} component={Role} type="select" />

        </Form>
    );
};

//FirstName.tsx
export const FirstName: React.StatelessComponent<React.InputHTMLAttributes<HTMLInputElement>> = ({
    input,
}: React.InputHTMLAttributes<HTMLInputElement> & WrappedFieldProps) => (
    <FormGroup>
     First Name
     <Input {...input} type="text" name="firstName" id="firstName" />
    </FormGroup>
);

And here's the TS error that I'm seeing:

[ts]
Type '{ name: "firstName"; component: StatelessComponent<InputHTMLAttributes<HTMLInputElement>>; type: ...' is not assignable to type '(IntrinsicAttributes & IntrinsicClassAttributes<Field<GenericFieldHTMLAttributes>> & Readonly<{ c...'.
  Type '{ name: "firstName"; component: StatelessComponent<InputHTMLAttributes<HTMLInputElement>>; type: ...' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Field<GenericFieldHTMLAttributes>> & Readonly<{ ch...'.
    Type '{ name: "firstName"; component: StatelessComponent<InputHTMLAttributes<HTMLInputElement>>; type: ...' is not assignable to type 'Readonly<BaseFieldProps<GenericFieldHTMLAttributes> & TextareaHTMLAttributes<HTMLTextAreaElement>>'.
     Types of property 'component' are incompatible.
        Type 'StatelessComponent<InputHTMLAttributes<HTMLInputElement>>' is not assignable to type '"input" | "select" | "textarea" | ComponentClass<GenericFieldHTMLAttributes> | StatelessComponent...'.
          Type 'StatelessComponent<InputHTMLAttributes<HTMLInputElement>>' is not assignable to type 'StatelessComponent<GenericFieldHTMLAttributes>'.
            Type 'React.ReactElement<any> | null' is not assignable to type 'React.ReactElement<any> | null'. Two different types with this name exist, but they are unrelated.
              Type 'ReactElement<any>' is not assignable to type 'ReactElement<any> | null'.
                Type 'React.ReactElement<any>' is not assignable to type 'React.ReactElement<any>'. Two different types with this name exist, but they are unrelated.
                  Types of property 'type' are incompatible.
                    Type 'string | React.ComponentClass<any> | React.StatelessComponent<any>' is not assignable to type 'string | React.ComponentClass<any> | React.StatelessComponent<any>'. Two different types with this name exist, but they are unrelated.
                      Type 'ComponentClass<any>' is not assignable to type 'string | ComponentClass<any> | StatelessComponent<any>'.
                        Type 'ComponentClass<any>' is not assignable to type 'StatelessComponent<any>'.
                          Type 'ComponentClass<any>' provides no match for the signature '(props: any, context?: any): ReactElement<any> | null'.

Does anyone see what I'm doing wrong?


问:
Catching Signals and Pausing with Character Device Drivers
I'm a student new to C Programming and am not fully understanding how signal catching works, and in line with character device drivers.  I'd appreciate some help but I need to state that this is for a project that is due in my first C Programming class.  So I have not posted any direct code, only an example of my initial approach.

My project needs to accept a signal input and set that signal to a variable to pass to my character device driver. Another program I've written will need to access that variable's value such that when read, it performs a certain outcome.  I've tried to run my control program (<name> &) but it quits immediately.  I double check by entering ps into my command prompt and the process is gone.

Basically I need my control program to pause and wait for the signal to be received.  Once received, if the signal matches it will set a variable to its value.  Otherwise, if it is SIGTERM it will either end or pause(), where it will wait until another signal is received that meets another condition.  Currently, when I compile and run it with & it simply runs and quits.  Here is an example of my code:

```<code>#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

void sig_handler(int sig);

void sig_handler(int sig){
    while(1){
        if(sig == SIGRTMIN){
            printf("SIG = SIGRTMIN\n");
            file_state = 0;
        }else if(sig == SIGRTMIN+1){
            printf("SIG = SIGRTMIN1\n");
            file_state = 1;
        }else if(sig == SIGTERM){
            printf("Exiting\n");
            exit(0);                         //exit
        }else{
            printf("SIG = %i\n", sig);
            pause();                        //doesn't match, pause for next signal
        }
    }
}

int main(){
    signal(SIGINT, sig_handler);
    //return 0;  //tried with and without
}
</code>```

I'm waiting until this daemon receives a signal to put the device driver into a particular mode.  I haven't entered any write() methods yet because I'm trying to take this one step at a time where I send a signal with kill() and the proper response is returned with printf().
 My problem is that I can't seem to keep this in pause() mode while I'm waiting for a signal that breaks the if loop.  What's worse (other than my lack of knowledge and programming) is that I can't even keep this daemon open long enough to attempt a signal send.  Once I can get this to pause and receive the signal, I plan to use the system write() method to write my file_state variable to the /dev/<filename>, which will be cross-referenced in my executable.

How far off am I?  This is the final part that (I believe) I'm stuck on and I can't figure out how this should be approached.  I've looked online and about 95% of the examples that delve into this contain methods we haven't learned yet.  And if not, the examples are more simplistic where they do not include passing a value to a character device driver for use when another program is using the driver.

Any help is greatly appreciated.

ETA
I've updated my code so now it stays open until a signal is received.  Problem is that I want this to pause() and remain open until the SIGTERM signal is received, breaking the loop and ending the program.  I can't seem to get the loop correct.  Even entering a conditional int variable into the while() loop still is broken when any signal is received.  Here is my updated code below:

```<code>#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

int keep_alive = 1;                       //added for conditional checking to keep the while
                                          //loop open to receive more than one signal

void sig_handler(int sig);

void sig_handler(int sig){
    if(sig == SIGRTMIN){
        printf("SIG = SIGRTMIN\n");
        file_state = 0;
    }else if(sig == SIGRTMIN+1){
        printf("SIG = SIGRTMIN1\n");
        file_state = 1;
    }else if(sig == SIGTERM){
        keep_alive = 0;
    }else{
    }
}

int main(){
    do{
        signal(SIGINT, sig_handler);
        pause();                           //thought pausing here would help with waiting for a new signal
    }while(keep_alive == 1);               //keep looping until false
    return 0;                              //tried with and without
}
</code>```

I'm trying to figure out a method to keep this process and signal catching loop alive until a specific signal is received.  I can't figure it out for the life of me.

ETA 2

Discovered my issue.  I wasn't paying attention and fully understanding the signal() method.  The first argument requires the exact signal you are attempting to catch.  I was using SIGINT which I was understanding it to be a "class" of interrupts that you wanted to catch.  And then in the signal_handler() function, you would specify which type of interrupt you were catching.  But, it is actually looking to catch the exact signal you are interested in.  So in my example code, I should have been using:

```<code>int main(){
    if(signal(SIGRMIN, sig_handler) == SIG_ERR){
         printf("can't catch SIGRMIN Signal.\n")
    }
...
}
</code>```

I'm going to update with my new script as an answer and if anyone thinks it should be done differently or have any constructive criticisms please let me know.  Thanks again!

答:
So I found my issue, and it is working now.  Below is my fixed code that produces the correct response back to the terminal when caught.  I've added a for() loop to catch any other signals I'm not worried about didn't stop my process, only SIGTERM will.  Look forward to getting critiqued and why I would never want to do my approach.

```<code>#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

void sig_handler(int sig);

void sig_handler(int sig){
    if(sig == SIGRTMIN){
        printf("SIG = SIGRTMIN\n");
        file_state = 0;
    }else if(sig == SIGRTMIN+1){
        printf("SIG = SIGRTMIN1\n");
        file_state = 1;
    }else if(sig == SIGTERM){
        exit(0);
        EXIT_SUCCESS;
    }else{
        printf("SIGNAL CAUGHT #%d\n", sig);
    }
}

int main(){
    if(signal(SIGRTMIN, sig_handler)==SIG_ERR){
         printf("Unable to catch SIGRTMIN\n");
    }
    if(signal(SIGRTMIN+1, sig_handler)==SIG_ERR){
         printf("Unable to catch SIGRTMIN+1\n");
    }
    if(signal(SIGTERM, sig_handler)==SIG_ERR){
         printf("Unable to terminate process.\n");
    }

    //This for loop will catch all other signals except the un-catchable and
    //other user-specified above signal #31.

    int s;
    for(s = 0; s < 32; s++){
         signal(s, sig_handler);
    }

    while(1);
    pause();
    return 0;
}
</code>```

Body:
I'm a student new to C Programming and am not fully understanding how signal catching works, and in line with character device drivers.  I'd appreciate some help but I need to state that this is for a project that is due in my first C Programming class.  So I have not posted any direct code, only an example of my initial approach.

My project needs to accept a signal input and set that signal to a variable to pass to my character device driver. Another program I've written will need to access that variable's value such that when read, it performs a certain outcome.  I've tried to run my control program (<name> &) but it quits immediately.  I double check by entering ps into my command prompt and the process is gone.

Basically I need my control program to pause and wait for the signal to be received.  Once received, if the signal matches it will set a variable to its value.  Otherwise, if it is SIGTERM it will either end or pause(), where it will wait until another signal is received that meets another condition.  Currently, when I compile and run it with & it simply runs and quits.  Here is an example of my code:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

void sig_handler(int sig);

void sig_handler(int sig){
    while(1){
        if(sig == SIGRTMIN){
            printf("SIG = SIGRTMIN\n");
            file_state = 0;
        }else if(sig == SIGRTMIN+1){
            printf("SIG = SIGRTMIN1\n");
            file_state = 1;
        }else if(sig == SIGTERM){
            printf("Exiting\n");
            exit(0);                         //exit
        }else{
            printf("SIG = %i\n", sig);
            pause();                        //doesn't match, pause for next signal
        }
    }
}

int main(){
    signal(SIGINT, sig_handler);
    //return 0;  //tried with and without
}

I'm waiting until this daemon receives a signal to put the device driver into a particular mode.  I haven't entered any write() methods yet because I'm trying to take this one step at a time where I send a signal with kill() and the proper response is returned with printf().
 My problem is that I can't seem to keep this in pause() mode while I'm waiting for a signal that breaks the if loop.  What's worse (other than my lack of knowledge and programming) is that I can't even keep this daemon open long enough to attempt a signal send.  Once I can get this to pause and receive the signal, I plan to use the system write() method to write my file_state variable to the /dev/<filename>, which will be cross-referenced in my executable.

How far off am I?  This is the final part that (I believe) I'm stuck on and I can't figure out how this should be approached.  I've looked online and about 95% of the examples that delve into this contain methods we haven't learned yet.  And if not, the examples are more simplistic where they do not include passing a value to a character device driver for use when another program is using the driver.

Any help is greatly appreciated.

ETA
I've updated my code so now it stays open until a signal is received.  Problem is that I want this to pause() and remain open until the SIGTERM signal is received, breaking the loop and ending the program.  I can't seem to get the loop correct.  Even entering a conditional int variable into the while() loop still is broken when any signal is received.  Here is my updated code below:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

int keep_alive = 1;                       //added for conditional checking to keep the while
                                          //loop open to receive more than one signal

void sig_handler(int sig);

void sig_handler(int sig){
    if(sig == SIGRTMIN){
        printf("SIG = SIGRTMIN\n");
        file_state = 0;
    }else if(sig == SIGRTMIN+1){
        printf("SIG = SIGRTMIN1\n");
        file_state = 1;
    }else if(sig == SIGTERM){
        keep_alive = 0;
    }else{
    }
}

int main(){
    do{
        signal(SIGINT, sig_handler);
        pause();                           //thought pausing here would help with waiting for a new signal
    }while(keep_alive == 1);               //keep looping until false
    return 0;                              //tried with and without
}

I'm trying to figure out a method to keep this process and signal catching loop alive until a specific signal is received.  I can't figure it out for the life of me.

ETA 2

Discovered my issue.  I wasn't paying attention and fully understanding the signal() method.  The first argument requires the exact signal you are attempting to catch.  I was using SIGINT which I was understanding it to be a "class" of interrupts that you wanted to catch.  And then in the signal_handler() function, you would specify which type of interrupt you were catching.  But, it is actually looking to catch the exact signal you are interested in.  So in my example code, I should have been using:

int main(){
    if(signal(SIGRMIN, sig_handler) == SIG_ERR){
         printf("can't catch SIGRMIN Signal.\n")
    }
...
}

I'm going to update with my new script as an answer and if anyone thinks it should be done differently or have any constructive criticisms please let me know.  Thanks again!

Body:
So I found my issue, and it is working now.  Below is my fixed code that produces the correct response back to the terminal when caught.  I've added a for() loop to catch any other signals I'm not worried about didn't stop my process, only SIGTERM will.  Look forward to getting critiqued and why I would never want to do my approach.

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

void sig_handler(int sig);

void sig_handler(int sig){
    if(sig == SIGRTMIN){
        printf("SIG = SIGRTMIN\n");
        file_state = 0;
    }else if(sig == SIGRTMIN+1){
        printf("SIG = SIGRTMIN1\n");
        file_state = 1;
    }else if(sig == SIGTERM){
        exit(0);
        EXIT_SUCCESS;
    }else{
        printf("SIGNAL CAUGHT #%d\n", sig);
    }
}

int main(){
    if(signal(SIGRTMIN, sig_handler)==SIG_ERR){
         printf("Unable to catch SIGRTMIN\n");
    }
    if(signal(SIGRTMIN+1, sig_handler)==SIG_ERR){
         printf("Unable to catch SIGRTMIN+1\n");
    }
    if(signal(SIGTERM, sig_handler)==SIG_ERR){
         printf("Unable to terminate process.\n");
    }

    //This for loop will catch all other signals except the un-catchable and
    //other user-specified above signal #31.

    int s;
    for(s = 0; s < 32; s++){
         signal(s, sig_handler);
    }

    while(1);
    pause();
    return 0;
}


问:
How to find the particular text stored in the file "data.txt" and it occurs only once
The line I seek is stored in the file data.txt and is the only line of text that occurs only once.

How do I go about finding that particular line using linux?

答:
And one with only one tool in use, awk:

```<code>awk '{a[$1]++}END{for(i in a){if(a[i] == 1){print i} }}' data.txt
</code>```

Body:
And one with only one tool in use, awk:

awk '{a[$1]++}END{for(i in a){if(a[i] == 1){print i} }}' data.txt


问:
Use Grails Form tag with Controller in Subfolder
I'd like to send an email using a controller in a subfolder. I can't seem to find the syntax to accomplish this.

The default would be something like this...

```<code><g:form controller="email" action="sendEmail">
     // form stuff
</g:form>
</code>```

But my email controller, called Email.groovy, is in controllers/portal/Utils. Maybe this is outside normal convention?

答: Change your controller class name to EmailController.groovy</p>

Body:
I'd like to send an email using a controller in a subfolder. I can't seem to find the syntax to accomplish this.

The default would be something like this...

<g:form controller="email" action="sendEmail">
     // form stuff
</g:form>

But my email controller, called Email.groovy, is in controllers/portal/Utils. Maybe this is outside normal convention?


问:
Submit to App Store issues: Unsupported Architecture x86
So I am trying to use the Shopify API. When I archive the app and validate it then there are no issues but when I submit it to the app store then it gives me the following issues.

ERROR ITMS-90087: "Unsupported Architecture. Your executable contains unsupported architecture '[x86_64, i386]'."

ERROR ITMS-90209: "Invalid segment Alignment. The App Binary at SJAPP.app/Frameworks/Buy.framework/Buy does not have proper segment alignment. Try rebuilding the app with the latest Xcode version." (I am already using the latest version.)

ERROR ITMS-90125: "The Binary is invalid. The encryption info in the LC_ENCRYPTION_INFO load command is either missing or invalid, or the binary is already encrypted. This binary does not seem to have been built with Apple's Linker."

WARNING ITMS-90080: "The Executable Payload/..../Buy.framework is not a Position Independent Executable. Please ensure that ur build settings are configured to create PIE executables."

答:
I removed architectures i386 & x64_86 from Build Settings - Valid Architectures - Release, and everything worked just fine.

Now the only issue would be that you can't run a RELEASE build for testing purposes on a SIMULATOR. But as easily as you removed the archs, you can add them back if you want to.


答:
I'm not entirely clear on your question, as it's in broken English.  I think you're just referring to the ruby String method method scan - nothing rails-specific about it.

It just takes a regular expression.  /(\/.*)/ will match from the first forward slash to the end of the string.

my_string.scan(/\/.*/) {|slash_stuff| puts slash_stuff}

edit: using \w+ will only return the first word after the slash.  .* will return everything until the end of the string.

edit: using split will break it up into >2 pieces if there are multiple forward slashes, which isn't clear from your description what you would want for an input of hi / there / person - do you want "/ there / person" (use scan) or " there " and " person" (use split)

Title: Rails scan for forward slash

Body:
I am looking to find forward slash tags in posts to my website. How can I use scan in Rails to do this? This should get the / then the words following. For instance it would be "This is my message /slash" and I am looking to scan for /slash.

@forward_slashes ||= message.scan( )


问:
NSOutlineView - Disclosure Triangle Interferes with Highlight Rectangle
I have an NSOutlineView with the highlight mode set to source list and the menu property set to a non-empty menu (I figured this last consdition is necessary to have the outline drawn).

When I right-click on a row representing an item that has children (i.e., is expandable), The blue outline around the cell has a slightly different color right above and below the disclosure triangle:

(This happens for every node, at every level of the hierarchy)

Additional information: My outline view is view based, does not use bindings (view controller is the delegate and data source).
Me cells are custom, designed on the storyboard, nothing fancy (icon image view and text field).

What can be causing this?

EDIT: The issue only appears with the round-cornerered highlight rectangle of the "Source List" highlight mode. With the straight-cornered rectangle of the "Regular" highlight mode, the stroke color is even all along.

答: When using the Source List style, your outline view has an NSVisualEffect view behind it, which causes the list to be composited differently. What you're seeing seems to be a bug with the vibrancy appearance. You could perhaps try to work around it by reducing the frame of the outline cell by overriding frameOfOutlineCell.


问:
SAS - Transpose all colums by unique records in each column with counts
I am trying to find efficient, transpose-like code that can convert the Test table below into the Final table. I have code below that works for this example, but for practical purposes, the split data step can produce a very deep table (137 million records in my case, vs 2k as aggregated).

I was hoping there was some Proc or Data step trick I was missing that could skip that intermediate step and be more efficient.

```<code>Data test;
    Input f1 $ f2 $ f3 $ f4 $ f5 $ f6 $ f7 $ f8 $;

    DataLines;
a c f h k l o q
a c f h k l o q
a c g h k m o q
b c g h k m o q
b d g i k m o r
b d g i k n o r
b e g j k n o s
b e g j k n p s
    ;

Run;

Data final;
    Input field $ values $ records;

    DataLines;
f1 a 3
f1 b 5
f2 c 4
f2 d 2
f2 e 2
f3 f 2
f3 g 6
f4 h 4
f4 i 2
f4 j 2
f5 k 8
f6 l 2
f6 m 3
f6 n 3
f7 o 7
f7 p 1
f8 q 4
f8 r 2
f8 s 2
    ;

Run;

/*Working solution - could it be done more efficiently?*/
Data split;
    Set test;

    Array f{8} f1-f8;
    Do i=1 To 8;
        field = 'f'||PUT(i,best2.);
        values = f{i};
        Output;
    End;

    Drop i f1-f8;
Run;

Proc SQL;
    Create Table final As
    Select
        field
        ,values
        ,COUNT(*) As records Format=comma8.0
    From split
    Group By 1,2
    Order By 1,2
    ;
Quit;
</code>```

答:
The solution that's likely most time-efficient is to use a summarization procedure.  PROC TABULATE seems best suited here.

```<code>proc tabulate data=test out=test_c;
  class f1-f8;
  tables (f1-f8),n;
run;
data want;
  set test_c;
  array f f1-f8;
  col = cats(of f[*]);
  which_f = whichc(col,of f[*]);
  var = vname(f[which_f]);
  keep col var n;
run;
</code>```

That final datastep is very 'cheap', as it's only done on the summarized dataset so the 2k sized dataset.  As long as you don't have a huge number of columns this should be pretty simple.

If you do have a huge number of columns as well, then the data step based solution that you present above is probably best.  You may be able to speed it up significantly by making the intermediate (split) data step into a view.

Body:
I am trying to find efficient, transpose-like code that can convert the Test table below into the Final table. I have code below that works for this example, but for practical purposes, the split data step can produce a very deep table (137 million records in my case, vs 2k as aggregated).

I was hoping there was some Proc or Data step trick I was missing that could skip that intermediate step and be more efficient.

Data test;
    Input f1 $ f2 $ f3 $ f4 $ f5 $ f6 $ f7 $ f8 $;

    DataLines;
a c f h k l o q
a c f h k l o q
a c g h k m o q
b c g h k m o q
b d g i k m o r
b d g i k n o r
b e g j k n o s
b e g j k n p s
    ;

Run;

Data final;
    Input field $ values $ records;

    DataLines;
f1 a 3
f1 b 5
f2 c 4
f2 d 2
f2 e 2
f3 f 2
f3 g 6
f4 h 4
f4 i 2
f4 j 2
f5 k 8
f6 l 2
f6 m 3
f6 n 3
f7 o 7
f7 p 1
f8 q 4
f8 r 2
f8 s 2
    ;

Run;

/*Working solution - could it be done more efficiently?*/
Data split;
    Set test;

    Array f{8} f1-f8;
    Do i=1 To 8;
        field = 'f'||PUT(i,best2.);
        values = f{i};
        Output;
    End;

    Drop i f1-f8;
Run;

Proc SQL;
    Create Table final As
    Select
        field
        ,values
        ,COUNT(*) As records Format=comma8.0
    From split
    Group By 1,2
    Order By 1,2
    ;
Quit;

Body:
The solution that's likely most time-efficient is to use a summarization procedure.  PROC TABULATE seems best suited here.

proc tabulate data=test out=test_c;
  class f1-f8;
  tables (f1-f8),n;
run;
data want;
  set test_c;
  array f f1-f8;
  col = cats(of f[*]);
  which_f = whichc(col,of f[*]);
  var = vname(f[which_f]);
  keep col var n;
run;

That final datastep is very 'cheap', as it's only done on the summarized dataset so the 2k sized dataset.  As long as you don't have a huge number of columns this should be pretty simple.

If you do have a huge number of columns as well, then the data step based solution that you present above is probably best.  You may be able to speed it up significantly by making the intermediate (split) data step into a view.


问:
Is it possible to force Excel recognize UTF-8 CSV files automatically?
I'm developing a part of an application that's responsible for exporting some data into CSV files. The application always uses UTF-8 because of its multilingual nature at all levels. But opening such CSV files (containing e.g. diacritics, cyrillic letters, Greek letters) in Excel does not achieve the expected results showing something like Г„/Г¤, Г–/Г¶. And I don't know how to force Excel understand that the open CSV file is encoded in UTF-8. I also tried specifying UTF-8 BOM EF BB BF, but Excel ignores that.

Is there any workaround?

P.S. Which tools may potentially behave like Excel does?

UPDATE

I have to say that I've confused the community with the formulation of the question. When I was asking this question, I asked for a way of opening a UTF-8 CSV file in Excel without any problems for a user, in a fluent and transparent way. However, I used a wrong formulation asking for doing it automatically. That is very confusing and it clashes with VBA macro automation. There are two answers for this questions that I appreciate the most: the very first answer by Alex https://stackoverflow.com/a/6002338/166589, and I've accepted this answer; and the second one by Mark https://stackoverflow.com/a/6488070/166589 that have appeared a little later. From the usability point of view, Excel seemed to have lack of a good user-friendly UTF-8 CSV support, so I consider both answers are correct, and I have accepted Alex's answer first because it really stated that Excel was not able to do that transparently. That is what I confused with automatically here. Mark's answer promotes a more complicated way for more advanced users to achieve the expected result. Both answers are great, but Alex's one fits my not clearly specified question a little better.

UPDATE 2

Five months later after the last edit, I've noticed that Alex's answer has disappeared for some reason. I really hope it wasn't a technical issue and I hope there is no more discussion on which answer is greater now. So I'm accepting Mark's answer as the best one.

答:
As I posted on http://thinkinginsoftware.blogspot.com/2017/12/correctly-generate-csv-that-excel-can.html:

Tell the software developer in charge of generating the CSV to correct it. As a quick workaround you can use gsed to insert the UTF-8 BOM at the beginning of the string:

```<code>gsed -i '1s/^\(\xef\xbb\xbf\)\?/\xef\xbb\xbf/' file.csv
</code>```

This command inserts the UTF-4 BOM if not present. Therefore it is an idempotent command. Now you should be able to double click the file and open it in Excel.

Body:
As I posted on http://thinkinginsoftware.blogspot.com/2017/12/correctly-generate-csv-that-excel-can.html:

Tell the software developer in charge of generating the CSV to correct it. As a quick workaround you can use gsed to insert the UTF-8 BOM at the beginning of the string:

gsed -i '1s/^\(\xef\xbb\xbf\)\?/\xef\xbb\xbf/' file.csv

This command inserts the UTF-4 BOM if not present. Therefore it is an idempotent command. Now you should be able to double click the file and open it in Excel.


答: The solution was to modify a Config_Build.h file which caused the compile to NOT change the types of some standard C types.</p>

Title: C conflicting types caused by macro

Body:
I'm building some code that used to compile properly with an older version of Rowley Crossworks for ARM version 2. Now trying to compile the application with Crossworks for ARM version 4, the following header file causes the compiler to throw the following errors:

conflicting types for 'UEZMemAlloc'
 conflicting types for
  'UEZMemRealloc'

/*-------------------------------------------------------------------------*
 * File:  uEZMemory.h
 *-------------------------------------------------------------------------*
 * Description:
 *     uEZ Memory Allocation (thread safe) routines
 *-------------------------------------------------------------------------*/
#ifndef _UEZ_MEMORY_H_
#define _UEZ_MEMORY_H_

/*--------------------------------------------------------------------------
 * uEZ(R) - Copyright (C) 2007-2010 Future Designs, Inc.
 *--------------------------------------------------------------------------
 * This file is part of the uEZ(R) distribution.  See the included
 * uEZLicense.txt or visit http://www.teamfdi.com/uez for details.
 *
 *    *===============================================================*
 *    |  Future Designs, Inc. can port uEZ(tm) to your own hardware!  |
 *    |             We can get you up and running fast!               |
 *    |      See http://www.teamfdi.com/uez for more details.         |
 *    *===============================================================*
 *
 *-------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------*
 * Includes:
 *-------------------------------------------------------------------------*/
#include "uEZTypes.h"

#ifndef UEZ_MEM_CHECK_MEMORY
#define UEZ_MEM_CHECK_MEMORY    0
#endif
#ifndef UEZ_MEM_CHECK_MEMORY_FAIL_CALLBACK
#define UEZ_MEM_CHECK_MEMORY_FAIL_CALLBACK 0
#endif

/*-------------------------------------------------------------------------*
 * Prototypes:
 *-------------------------------------------------------------------------*/
void UEZMemInit(void);
void *UEZMemAlloc(TUInt32 aSize);
void *UEZStackMemAlloc(TUInt32 aSize);
void UEZMemFree(void *aMemory);
void *UEZMemRealloc(void *aMemory, TUInt32 aSize); //NOT IMPLEMENTED YET
void *UEZMemAllocPermanent(TUInt32 aSize);
void *UEZPlatformMemAllocPermanent(TUInt32 aSize);

#if UEZ_MEM_CHECK_MEMORY_FAIL_CALLBACK
void UEZMemFailedCallback(void);
#endif
#if UEZ_MEM_CHECK_MEMORY
TUInt32 UEZMemGetSize(void *aMemory);
TUInt32 UEZMemGetNumBlocks(void);
#endif

/*-------------------------------------------------------------------------*
 * Macros:
 *-------------------------------------------------------------------------*/
// Provide standard C compatible routines
#define malloc(a)           UEZMemAlloc(a)
#define free(a)             UEZMemFree(a)
#define realloc(a, b)       UEZMemRealloc(a, b)

#endif // _UEZ_MEMORY_H_

/*-------------------------------------------------------------------------*
 * End of File:  uEZMemory.h
 *-------------------------------------------------------------------------*/

It looks to me like the newer compiler is now irritated about:

#define malloc(a)           UEZMemAlloc(a)
#define realloc(a, b)       UEZMemRealloc(a, b)

The uEZ library I'm using has documentation here. It seems to be indicate it was done on purpose. Has the gcc compiler/preprocessor gotten more picky over time? Is there a way to avoid these errors? Rowley Crossworks for ARM uses GCC.


问:
Getting Keras trained model predictions in c#
As title states I'm trying to use my Keras (tf backend) pretrained model for predicitions in c#. What's the best approach?

I've tried IronPython but it gave me errors, after search I found it isn't supported. Simply calling python script won't work since target Windows devices won't have python interpreters installed.

答: it does not work like that, since you wont even be able to install tensorflow in a C# project. Abandon C# stack and learn framework in python stack instead, ex. if if you need to consume the prediction result in a web app, learn Flask or Django </p>


问:
Return data filtered on ngOnInit
In my component.ts I have a function that returns data from a service, and saves it to myPosts object. The function is called getData();
What I want to do is filter getData initially by date before calling it on ngOnInit().

So initially my table would display all last months' posts.
And then I should be able to change the date on another function and filter for different ranges.

My filtering functions are on the controller.
How do I call the filter Function after I get the data, so that initially that data is filtered on ngOnInit ?

```<code>public getData() {
this.postsService.getAllPosts().subscribe(results => {
  this.myPosts= results['data'];
});
}

filterByDate(){
  const monthAgo= moment().subtract(1, 'month');
   this.myPosts= this.myPosts.filter(item => moment(item.SubmittedDate).isAfter(monthAgo));
}
</code>```

答:
Create a method to filter and then assign the data as below,

```<code>filterByDate(myPosts){
  const monthAgo= moment().subtract(1, 'month');
   return myPosts.filter(item => moment(item.SubmittedDate).isAfter(monthAgo));
}
</code>```

In your onInit function, use that function

```<code>public getData() {
this.postsService.getAllPosts().subscribe(results => {
  this.myPosts= this.filterByDate(results['data']);
});
}
</code>```

Title: Return data filtered on ngOnInit

Body:
In my component.ts I have a function that returns data from a service, and saves it to myPosts object. The function is called getData();
What I want to do is filter getData initially by date before calling it on ngOnInit().

So initially my table would display all last months' posts.
And then I should be able to change the date on another function and filter for different ranges.

My filtering functions are on the controller.
How do I call the filter Function after I get the data, so that initially that data is filtered on ngOnInit ?

public getData() {
this.postsService.getAllPosts().subscribe(results => {
  this.myPosts= results['data'];
});
}

filterByDate(){
  const monthAgo= moment().subtract(1, 'month');
   this.myPosts= this.myPosts.filter(item => moment(item.SubmittedDate).isAfter(monthAgo));
}

Body:
Create a method to filter and then assign the data as below,

filterByDate(myPosts){
  const monthAgo= moment().subtract(1, 'month');
   return myPosts.filter(item => moment(item.SubmittedDate).isAfter(monthAgo));
}

In your onInit function, use that function

public getData() {
this.postsService.getAllPosts().subscribe(results => {
  this.myPosts= this.filterByDate(results['data']);
});
}