问:
VHDL Entity port does not match type of component port
I'm working on a MIPS-like CPU in VHDL with Xilinx Vivado. I have a component for my BranchControl module, which goes like this:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity BranchControl is
    Port ( PL : in STD_LOGIC;
           BC : in STD_LOGIC_VECTOR(3 downto 0);
           PC : in STD_LOGIC_VECTOR (31 downto 0);
           AD : in STD_LOGIC_VECTOR (31 downto 0);
           Flags : in STD_LOGIC_VECTOR(3 downto 0);
           PCLoad : out STD_LOGIC;
           PCValue : out STD_LOGIC_VECTOR (31 downto 0));
end BranchControl;

architecture Behavioral of branchcontrol is

signal Z,N,P,C,V, T: std_logic;

begin

Z <= Flags(3);        -- zero flag
N <= Flags(2);        -- negative flag
P <= not N and not Z; -- positive flag
C <= FLags(1);        -- carry flag
V <= Flags(0);        -- overflow flag

T <=
    '1' when (PL = '1') and (BC = "0000") and (Flags = "XXXX") else -- B
    '1' when (PL = '1') and (BC = "0010") and (Flags = "1XXX") else -- BEQ
    '1' when (PL = '1') and (BC = "0011") and (Flags = "0XXX") else -- BNE
    '1' when (PL = '1') and (BC = "0100") and (Flags = "00XX") else -- BGT
    '1' when (PL = '1') and (BC = "0101") and (Flags = "11XX") else -- BGE
    '1' when (PL = '1') and (BC = "0110") and (Flags = "01XX") else -- BLT
    '1' when (PL = '1') and (BC = "0111") and (Flags = "11XX") else -- BLE
    '0';

with T select
PCValue <= PC+AD when '1',
           PC when others;
PCLoad <= T;

end Behavioral;
</code>```

I am writing a simulation to test the BranchControl component, and ensure it is working as I intend. Here's my simulation:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity SimulBranchControl is
end SimulBranchControl;

architecture Behavioral of SimulBranchControl is

component BranchControl is
    Port ( PL : in STD_LOGIC;
           BC : in STD_LOGIC_VECTOR( 3 downto 0);
           PC : in STD_LOGIC_VECTOR (31 downto 0);
           AD : in STD_LOGIC_VECTOR (31 downto 0);
           Flags : in STD_LOGIC_VECTOR(3 downto 0);
           PCLoad : out STD_LOGIC;
           PCValue : out STD_LOGIC_VECTOR (31 downto 0));
end component;

signal iPL : STD_LOGIC;
signal iBC : STD_LOGIC_VECTOR(3 downto 0);
signal iPC : STD_LOGIC_VECTOR(31 downto 0);
signal iAD : STD_LOGIC_VECTOR(31 downto 0);
signal iFlags : STD_LOGIC_VECTOR(3 downto 0);

signal clock : std_logic := '0';

begin

    process
    begin
        wait for 50 ns;
        clock <= not clock;
    end process;

    process
    begin
        wait until clock'event and clock='0';
        iPL<='1'; iBC<="0010"; iPC<=x"00000000"; iAD<=x"00000001"; iFlags<="0000";

    end process;

BC0: BranchControl port map(iPL=>PL, iBC=>BC, iPC=>PC, iAD=>AD, iFlags=>Flags);

end Behavioral;
</code>```

For some reason, when I try and run the simulation in Vivado, I get a set of errors on the elaboration step:

```<code>INFO: [VRFC 10-163] Analyzing VHDL file "/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/BranchControl.vhd" into library xil_defaultlib
INFO: [VRFC 10-307] analyzing entity BranchControl
INFO: [VRFC 10-163] Analyzing VHDL file "/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd" into library xil_defaultlib
INFO: [VRFC 10-307] analyzing entity SimulBranchControl
ERROR: [VRFC 10-719] formal port/generic <ipl> is not declared in <branchcontrol> [/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd:43]
ERROR: [VRFC 10-704] formal pl has no actual or default value [/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd:43]
ERROR: [VRFC 10-1504] unit behavioral ignored due to previous errors [/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd:8]
INFO: [VRFC 10-240] VHDL file /home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd ignored due to errors
</code>```

Now, from what I understand this means that my entity BranchControl, and my my component of it on the Simulation have incompatible declarations, but I don't see how this is true, they seem exactly the same to me. Here's a screenshot of Vivado giving me the error.

Why is this happening? What am I doing wrong?

答:
Your component mapping in the instantiation is the wrong way around; it should be:</p>

```<code>bc0: BranchControl port map (pl => ipl, bc => ibc, pc => ipc, ad => iad, flags => iflags);
</code>```

Body:
I'm working on a MIPS-like CPU in VHDL with Xilinx Vivado. I have a component for my BranchControl module, which goes like this:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity BranchControl is
    Port ( PL : in STD_LOGIC;
           BC : in STD_LOGIC_VECTOR(3 downto 0);
           PC : in STD_LOGIC_VECTOR (31 downto 0);
           AD : in STD_LOGIC_VECTOR (31 downto 0);
           Flags : in STD_LOGIC_VECTOR(3 downto 0);
           PCLoad : out STD_LOGIC;
           PCValue : out STD_LOGIC_VECTOR (31 downto 0));
end BranchControl;

architecture Behavioral of branchcontrol is

signal Z,N,P,C,V, T: std_logic;

begin

Z <= Flags(3);        -- zero flag
N <= Flags(2);        -- negative flag
P <= not N and not Z; -- positive flag
C <= FLags(1);        -- carry flag
V <= Flags(0);        -- overflow flag

T <=
    '1' when (PL = '1') and (BC = "0000") and (Flags = "XXXX") else -- B
    '1' when (PL = '1') and (BC = "0010") and (Flags = "1XXX") else -- BEQ
    '1' when (PL = '1') and (BC = "0011") and (Flags = "0XXX") else -- BNE
    '1' when (PL = '1') and (BC = "0100") and (Flags = "00XX") else -- BGT
    '1' when (PL = '1') and (BC = "0101") and (Flags = "11XX") else -- BGE
    '1' when (PL = '1') and (BC = "0110") and (Flags = "01XX") else -- BLT
    '1' when (PL = '1') and (BC = "0111") and (Flags = "11XX") else -- BLE
    '0';

with T select
PCValue <= PC+AD when '1',
           PC when others;
PCLoad <= T;

end Behavioral;

I am writing a simulation to test the BranchControl component, and ensure it is working as I intend. Here's my simulation:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity SimulBranchControl is
end SimulBranchControl;

architecture Behavioral of SimulBranchControl is

component BranchControl is
    Port ( PL : in STD_LOGIC;
           BC : in STD_LOGIC_VECTOR( 3 downto 0);
           PC : in STD_LOGIC_VECTOR (31 downto 0);
           AD : in STD_LOGIC_VECTOR (31 downto 0);
           Flags : in STD_LOGIC_VECTOR(3 downto 0);
           PCLoad : out STD_LOGIC;
           PCValue : out STD_LOGIC_VECTOR (31 downto 0));
end component;

signal iPL : STD_LOGIC;
signal iBC : STD_LOGIC_VECTOR(3 downto 0);
signal iPC : STD_LOGIC_VECTOR(31 downto 0);
signal iAD : STD_LOGIC_VECTOR(31 downto 0);
signal iFlags : STD_LOGIC_VECTOR(3 downto 0);

signal clock : std_logic := '0';

begin

    process
    begin
        wait for 50 ns;
        clock <= not clock;
    end process;

    process
    begin
        wait until clock'event and clock='0';
        iPL<='1'; iBC<="0010"; iPC<=x"00000000"; iAD<=x"00000001"; iFlags<="0000";

    end process;

BC0: BranchControl port map(iPL=>PL, iBC=>BC, iPC=>PC, iAD=>AD, iFlags=>Flags);

end Behavioral;

For some reason, when I try and run the simulation in Vivado, I get a set of errors on the elaboration step:

INFO: [VRFC 10-163] Analyzing VHDL file "/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/BranchControl.vhd" into library xil_defaultlib
INFO: [VRFC 10-307] analyzing entity BranchControl
INFO: [VRFC 10-163] Analyzing VHDL file "/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd" into library xil_defaultlib
INFO: [VRFC 10-307] analyzing entity SimulBranchControl
ERROR: [VRFC 10-719] formal port/generic <ipl> is not declared in <branchcontrol> [/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd:43]
ERROR: [VRFC 10-704] formal pl has no actual or default value [/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd:43]
ERROR: [VRFC 10-1504] unit behavioral ignored due to previous errors [/home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd:8]
INFO: [VRFC 10-240] VHDL file /home/meurer/src/acomp/L02/Project2/Project2.srcs/sim_1/new/SimulBranchControl.vhd ignored due to errors

Now, from what I understand this means that my entity BranchControl, and my my component of it on the Simulation have incompatible declarations, but I don't see how this is true, they seem exactly the same to me. Here's a screenshot of Vivado giving me the error.

Why is this happening? What am I doing wrong?

Body:
Your component mapping in the instantiation is the wrong way around; it should be:

bc0: BranchControl port map (pl => ipl, bc => ibc, pc => ipc, ad => iad, flags => iflags);


来源: stackexchange

问:
How do I echo strings on the same line as a previous echo?
How do I echo "I have 1 number" using two echo commands in a batch file?

```<code>echo "I have "
...
... do stuff
...
echo "1 number"
</code>```

creates two lines:

```<code>I have
1 number
</code>```

how do I suppress the cr/lf on the first echo?  to create:

```<code>I have 1 number
</code>```

答:
Perhaps I am missing part of the problem. Save the first part in a variable, then use it later with the latter part.

```<code>SET "PART_1=I have "
.
... do stuff
.
ECHO %PART_1% 1 number
</code>```

How about...

```<code>C:\Users\lit\t>ECHO SET "currentdir=%CD%" >a.bat

C:\Users\lit\t>type a.bat
SET "currentdir=C:\Users\lit\t"
</code>```

Multiple lines...? The ECHO command writes a newline CRLF at the end of anything it outputs. You are not going to get a subsequent ECHO command to write over the newline from the first ECHO. How about...

```<code>SET TMPFILE=%TEMP%\mytempfile.tmp
ECHO>"%TMPFILE%" I have
... do stuff
FOR /F "usebackq tokens=*" %%a IN (`TYPE "%TMPFILE%"`) DO (SET "S1=%%~a")
ECHO %S1% 1 file
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I echo "I have 1 number" using two echo commands in a batch file?

echo "I have "
...
... do stuff
...
echo "1 number"

creates two lines:

I have
1 number

how do I suppress the cr/lf on the first echo?  to create:

I have 1 number

Body:
Perhaps I am missing part of the problem. Save the first part in a variable, then use it later with the latter part.

SET "PART_1=I have "
.
... do stuff
.
ECHO %PART_1% 1 number

How about...

C:\Users\lit\t>ECHO SET "currentdir=%CD%" >a.bat

C:\Users\lit\t>type a.bat
SET "currentdir=C:\Users\lit\t"

Multiple lines...? The ECHO command writes a newline CRLF at the end of anything it outputs. You are not going to get a subsequent ECHO command to write over the newline from the first ECHO. How about...

SET TMPFILE=%TEMP%\mytempfile.tmp
ECHO>"%TMPFILE%" I have
... do stuff
FOR /F "usebackq tokens=*" %%a IN (`TYPE "%TMPFILE%"`) DO (SET "S1=%%~a")
ECHO %S1% 1 file
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")


问:
How do I upgrade my PHP 4.0 login script to PHP 5.6?
my script below worked perfect on PHP 4.0 but my ISP upgraded to PHP 5.6 and now there seems to be something wrong (it does not connect to mySQL, etc), any help is appreciated

Many thanks

```<code><?php
$userdb="var1";
$pass="var2";
$database="var3";

mysql_connect("sql.servername.com",$userdb,$pass);
@mysql_select_db($database) or die ( header('location: status4.htm') );
$match = "select id from USER_ACCOUNTS where username = '$username' and password = '$password'";
$qry = mysql_query($match)
or die ( header('location: status.htm?status=9') );
$num_rows = mysql_num_rows($qry);

// Valid Username and Password
if ($num_rows > 0) {
$qry = "SELECT * FROM USER_ACCOUNTS WHERE username like '%" . $username . "%'";
$res = mysql_query($qry);
$output='';
while($row = mysql_fetch_assoc($res)){
// loop through all returned results
$output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
echo "&status=1";
echo $output;
}
}
?>
</code>```

Here is the mySQL 4.0 Table

```<code>id  viewUsername    viewPassword    username    password    name    title   email   admin   file    file2   file3   file4

1                                   user1       pass123     USER1   Manager email1   1      file1   file2   file3   file4
</code>```

答:
Here you go example with PDO prepared statements

```<code><?php

error_reporting(1);
ini_set('display_errors', '1');

// mysql connection
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'mydatabase';

$dbh = new PDO('mysql:host='.$db_host.';dbname='.$db_name.';charset=utf8', $db_user, $db_pass);

// submit form
if (isset($_POST['submit']))
{

    $username = $_POST['username'];
    $password = $_POST['password'];

    $stmt = $dbh->prepare("SELECT * FROM USER_ACCOUNTS WHERE username = :username AND password = :password");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    $stmt->execute();
    $number_of_rows = $stmt->fetchColumn();

    // Valid Username and Password
    if ($number_of_rows > 0)
    {
        $row = $stmt->fetchAll();

        $output = '';

        while($row)
        {
            // loop through all returned results
            $output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
            echo "&status=1";
            echo $output;
        }
    }

}

?>
</code>```

And html form

```<code><form action="" method="post">
    <input type="text" name="username" placeholder="Username"><br />
    <input type="password" name="password" placeholder="Password"><br />
    <input type="submit" name="submit" value="Login">
</form>
</code>```

Update

```<code><?php

error_reporting(1);
ini_set('display_errors', '1');

// mysql connection
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'mydatabase';

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

/* check connection */
if (mysqli_connect_errno())
{
    echo "Connect failed: " . mysqli_connect_error();
    exit();
}

// submit form
if (isset($_POST['submit']))
{

    $username = $_POST['username'];
    $password = $_POST['password'];

    /* create a prepared statement */
    if ($stmt = $mysqli->prepare("SELECT * FROM USER_ACCOUNTS WHERE username = ? AND password = ?"))
    {
        /* bind parameters for markers */
        $stmt->bind_param("s", $username);
        $stmt->bind_param("s", $password);

        /* execute query */
        $stmt->execute();

        $number_of_rows = $stmt->rowCount();

        // Valid Username and Password
        if ($number_of_rows > 0)
        {
            $row = $stmt->fetchAll();

            $output = '';

            while($row)
            {
                // loop through all returned results
                $output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
                echo "&status=1";
                echo $output;
            }
        }

        /* close statement */
        $stmt->close();
    }
}
$mysqli->close();
?>
</code>```

And try this

```<code><?php

error_reporting(1);
ini_set('display_errors', '1');

$conn = mysqli_connect('host', 'username', 'password', 'table name');

/* check connection */
if (mysqli_connect_errno())
{
    echo "Connect failed: " . mysqli_connect_error();
    exit();
}

// submit form
if (isset($_POST['submit']))
{

    $username = $_POST['username'];
    $password = $_POST['password'];

    $query = mysqli_query($conn, "SELECT * FROM USER_ACCOUNTS WHERE username = '$username' AND password = '$password'");

    if ($query)
    {
        // Valid Username and Password
        if (mysqli_row_count($query) > 0)
        {
            $row = mysqli_fetch_array($query);

            $output = '';

            while($row)
            {
                // loop through all returned results
                $output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
                echo "&status=1";
                echo $output;
            }
        }
    }
}

?>
</code>```

Body:
my script below worked perfect on PHP 4.0 but my ISP upgraded to PHP 5.6 and now there seems to be something wrong (it does not connect to mySQL, etc), any help is appreciated

Many thanks

<?php
$userdb="var1";
$pass="var2";
$database="var3";

mysql_connect("sql.servername.com",$userdb,$pass);
@mysql_select_db($database) or die ( header('location: status4.htm') );
$match = "select id from USER_ACCOUNTS where username = '$username' and password = '$password'";
$qry = mysql_query($match)
or die ( header('location: status.htm?status=9') );
$num_rows = mysql_num_rows($qry);

// Valid Username and Password
if ($num_rows > 0) {
$qry = "SELECT * FROM USER_ACCOUNTS WHERE username like '%" . $username . "%'";
$res = mysql_query($qry);
$output='';
while($row = mysql_fetch_assoc($res)){
// loop through all returned results
$output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
echo "&status=1";
echo $output;
}
}
?>

Here is the mySQL 4.0 Table

id  viewUsername    viewPassword    username    password    name    title   email   admin   file    file2   file3   file4

1                                   user1       pass123     USER1   Manager email1   1      file1   file2   file3   file4

Body:
Here you go example with PDO prepared statements

<?php

error_reporting(1);
ini_set('display_errors', '1');

// mysql connection
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'mydatabase';

$dbh = new PDO('mysql:host='.$db_host.';dbname='.$db_name.';charset=utf8', $db_user, $db_pass);

// submit form
if (isset($_POST['submit']))
{

    $username = $_POST['username'];
    $password = $_POST['password'];

    $stmt = $dbh->prepare("SELECT * FROM USER_ACCOUNTS WHERE username = :username AND password = :password");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    $stmt->execute();
    $number_of_rows = $stmt->fetchColumn();

    // Valid Username and Password
    if ($number_of_rows > 0)
    {
        $row = $stmt->fetchAll();

        $output = '';

        while($row)
        {
            // loop through all returned results
            $output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
            echo "&status=1";
            echo $output;
        }
    }

}

?>

And html form

<form action="" method="post">
    <input type="text" name="username" placeholder="Username"><br />
    <input type="password" name="password" placeholder="Password"><br />
    <input type="submit" name="submit" value="Login">
</form>

Update

<?php

error_reporting(1);
ini_set('display_errors', '1');

// mysql connection
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'mydatabase';

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

/* check connection */
if (mysqli_connect_errno())
{
    echo "Connect failed: " . mysqli_connect_error();
    exit();
}

// submit form
if (isset($_POST['submit']))
{

    $username = $_POST['username'];
    $password = $_POST['password'];

    /* create a prepared statement */
    if ($stmt = $mysqli->prepare("SELECT * FROM USER_ACCOUNTS WHERE username = ? AND password = ?"))
    {
        /* bind parameters for markers */
        $stmt->bind_param("s", $username);
        $stmt->bind_param("s", $password);

        /* execute query */
        $stmt->execute();

        $number_of_rows = $stmt->rowCount();

        // Valid Username and Password
        if ($number_of_rows > 0)
        {
            $row = $stmt->fetchAll();

            $output = '';

            while($row)
            {
                // loop through all returned results
                $output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
                echo "&status=1";
                echo $output;
            }
        }

        /* close statement */
        $stmt->close();
    }
}
$mysqli->close();
?>

And try this

<?php

error_reporting(1);
ini_set('display_errors', '1');

$conn = mysqli_connect('host', 'username', 'password', 'table name');

/* check connection */
if (mysqli_connect_errno())
{
    echo "Connect failed: " . mysqli_connect_error();
    exit();
}

// submit form
if (isset($_POST['submit']))
{

    $username = $_POST['username'];
    $password = $_POST['password'];

    $query = mysqli_query($conn, "SELECT * FROM USER_ACCOUNTS WHERE username = '$username' AND password = '$password'");

    if ($query)
    {
        // Valid Username and Password
        if (mysqli_row_count($query) > 0)
        {
            $row = mysqli_fetch_array($query);

            $output = '';

            while($row)
            {
                // loop through all returned results
                $output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
                echo "&status=1";
                echo $output;
            }
        }
    }
}

?>


问:
How to find out if a cookie is already there?
So I do simple JS function like

```<code>function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

}
</code>```

how tm make sure that users_resolution is set?

答:
You might want to use indexOf to check whether it exists or not:

```<code>if(document.cookie.indexOf('users_resolution=') > 0){
  // cookie was set
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
So I do simple JS function like

function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

}

how tm make sure that users_resolution is set?

Body:
You might want to use indexOf to check whether it exists or not:

if(document.cookie.indexOf('users_resolution=') > 0){
  // cookie was set
}


问:
Access VB - Shell string problems
Trying to create the string for use with the Shell command in Access VB.  The string works if written in full but if I try to use variables in the string the command does not work even if the use of variables produces exactly the full string, (in the immediate window), that works.

I suspect something is going on in the interpretation of the string version of the code but can't work out what.

Here's the code, I have used CHR(34) to produce the quotation marks that I want to show in the string.  Suggestions would be so much appreciated - I don't have much hair left!

Private Sub temp()

Dim strFilePath As String

Dim strFileName As String

Dim strZipFilename As String

Dim strPDFfilename As String

Dim strShellString As String

Dim shell As Object

Dim result As Long

```<code>Set shell = CreateObject("WScript.shell")

strFilePath = "E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs"
strFileName = "17-03-31temp"
strZipFilename = strFilePath & "\" & strFileName & ".zip"
strZipFilename = Chr(34) & strZipFilename & Chr(34)
strPDFfilename = strFilePath & "\" & strFileName & ".pdf"
strPDFfilename = Chr(34) & strPDFfilename & Chr(34)
strShellString = Chr(34) & Chr(34) & Chr(34) & "C:\Program Files\7-Zip\7z.exe" & Chr(34) & Chr(34) & " a -tzip " & Chr(34) & strZipFilename & Chr(34) & " " & Chr(34) & strPDFfilename & Chr(34) & Chr(34)
</code>```

'Non Working shell command

result = shell.Run(strShellString, 0, False)

'Working shell command

```<code>result = shell.Run("""C:\Program Files\7-Zip\7z.exe"" a -tzip ""E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs\17-03-31temp.zip"" ""E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs\17-03-31temp.pdf""", 0, False)
</code>```

'Immediate Window output of strShellString

'                      """C:\Program Files\7-Zip\7z.exe"" a -tzip ""E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs\17-03-31temp.zip"" ""E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs\17-03-31temp.pdf"""

End Sub

答:
My hair is saved - I worked out the answer!  So, for posterity here it is.

I modified strFilePath to put quotes around the two word folder names and removed quotations from around the strZipFilename and strPDFFilename lines.  I guess Shell was suffering from a surfeit of quotes.

Whilst modifying it I added a password to the zip file and changed the false to true at the end of the string command so that it would return an error code.

Thanks to anyone who spent time trying to work out what I had done.

Public Sub temp()

Dim strFilePath As String

Dim strFileName As String

Dim strZipFilename As String

Dim strPDFfilename As String

Dim strPassword As String

Dim shell As Object

Dim result As Long

```<code>Set shell = CreateObject("WScript.shell")

strPassword = "frog"
strFilePath = "E:\Documents\""Excel Spreadsheets""\""Roz Theremas""\Access\PDFs"
strFileName = "17-03-31temp"
strZipFilename = strFilePath & "\" & strFileName & ".zip"
strPDFfilename = strFilePath & "\" & strFileName & ".pdf"

result = shell.Run("""C:\Program Files\7-Zip\7z.exe"" a -tzip " & "-p" & strPassword & " " & strZipFilename & " " & strPDFfilename, 0, True)
</code>```

Title: Access VB - Shell string problems

Body:
Trying to create the string for use with the Shell command in Access VB.  The string works if written in full but if I try to use variables in the string the command does not work even if the use of variables produces exactly the full string, (in the immediate window), that works.

I suspect something is going on in the interpretation of the string version of the code but can't work out what.

Here's the code, I have used CHR(34) to produce the quotation marks that I want to show in the string.  Suggestions would be so much appreciated - I don't have much hair left!

Private Sub temp()

Dim strFilePath As String

Dim strFileName As String

Dim strZipFilename As String

Dim strPDFfilename As String

Dim strShellString As String

Dim shell As Object

Dim result As Long

Set shell = CreateObject("WScript.shell")

strFilePath = "E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs"
strFileName = "17-03-31temp"
strZipFilename = strFilePath & "\" & strFileName & ".zip"
strZipFilename = Chr(34) & strZipFilename & Chr(34)
strPDFfilename = strFilePath & "\" & strFileName & ".pdf"
strPDFfilename = Chr(34) & strPDFfilename & Chr(34)
strShellString = Chr(34) & Chr(34) & Chr(34) & "C:\Program Files\7-Zip\7z.exe" & Chr(34) & Chr(34) & " a -tzip " & Chr(34) & strZipFilename & Chr(34) & " " & Chr(34) & strPDFfilename & Chr(34) & Chr(34)

'Non Working shell command

result = shell.Run(strShellString, 0, False)

'Working shell command

result = shell.Run("""C:\Program Files\7-Zip\7z.exe"" a -tzip ""E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs\17-03-31temp.zip"" ""E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs\17-03-31temp.pdf""", 0, False)

'Immediate Window output of strShellString

'                      """C:\Program Files\7-Zip\7z.exe"" a -tzip ""E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs\17-03-31temp.zip"" ""E:\Documents\Excel Spreadsheets\Roz Theremas\Access\PDFs\17-03-31temp.pdf"""

End Sub

Body:
My hair is saved - I worked out the answer!  So, for posterity here it is.

I modified strFilePath to put quotes around the two word folder names and removed quotations from around the strZipFilename and strPDFFilename lines.  I guess Shell was suffering from a surfeit of quotes.

Whilst modifying it I added a password to the zip file and changed the false to true at the end of the string command so that it would return an error code.

Thanks to anyone who spent time trying to work out what I had done.

Public Sub temp()

Dim strFilePath As String

Dim strFileName As String

Dim strZipFilename As String

Dim strPDFfilename As String

Dim strPassword As String

Dim shell As Object

Dim result As Long

Set shell = CreateObject("WScript.shell")

strPassword = "frog"
strFilePath = "E:\Documents\""Excel Spreadsheets""\""Roz Theremas""\Access\PDFs"
strFileName = "17-03-31temp"
strZipFilename = strFilePath & "\" & strFileName & ".zip"
strPDFfilename = strFilePath & "\" & strFileName & ".pdf"

result = shell.Run("""C:\Program Files\7-Zip\7z.exe"" a -tzip " & "-p" & strPassword & " " & strZipFilename & " " & strPDFfilename, 0, True)


问:
Hide/Show left sidebar on mouse hover
What css/js function can be used to make my left sidebar hide/show on mouse hover, so if my mouse is somewhere in the middle of screen, google iframe from code will be displayed at whole page, but if i put my mouse on the left, sidebar will be visible and google iframe will be less sized?

body {
    padding-top: 70px; /* Padding for .navbar-fixed-top. Change value if navbar height changes. Remove if using .navbar-static-top. */
}

h1, h2, h3, h4, h5, h6 {
 color: black;
 }

#side-carousel img {
 margin: 0 auto;
 }

.footer-blurb {
    padding: 30px 0;
    margin-top: 20px;
    background-color: #eee;
    color: black;
}

.footer-blurb-item {
    padding: 20px;
    }

.small-print {
 background-color: #fff;
 padding: 30px 0;
}

.feature,
.page-intro,
.article-intro,
.small-print {
 text-align: center;
 }

 .extra {
    display: none;
}

p:hover .extra {
    display: block;
}

.box{
    display: none;
    width: 100%;
}

a:hover + .box,.box:hover{
    display: block;
    position: relative;
    z-index: 100;
}

* {
 box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 10px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 6px;
  text-decoration: none;
  font-size: 12px;
  color: black;
  display: block
}

#myUL li a.header {
  background-color: #e2e2e2;
  cursor: default;
}

#myUL li {
 display: none;
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->

    <title>Testing Page</title>

    <!-- Bootstrap Core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS: You can use this stylesheet to override any Bootstrap styles and/or apply your own styles -->
    <link href="css/custom.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

    <!-- Navigation -->
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container">
            <!-- Logo and responsive toggle -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>

   <!-- Search --></div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container -->
    </nav>

<div class="container-fluid">

  <!-- Left Column -->
  <div style="overflow: hidden; margin: 1px auto; max-width: 2736px;">
          <iframe src="http://google.com" width="2500px" height="1200"> </iframe>
  </div>
  <div class="col-sm-3">
<div class="panel panel-default">
<center>
<p><center><center><b>
<p class="tooltip-inner">asasassa</p>
<p class="tooltip-inner">as</p>
<p class="tooltip-inner">sa</p>
<p class="tooltip-inner">as</p>
<p class="tooltip-inner">asas</p>
<p class="tooltip-inner"> </p>
<p class="tooltip-inner">as</p>
<p class="tooltip-inner">as</p>
<p class="tooltip-inner">as</p>
<p class="tooltip-inner">asas</p>
<p class="tooltip-inner">as</p>
<p class="tooltip-inner">s</p>
<p class="tooltip-inner">a</p>
</b>
</div></div>
</div>
     </div>
   </div>
   <!-- List-Group Panel --><!--/Left Column-->

  <!-- Center Column -->
  <div class="col-sm-6">

   <!-- Alert -->

   <!-- Articles -->
   <div class="row"></div>
   <div class="row"></div>
   <div class="row"></div>
  </div><!--/Center Column-->

   <!-- Right Column --><!--/Right Column -->

</div><!--/container-fluid--><!-- jQuery -->
    <script src="js/jquery-1.11.3.min.js"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="js/bootstrap.min.js"></script>

 <!-- IE10 viewport bug workaround -->
 <script src="js/ie10-viewport-bug-workaround.js"></script>

 <!-- Placeholder Images -->
 <script src="js/holder.min.js"></script>

    <!-- Searchable Driver List -->
 <script src="js/driverlist.js"></script>
</body>

</html></code>```

答:
You can handle the events with .mouseover() and .mouseout()

To change the size of an element take a look at .height() and .width()

Try to read through the JQuery docs everything is explained there quite good:

https://api.jquery.com/mouseout/

http://api.jquery.com/height/

I hope that helps

Title: Hide/Show left sidebar on mouse hover

Body:
What css/js function can be used to make my left sidebar hide/show on mouse hover, so if my mouse is somewhere in the middle of screen, google iframe from code will be displayed at whole page, but if i put my mouse on the left, sidebar will be visible and google iframe will be less sized?

body {
    padding-top: 70px; /* Padding for .navbar-fixed-top. Change value if navbar height changes. Remove if using .navbar-static-top. */
}

h1, h2, h3, h4, h5, h6 {
 color: black;
 }

#side-carousel img {
 margin: 0 auto;
 }

.footer-blurb {
    padding: 30px 0;
    margin-top: 20px;
    background-color: #eee;
    color: black;
}

.footer-blurb-item {
    padding: 20px;
    }

.small-print {
 background-color: #fff;
 padding: 30px 0;
}

.feature,
.page-intro,
.article-intro,
.small-print {
 text-align: center;
 }

 .extra {
    display: none;
}

p:hover .extra {
    display: block;
}

.box{
    display: none;
    width: 100%;
}

a:hover + .box,.box:hover{
    display: block;
    position: relative;
    z-index: 100;
}

* {
 box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 10px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 6px;
  text-decoration: none;
  font-size: 12px;
  color: black;
  display: block
}

#myUL li a.header {
  background-color: #e2e2e2;
  cursor: default;
}

#myUL li {
 display: none;
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Testing Page</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/custom.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                    Toggle navigation

                </button>

asasassa

as

sa

as

asas

as

as

as

asas

as

s

a


问:
Circular list iterator in Python
I need to iterate over a circular list, possibly many times, each time starting with the last visited item.

The use case is a connection pool. A client asks for connection, an iterator checks if pointed-to connection is available and returns it, otherwise loops until it finds one that is available.

How can I do this neatly in Python?

If you instead need an immediately created list of the results up to a certain length, rather than iterating on demand: see Repeat list to max number of elements for general techniques, and How to replicate array to specific length array for Numpy-specific techniques.

答:
you can accomplish this with append(pop()) loop:

```<code>l = ['a','b','c','d']
while True:
    print l[0]
    l.append(l.pop(0))
</code>```

or for i in range() loop:

```<code>l = ['a','b','c','d']
ll = len(l)
while True:
    for i in range(ll):
       print l[i]
</code>```

or simply:

```<code>l = ['a','b','c','d']

while True:
    for i in l:
       print i
</code>```

all of which print:

```<code>>>>
a
b
c
d
a
b
c
d
...etc.
</code>```

of the three I'd be prone to the append(pop()) approach as a function

```<code>servers = ['a','b','c','d']

def rotate_servers(servers):
    servers.append(servers.pop(0))
    return servers

while True:
    servers = rotate_servers(servers)
    print servers[0]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Circular list iterator in Python

Body:
you can accomplish this with append(pop()) loop:

l = ['a','b','c','d']
while True:
    print l[0]
    l.append(l.pop(0))

or for i in range() loop:

l = ['a','b','c','d']
ll = len(l)
while True:
    for i in range(ll):
       print l[i]

or simply:

l = ['a','b','c','d']

while True:
    for i in l:
       print i

all of which print:

>>>
a
b
c
d
a
b
c
d
...etc.

of the three I'd be prone to the append(pop()) approach as a function

servers = ['a','b','c','d']

def rotate_servers(servers):
    servers.append(servers.pop(0))
    return servers

while True:
    servers = rotate_servers(servers)
    print servers[0]


问:
HTML code is not work on Chrome and server?
I have a simple HTML page which is gets pictures from the JSON file by using ResponsiveSlides.js it is work in Firefox but it is not shows empty page in other browser and also when I run it  from the server it is just shows the picture separately without animation? What should I do to run my HTML in all browsers and server?

```<code>    <!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ResponsiveSlides.js/1.55/responsiveslides.min.js"></script>

</head>
<body>

<div>
<ul id="exampleSlider">
</ul>
</div>

<script type="text/javascript">
    $.getJSON('slides.json', function(data) {
    $("h2").html(data[0].title);
        $.each(data, function (i, f) {
            if(i>0){
                $("#exampleSlider").append("<li><a><img src=" + f.content + "></img></a><p>"+f.title+"</p></li>");
                $("a").attr("href", "#");
            }
        });
   });

    $(function () {
      $("#exampleSlider").responsiveSlides({
        auto: true,
        pause: true,
        speed: 1200,
        timeout: 3000
      });
});
</script>
</body>
</html>
</code>```

答:
You should initialize the responsiveSlides after you have inserted your images in the page (after the AJAX is complete).

$(function() {

  $.getJSON('slides.json', function(data) {

    $("h2").html(data[0].title);

    $.each(data, function(i, f) {
      if (i > 0) {
        $("#exampleSlider").append("

" + f.title + "

");
        $("a").attr("href", "#");
      }
    });

    $("#exampleSlider").responsiveSlides({
      auto: true,
      pause: true,
      speed: 1200,
      timeout: 3000
    });

  });

});
```

Body:
I have a simple HTML page which is gets pictures from the JSON file by using ResponsiveSlides.js it is work in Firefox but it is not shows empty page in other browser and also when I run it  from the server it is just shows the picture separately without animation? What should I do to run my HTML in all browsers and server?

    <!DOCTYPE html>

    <title></title>

Body:
You should initialize the responsiveSlides after you have inserted your images in the page (after the AJAX is complete).

$(function() {

  $.getJSON('slides.json', function(data) {

    $("h2").html(data[0].title);

    $.each(data, function(i, f) {
      if (i > 0) {
        $("#exampleSlider").append("<li><a><img src=" + f.content + "></img></a><p>" + f.title + "</p></li>");
        $("a").attr("href", "#");
      }
    });

    $("#exampleSlider").responsiveSlides({
      auto: true,
      pause: true,
      speed: 1200,
      timeout: 3000
    });

  });

});


问:
HDFS block size and its relationship with underlying physical file-system block size
I am trying to understand the relationship between the HDFS file-system block size and the underlying physical file-system block size.

As per my understanding hdfs is just a virtual file-system which stores the actual data on the underlying physical file-system. The HDFS block size in hadoop 2 is 128 MB; however in most of the linux based file-systems the block size is 4 KB.

My questions:

Q1) When a HDFS block is written to the actual file-system, does it write to multiple block of the underlying file-system? That is for a single HDFS blocks, it has to write to 128 * 1024 KB / 4 KB --> 32,768 blocks?

Q2) If above is correct, doesn't it involve lot of seeks on the disk head? Isn't it time consuming process? How is Hadoop to make this process efficiently?

Can anyone help me understand this?

答:
There's no connection between the two at all.  The 128MB block size in HDFS just means that HDFS doesn't produce files bigger than 128MB.  When it needs to store a larger amount of data, it divides it into several files.  But the 128MB files created by HDFS are no different than 128MB files created by any other program.

You're correct that having lots of 4k blocks scattered all over the disk can lead to lots of disk seeks when accessing the file.  To avoid that, when the operating system allocates space on disk for a file – any file, not just one created by HDFS – it tries to choose blocks that are adjacent to each other, so that the disk can seek once and then read or write all the blocks together.

For more information, read about disk fragmentation.


问:
Exceeding max redirects when attempting to scrape a webpage?
I'm attempting to scrape a webpage in Node.js.

```<code>var request = require('request').defaults({maxRedirects:3});

let url = "https://webapp4.asu.edu/catalog/classlist?k=81684&t=2177&e=all&hon=F&promod=F"
// , qs:propertiesObject
request({url:url}, function(err, response, body) {
  if(err) { console.log(err); return; }
  console.log("Get response: " + response.statusCode);
});
</code>```

I'm getting max number of redirects for some reason. I can do a get request in postman and I can visit the page just fine. What would I do to cause redirects to happen?

答:
Best Pratice: You should always check for a robots.txt file before scraping a webpage.  I was unable to locate one for this specific site, but if you do come across a site that does not allow scraping you should follow all rules.

That being said, it seems as if your scraper is getting stuck in an infinite redirect loop due to the lack of headers on the outgoing request.

Something like the below will get you a response, but you will need to determine what parsing needs to be done to extract information from it.

```<code>var request = require('request');

var options = {
  url: 'https://webapp4.asu.edu/catalog/classlist?k=81684&t=2177&e=all&hon=F&promod=F',
  headers: {
    "method":"GET",
    "path":"/catalog/classlist?k=math&t=2177&e=all&hon=F&promod=F",
    "scheme":"https",
    "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "accept-encoding":"gzip, deflate, sdch, br",
    "accept-language":"en-US,en;q=0.8",
    "cache-control":"no-cache",
    "cookie":"JSESSIONID=javaprod19~413DF4150236B1466C8ECB85EB796C06.catalog19; onlineCampusSelection=C; __cfduid=d5e9cb96f2485f7500fec2116ee8f23381491087061; __utma=59190898.1874896314.1491088625.1491088625.1491088625.1; __utmb=59190898.2.10.1491088625; __utmc=59190898; __utmz=59190898.1491088625.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=137925942.2000995260.1491087063.1491087063.1491088718.2; __utmb=137925942.2.10.1491088718; __utmc=137925942; __utmz=137925942.1491088718.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); ADRUM=s=1491089349546&r=https%3A%2F%2Fwebapp4.asu.edu%2Fcatalog%2Fclasslist%3F-1275642430",
    "pragma":"no-cache",
    "referer":"https://webapp4.asu.edu/catalog/",
    "upgrade-insecure-requests":"1",
    "user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
  }
};

function callback(error, response, body) {

    console.log(response.body)

}
request(options, callback);
</code>```

Body:
I'm attempting to scrape a webpage in Node.js.

var request = require('request').defaults({maxRedirects:3});

let url = "https://webapp4.asu.edu/catalog/classlist?k=81684&t=2177&e=all&hon=F&promod=F"
// , qs:propertiesObject
request({url:url}, function(err, response, body) {
  if(err) { console.log(err); return; }
  console.log("Get response: " + response.statusCode);
});

I'm getting max number of redirects for some reason. I can do a get request in postman and I can visit the page just fine. What would I do to cause redirects to happen?

Body:
Best Pratice: You should always check for a robots.txt file before scraping a webpage.  I was unable to locate one for this specific site, but if you do come across a site that does not allow scraping you should follow all rules.

That being said, it seems as if your scraper is getting stuck in an infinite redirect loop due to the lack of headers on the outgoing request.

Something like the below will get you a response, but you will need to determine what parsing needs to be done to extract information from it.

var request = require('request');

var options = {
  url: 'https://webapp4.asu.edu/catalog/classlist?k=81684&t=2177&e=all&hon=F&promod=F',
  headers: {
    "method":"GET",
    "path":"/catalog/classlist?k=math&t=2177&e=all&hon=F&promod=F",
    "scheme":"https",
    "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "accept-encoding":"gzip, deflate, sdch, br",
    "accept-language":"en-US,en;q=0.8",
    "cache-control":"no-cache",
    "cookie":"JSESSIONID=javaprod19~413DF4150236B1466C8ECB85EB796C06.catalog19; onlineCampusSelection=C; __cfduid=d5e9cb96f2485f7500fec2116ee8f23381491087061; __utma=59190898.1874896314.1491088625.1491088625.1491088625.1; __utmb=59190898.2.10.1491088625; __utmc=59190898; __utmz=59190898.1491088625.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=137925942.2000995260.1491087063.1491087063.1491088718.2; __utmb=137925942.2.10.1491088718; __utmc=137925942; __utmz=137925942.1491088718.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); ADRUM=s=1491089349546&r=https%3A%2F%2Fwebapp4.asu.edu%2Fcatalog%2Fclasslist%3F-1275642430",
    "pragma":"no-cache",
    "referer":"https://webapp4.asu.edu/catalog/",
    "upgrade-insecure-requests":"1",
    "user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
  }
};

function callback(error, response, body) {

    console.log(response.body)

}
request(options, callback);


问:
Python - Use values from 1D array as column indices for 2D array
Little tricky to explain it with few words (and google it), so:

I have this 2D np array:

```<code>import numpy as np

x = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14],[15,16,17]])
</code>```

and this 1D np array:

```<code>y = np.array([0,2,1,0,2,0])
</code>```

what I would like to do is to return the column values from x using y as a (column) index, so it will return something like this:

```<code>[0, 5, 7, 9, 14, 15]
</code>```

in ugly-code it would be solved like this:

```<code>for row,col in zip(x,y):
    print(row[col])
</code>```

and in a not-so-ugly code:

```<code>[row[col] for row,col in zip(x,y)]
</code>```

Is there another way solve this? I would like something like:

```<code>x[y]
</code>```

or a numpy specific function.

答:
You can use advanced indexing:</p>

```<code>x[np.arange(6), y]
# array([ 0,  5,  7,  9, 14, 15])
</code>```

Body:
Little tricky to explain it with few words (and google it), so:

I have this 2D np array:

import numpy as np

x = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14],[15,16,17]])

and this 1D np array:

y = np.array([0,2,1,0,2,0])

what I would like to do is to return the column values from x using y as a (column) index, so it will return something like this:

[0, 5, 7, 9, 14, 15]

in ugly-code it would be solved like this:

for row,col in zip(x,y):
    print(row[col])

and in a not-so-ugly code:

[row[col] for row,col in zip(x,y)]

Is there another way solve this? I would like something like:

x[y]

or a numpy specific function.

Body:
You can use advanced indexing:

x[np.arange(6), y]
# array([ 0,  5,  7,  9, 14, 15])


问:
Rails - Generating multiple pages dynamically based on database records
I have a rails app and I need to loop through records in a database and match them with records in the same database then render a page with content that is based on the words present in the URL.

So imagine we have this database:

```<code>1 Basketball
2 Soccer
3 Baseball
4 Swimming
</code>```

I need to build a function that generates a page for each:

```<code>domain.com/basketball-soccer
domain.com/basketball-baseball
domain.com/basketball-swimming
domain.com/soccer-baseball
domain.com/soccer-swimming
domain.com/baseball-swimming
</code>```

This shouldn't generate pages for basketball-basketball, etc. and if it generates a page for basketball-soccer, page for soccer-basketball

also a page like domain.com/basketball-cricket because cricket isn't listed in the database

Example of how the content should display on each page:
This page is for a Basketball / Soccer match.

Looking for suggestions or resources on getting started with this. I'm not sure if it's possible to generate pages on the fly like this. I don't want to build each of these pages individually.

答:
You can do this with a wildcard (catch all) route, and then handle all the logic inside the controller. For example:

```<code># routes.rb
# put this as the last route in the file
get '*url_pair', to: 'examples#show'

# examples_controller.rb
def show
  # get both values into an array, and sort into alphabetical order
  # (so pages URL pairings are always consistent)
  names = params[:url_pair].split('-').sort

  # show 404 not found if the names are the same
  raise ActiveRecord::RecordNotFound if names.uniq.count == 1

  # see if they are valid on the database. Note the use of find_by!,
  # so if either one or both don't exist, a RecordNotFound error will be raised,
  # resulting in a 404 not found page
  @activities = names.each { |n| ActivitiesModel.find_by!(name: n) }

  # if you've reached here, then we get to view rendering.
  # @activities is available to map up the view
end
</code>```

If you need to create a sitemap, or have a list of the valid pages - this will get you an array with all the valid pairings:

```<code># you could also load these from the DB
# e.g. Model.pluck(:name)
values = ["basketball", "soccer", "baseball", "swimming"]

values.combination(2).to_a.map(&:sort)
# => [["basketball", "soccer"], ["baseball", "basketball"], ["basketball", "swimming"], ["baseball", "soccer"], ["soccer", "swimming"], ["baseball", "swimming"]]
</code>```

Body:
I have a rails app and I need to loop through records in a database and match them with records in the same database then render a page with content that is based on the words present in the URL.

So imagine we have this database:

1 Basketball
2 Soccer
3 Baseball
4 Swimming

I need to build a function that generates a page for each:

domain.com/basketball-soccer
domain.com/basketball-baseball
domain.com/basketball-swimming
domain.com/soccer-baseball
domain.com/soccer-swimming
domain.com/baseball-swimming

This shouldn't generate pages for basketball-basketball, etc. and if it generates a page for basketball-soccer, page for soccer-basketball

also a page like domain.com/basketball-cricket because cricket isn't listed in the database

Example of how the content should display on each page:
This page is for a Basketball / Soccer match.

Looking for suggestions or resources on getting started with this. I'm not sure if it's possible to generate pages on the fly like this. I don't want to build each of these pages individually.

Body:
You can do this with a wildcard (catch all) route, and then handle all the logic inside the controller. For example:

# routes.rb
# put this as the last route in the file
get '*url_pair', to: 'examples#show'

# examples_controller.rb
def show
  # get both values into an array, and sort into alphabetical order
  # (so pages URL pairings are always consistent)
  names = params[:url_pair].split('-').sort

  # show 404 not found if the names are the same
  raise ActiveRecord::RecordNotFound if names.uniq.count == 1

  # see if they are valid on the database. Note the use of find_by!,
  # so if either one or both don't exist, a RecordNotFound error will be raised,
  # resulting in a 404 not found page
  @activities = names.each { |n| ActivitiesModel.find_by!(name: n) }

  # if you've reached here, then we get to view rendering.
  # @activities is available to map up the view
end

If you need to create a sitemap, or have a list of the valid pages - this will get you an array with all the valid pairings:

# you could also load these from the DB
# e.g. Model.pluck(:name)
values = ["basketball", "soccer", "baseball", "swimming"]

values.combination(2).to_a.map(&:sort)
# => [["basketball", "soccer"], ["baseball", "basketball"], ["basketball", "swimming"], ["baseball", "soccer"], ["soccer", "swimming"], ["baseball", "swimming"]]


问:
Why is this RMagick call generating a segmentation fault?
I've been banging my head against the wall for the better part of an hour trying to figure out what's going wrong here, and I'm sure (or rather hoping) it's something fairly obvious that I'm overlooking. I'm using Ruby 1.9.1, Sinatra 1.0, and RMagick 2.13.1. ImageMagick and RMagick are correctly installed and functional—I've successfully manipulated and saved images from irb.

The relevant part of the params array (formatting changes for the sake of readability):

```<code>{"admin_user_new_image_file"=>
    {
        :filename=>"freddie-on-shetland-pony.png",
        :type=>"image/png",
        :name=>"admin_user_new_image_file",
        :tempfile=>#<File:/var/folders/a7/a7pO5jMcGLCww9XBGRvWfE+++TI/-Tmp-/RackMultipart20100514-20700-o2tkqu-0>,
        :head=>"Content-Disposition: form-data; name=\"admin_user_new_image_file\"; filename=\"freddie-on-shetland-pony.png\"\r\nContent-Type: image/png\r\n"
    }
}
</code>```

The relevant code:

```<code>post "/admin/user/:account_name/image/new/" do
  if params[:admin_user_new_image_file][:tempfile]
    thumbnail = Magick::Image.read("png:"+params[:admin_user_new_image_file][:tempfile].path).first
  end
end
</code>```

The error (line 229 is the line starting with "thumbnail = ":

```<code>config.ru:229: [BUG] Segmentation fault
ruby 1.9.1p376 (2009-12-07 revision 26041) [i386-darwin10.3.0]

-- control frame ----------
c:0042 p:---- s:0196 b:0196 l:000195 d:000195 CFUNC  :read
c:0041 p:0121 s:0192 b:0192 l:001ab8 d:000191 LAMBDA config.ru:229
c:0040 p:---- s:0189 b:0189 l:000188 d:000188 FINISH
c:0039 p:---- s:0187 b:0187 l:000186 d:000186 CFUNC  :call
c:0038 p:0018 s:0184 b:0184 l:001d78 d:000183 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:865
c:0037 p:---- s:0182 b:0182 l:000181 d:000181 FINISH
c:0036 p:---- s:0180 b:0180 l:000179 d:000179 CFUNC  :instance_eval
c:0035 p:0016 s:0177 b:0175 l:000174 d:000174 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:521
c:0034 p:0024 s:0171 b:0171 l:000148 d:000170 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:500
c:0033 p:---- s:0169 b:0169 l:000168 d:000168 FINISH
c:0032 p:---- s:0167 b:0167 l:000166 d:000166 CFUNC  :catch
c:0031 p:0140 s:0163 b:0163 l:000148 d:000162 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:497
c:0030 p:---- s:0154 b:0154 l:000153 d:000153 FINISH
c:0029 p:---- s:0152 b:0152 l:000151 d:000151 CFUNC  :each
c:0028 p:0073 s:0149 b:0149 l:000148 d:000148 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:476
c:0027 p:0076 s:0141 b:0141 l:000140 d:000140 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:601
c:0026 p:0009 s:0137 b:0137 l:000138 d:000136 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411
c:0025 p:---- s:0135 b:0135 l:000134 d:000134 FINISH
c:0024 p:---- s:0133 b:0133 l:000132 d:000132 CFUNC  :instance_eval
c:0023 p:0012 s:0130 b:0130 l:000121 d:000129 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566
c:0022 p:---- s:0128 b:0128 l:000127 d:000127 FINISH
c:0021 p:---- s:0126 b:0126 l:000125 d:000125 CFUNC  :catch
c:0020 p:0013 s:0122 b:0122 l:000121 d:000121 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566
c:0019 p:0098 s:0115 b:0115 l:000138 d:000138 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411
c:0018 p:0019 s:0108 b:0108 l:000107 d:000107 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:399
c:0017 p:0014 s:0104 b:0104 l:000103 d:000103 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24
c:0016 p:0150 s:0098 b:0098 l:000097 d:000097 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/methodoverride.rb:24
c:0015 p:0031 s:0092 b:0092 l:000091 d:000091 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18
c:0014 p:0018 s:0084 b:0084 l:002080 d:000083 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979
c:0013 p:0032 s:0082 b:0082 l:000081 d:000081 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:1005
c:0012 p:0011 s:0078 b:0078 l:002080 d:002080 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979
c:0011 p:0100 s:0074 b:0074 l:000ff0 d:000ff0 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:47
c:0010 p:0022 s:0068 b:0068 l:000067 d:000067 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:35
c:0009 p:0014 s:0064 b:0064 l:000063 d:000063 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24
c:0008 p:0031 s:0058 b:0058 l:000057 d:000057 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18
c:0007 p:0014 s:0050 b:0050 l:000049 d:000049 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/content_length.rb:13
c:0006 p:0320 s:0042 b:0042 l:000041 d:000041 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/handler/webrick.rb:48
c:0005 p:0256 s:0030 b:0030 l:000029 d:000029 METHOD /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:111
c:0004 p:0382 s:0020 b:0020 l:000019 d:000019 METHOD /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:70
c:0003 p:0123 s:0009 b:0009 l:000bc8 d:000008 BLOCK  /usr/local/lib/ruby/1.9.1/webrick/server.rb:183
c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH
c:0001 p:---- s:0002 b:0002 l:000001 d:000001 TOP
---------------------------
-- Ruby level backtrace information-----------------------------------------
config.ru:229:in `read'
config.ru:229:in `block (2 levels) in <main>'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:865:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:865:in `block in route'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:521:in `instance_eval'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:521:in `route_eval'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:500:in `block (2 levels) in route!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:497:in `catch'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:497:in `block in route!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:476:in `each'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:476:in `route!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:601:in `dispatch!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411:in `block in call!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `instance_eval'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `block in invoke'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `catch'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `invoke'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411:in `call!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:399:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/methodoverride.rb:24:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979:in `block in call'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:1005:in `synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:47:in `_call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:35:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/content_length.rb:13:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/handler/webrick.rb:48:in `service'
/usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service'
/usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run'
/usr/local/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'

-- C level backtrace information -------------------------------------------
0x10010cd8d 0   libruby.dylib                       0x000000010010cd8d rb_vm_bugreport + 77
0x10002b184 1   libruby.dylib                       0x000000010002b184 report_bug + 260
0x10002b318 2   libruby.dylib                       0x000000010002b318 rb_bug + 200
0x1000b7124 3   libruby.dylib                       0x00000001000b7124 sigsegv + 132
0x7fff8301c80a 4   libSystem.B.dylib                   0x00007fff8301c80a _sigtramp + 26
0x1032313ac 5   libMagickCore.3.dylib               0x00000001032313ac Splay + 300
0x103119245 6   libMagickCore.3.dylib               0x0000000103119245 AcquirePixelCache + 325
0x1031cb317 7   libMagickCore.3.dylib               0x00000001031cb317 AcquireImage + 375
0x10333035b 8   libMagickCore.3.dylib               0x000000010333035b ReadPNGImage + 155
0x1031418fd 9   libMagickCore.3.dylib               0x00000001031418fd ReadImage + 2221
0x101f1b72b 10  RMagick2.bundle                     0x0000000101f1b72b rd_image + 339
0x101f1b59b 11  RMagick2.bundle                     0x0000000101f1b59b Image_read + 36
0x1000fd0e4 12  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 13  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 14  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 15  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x100106643 16  libruby.dylib                       0x0000000100106643 rb_vm_invoke_proc + 691
0x100106ccd 17  libruby.dylib                       0x0000000100106ccd vm_call0 + 1085
0x1000317c6 18  libruby.dylib                       0x00000001000317c6 rb_method_call + 406
0x1000fd0e4 19  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 20  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 21  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 22  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x100105ce6 23  libruby.dylib                       0x0000000100105ce6 yield_under + 710
0x100106188 24  libruby.dylib                       0x0000000100106188 specific_eval + 72
0x1000fd0e4 25  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 26  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 27  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 28  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x10010b6bf 29  libruby.dylib                       0x000000010010b6bf rb_f_catch + 639
0x1000fd0e4 30  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 31  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 32  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 33  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x10010aac9 34  libruby.dylib                       0x000000010010aac9 rb_yield + 505
0x100007902 35  libruby.dylib                       0x0000000100007902 rb_ary_each + 82
0x1000fd0e4 36  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 37  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 38  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 39  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x100105ce6 40  libruby.dylib                       0x0000000100105ce6 yield_under + 710
0x100106188 41  libruby.dylib                       0x0000000100106188 specific_eval + 72
0x1000fd0e4 42  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 43  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 44  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 45  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x10010b6bf 46  libruby.dylib                       0x000000010010b6bf rb_f_catch + 639
0x1000fd0e4 47  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 48  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 49  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 50  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x100106643 51  libruby.dylib                       0x0000000100106643 rb_vm_invoke_proc + 691
0x100111803 52  libruby.dylib                       0x0000000100111803 thread_start_func_2 + 835
0x100111921 53  libruby.dylib                       0x0000000100111921 thread_start_func_1 + 17
0x7fff82ff58b6 54  libSystem.B.dylib                   0x00007fff82ff58b6 _pthread_start + 331
0x7fff82ff5769 55  libSystem.B.dylib                   0x00007fff82ff5769 thread_start + 13

[NOTE]
You may encounter a bug of Ruby interpreter. Bug reports are welcome.
For details: http://www.ruby-lang.org/bugreport.html

Abort trap
</code>```

Anyone have any idea what's going on? Thanks!

答: I tried CaptainPete's MacPorts solution. It built 6.6.6-0 and still had the same problem. Switching to brew to do the build did the trick. Note that brew built 6.6.4-5. It's possible there are multiple bugs or a new bug in 6.6.6 that causes similar problems to occur.</p>

Body:
I've been banging my head against the wall for the better part of an hour trying to figure out what's going wrong here, and I'm sure (or rather hoping) it's something fairly obvious that I'm overlooking. I'm using Ruby 1.9.1, Sinatra 1.0, and RMagick 2.13.1. ImageMagick and RMagick are correctly installed and functional—I've successfully manipulated and saved images from irb.

The relevant part of the params array (formatting changes for the sake of readability):

{"admin_user_new_image_file"=>
    {
        :filename=>"freddie-on-shetland-pony.png",
        :type=>"image/png",
        :name=>"admin_user_new_image_file",
        :tempfile=>#<File:/var/folders/a7/a7pO5jMcGLCww9XBGRvWfE+++TI/-Tmp-/RackMultipart20100514-20700-o2tkqu-0>,
        :head=>"Content-Disposition: form-data; name=\"admin_user_new_image_file\"; filename=\"freddie-on-shetland-pony.png\"\r\nContent-Type: image/png\r\n"
    }
}

The relevant code:

post "/admin/user/:account_name/image/new/" do
  if params[:admin_user_new_image_file][:tempfile]
    thumbnail = Magick::Image.read("png:"+params[:admin_user_new_image_file][:tempfile].path).first
  end
end

The error (line 229 is the line starting with "thumbnail = ":

config.ru:229: [BUG] Segmentation fault
ruby 1.9.1p376 (2009-12-07 revision 26041) [i386-darwin10.3.0]

-- control frame ----------
c:0042 p:---- s:0196 b:0196 l:000195 d:000195 CFUNC  :read
c:0041 p:0121 s:0192 b:0192 l:001ab8 d:000191 LAMBDA config.ru:229
c:0040 p:---- s:0189 b:0189 l:000188 d:000188 FINISH
c:0039 p:---- s:0187 b:0187 l:000186 d:000186 CFUNC  :call
c:0038 p:0018 s:0184 b:0184 l:001d78 d:000183 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:865
c:0037 p:---- s:0182 b:0182 l:000181 d:000181 FINISH
c:0036 p:---- s:0180 b:0180 l:000179 d:000179 CFUNC  :instance_eval
c:0035 p:0016 s:0177 b:0175 l:000174 d:000174 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:521
c:0034 p:0024 s:0171 b:0171 l:000148 d:000170 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:500
c:0033 p:---- s:0169 b:0169 l:000168 d:000168 FINISH
c:0032 p:---- s:0167 b:0167 l:000166 d:000166 CFUNC  :catch
c:0031 p:0140 s:0163 b:0163 l:000148 d:000162 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:497
c:0030 p:---- s:0154 b:0154 l:000153 d:000153 FINISH
c:0029 p:---- s:0152 b:0152 l:000151 d:000151 CFUNC  :each
c:0028 p:0073 s:0149 b:0149 l:000148 d:000148 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:476
c:0027 p:0076 s:0141 b:0141 l:000140 d:000140 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:601
c:0026 p:0009 s:0137 b:0137 l:000138 d:000136 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411
c:0025 p:---- s:0135 b:0135 l:000134 d:000134 FINISH
c:0024 p:---- s:0133 b:0133 l:000132 d:000132 CFUNC  :instance_eval
c:0023 p:0012 s:0130 b:0130 l:000121 d:000129 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566
c:0022 p:---- s:0128 b:0128 l:000127 d:000127 FINISH
c:0021 p:---- s:0126 b:0126 l:000125 d:000125 CFUNC  :catch
c:0020 p:0013 s:0122 b:0122 l:000121 d:000121 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566
c:0019 p:0098 s:0115 b:0115 l:000138 d:000138 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411
c:0018 p:0019 s:0108 b:0108 l:000107 d:000107 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:399
c:0017 p:0014 s:0104 b:0104 l:000103 d:000103 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24
c:0016 p:0150 s:0098 b:0098 l:000097 d:000097 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/methodoverride.rb:24
c:0015 p:0031 s:0092 b:0092 l:000091 d:000091 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18
c:0014 p:0018 s:0084 b:0084 l:002080 d:000083 BLOCK  /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979
c:0013 p:0032 s:0082 b:0082 l:000081 d:000081 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:1005
c:0012 p:0011 s:0078 b:0078 l:002080 d:002080 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979
c:0011 p:0100 s:0074 b:0074 l:000ff0 d:000ff0 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:47
c:0010 p:0022 s:0068 b:0068 l:000067 d:000067 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:35
c:0009 p:0014 s:0064 b:0064 l:000063 d:000063 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24
c:0008 p:0031 s:0058 b:0058 l:000057 d:000057 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18
c:0007 p:0014 s:0050 b:0050 l:000049 d:000049 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/content_length.rb:13
c:0006 p:0320 s:0042 b:0042 l:000041 d:000041 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/handler/webrick.rb:48
c:0005 p:0256 s:0030 b:0030 l:000029 d:000029 METHOD /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:111
c:0004 p:0382 s:0020 b:0020 l:000019 d:000019 METHOD /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:70
c:0003 p:0123 s:0009 b:0009 l:000bc8 d:000008 BLOCK  /usr/local/lib/ruby/1.9.1/webrick/server.rb:183
c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH
c:0001 p:---- s:0002 b:0002 l:000001 d:000001 TOP
---------------------------
-- Ruby level backtrace information-----------------------------------------
config.ru:229:in `read'
config.ru:229:in `block (2 levels) in '
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:865:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:865:in `block in route'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:521:in `instance_eval'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:521:in `route_eval'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:500:in `block (2 levels) in route!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:497:in `catch'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:497:in `block in route!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:476:in `each'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:476:in `route!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:601:in `dispatch!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411:in `block in call!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `instance_eval'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `block in invoke'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `catch'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `invoke'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411:in `call!'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:399:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/methodoverride.rb:24:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979:in `block in call'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:1005:in `synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:47:in `_call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:35:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/content_length.rb:13:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/handler/webrick.rb:48:in `service'
/usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service'
/usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run'
/usr/local/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'

-- C level backtrace information -------------------------------------------
0x10010cd8d 0   libruby.dylib                       0x000000010010cd8d rb_vm_bugreport + 77
0x10002b184 1   libruby.dylib                       0x000000010002b184 report_bug + 260
0x10002b318 2   libruby.dylib                       0x000000010002b318 rb_bug + 200
0x1000b7124 3   libruby.dylib                       0x00000001000b7124 sigsegv + 132
0x7fff8301c80a 4   libSystem.B.dylib                   0x00007fff8301c80a _sigtramp + 26
0x1032313ac 5   libMagickCore.3.dylib               0x00000001032313ac Splay + 300
0x103119245 6   libMagickCore.3.dylib               0x0000000103119245 AcquirePixelCache + 325
0x1031cb317 7   libMagickCore.3.dylib               0x00000001031cb317 AcquireImage + 375
0x10333035b 8   libMagickCore.3.dylib               0x000000010333035b ReadPNGImage + 155
0x1031418fd 9   libMagickCore.3.dylib               0x00000001031418fd ReadImage + 2221
0x101f1b72b 10  RMagick2.bundle                     0x0000000101f1b72b rd_image + 339
0x101f1b59b 11  RMagick2.bundle                     0x0000000101f1b59b Image_read + 36
0x1000fd0e4 12  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 13  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 14  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 15  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x100106643 16  libruby.dylib                       0x0000000100106643 rb_vm_invoke_proc + 691
0x100106ccd 17  libruby.dylib                       0x0000000100106ccd vm_call0 + 1085
0x1000317c6 18  libruby.dylib                       0x00000001000317c6 rb_method_call + 406
0x1000fd0e4 19  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 20  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 21  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 22  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x100105ce6 23  libruby.dylib                       0x0000000100105ce6 yield_under + 710
0x100106188 24  libruby.dylib                       0x0000000100106188 specific_eval + 72
0x1000fd0e4 25  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 26  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 27  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 28  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x10010b6bf 29  libruby.dylib                       0x000000010010b6bf rb_f_catch + 639
0x1000fd0e4 30  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 31  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 32  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 33  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x10010aac9 34  libruby.dylib                       0x000000010010aac9 rb_yield + 505
0x100007902 35  libruby.dylib                       0x0000000100007902 rb_ary_each + 82
0x1000fd0e4 36  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 37  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 38  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 39  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x100105ce6 40  libruby.dylib                       0x0000000100105ce6 yield_under + 710
0x100106188 41  libruby.dylib                       0x0000000100106188 specific_eval + 72
0x1000fd0e4 42  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 43  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 44  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 45  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x10010b6bf 46  libruby.dylib                       0x000000010010b6bf rb_f_catch + 639
0x1000fd0e4 47  libruby.dylib                       0x00000001000fd0e4 vm_call_cfunc + 340
0x1000fe9b0 48  libruby.dylib                       0x00000001000fe9b0 vm_call_method + 896
0x1000ff8fc 49  libruby.dylib                       0x00000001000ff8fc vm_exec_core + 3180
0x100104b93 50  libruby.dylib                       0x0000000100104b93 vm_exec + 1203
0x100106643 51  libruby.dylib                       0x0000000100106643 rb_vm_invoke_proc + 691
0x100111803 52  libruby.dylib                       0x0000000100111803 thread_start_func_2 + 835
0x100111921 53  libruby.dylib                       0x0000000100111921 thread_start_func_1 + 17
0x7fff82ff58b6 54  libSystem.B.dylib                   0x00007fff82ff58b6 _pthread_start + 331
0x7fff82ff5769 55  libSystem.B.dylib                   0x00007fff82ff5769 thread_start + 13

[NOTE]
You may encounter a bug of Ruby interpreter. Bug reports are welcome.
For details: http://www.ruby-lang.org/bugreport.html

Abort trap

Anyone have any idea what's going on? Thanks!


问:
Is ChefSpec in chef really usable compared to testing with Kitchen
I had covered recipe code with ChefSpec and after that I have integration testing with Kitchen. To me at the end ChefSpec is not really usable just one extra think to maintain because:

When I'm writing Java with TDD/BDD I see real benefits from using this approach- lots of smaller classes, DI integration, modularity, less bugs.

However with Chef and ChefSpec to me is only usable default generated spec the helps me with some compile and syntax errors.

How to use ChefSpec with Chef to see the same benefits like TDD/BDD in Java for example.

答:
ChefSpec is an RSpec library, which I think is what you're referring to. It is built for unit testing, which it accomplishes by having all providers default to not actually running. So it does a "converge" but without any actual implementation of anything so it goes very quickly. The downside being that you can't actually check if the side effects were what you thought they should be. For that you need to actually run Chef for real, and that is what Test Kitchen is for. It is a framework for creating a VM, running Chef on it, and then running some kind of correctness tests on the VM. For the correctness tests you can use many tools, but the most common are Serverspec (which is an RSpec library) and InSpec (which isn't an RSpec library but kind of looks like one for the most part).

So RSpec is involved with both unit and integration testing, but for different tasks.


问:
Locale not working properly
I have a different string for English, French and spanish. Even after setting the Locale to French, the string being displayed is still in English.
I create a string resource file under values directory named values-fr-rFR.
My code is the following:

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Configuration c = getResources().getConfiguration();
        c.setLocale(new Locale("fr", "FR"));
        getApplicationContext().createConfigurationContext(c);
        TextView textId = (TextView)findViewById(R.id.helloId);
        textId.setText(R.string.hello);
    }
</code>```

Can someone say what is wrong in my code? Here you can that I have changed the Locale to "fr". But the string being displayed in textView textId is still in English.

答:
You need to make sure that you have a xml file with the localized version of the text you want to use. For instance, if you reference the Android docs:

English strings (default locale), /values/strings.xml:

```<code><resources>
    <string name="hello_world">Hello World!</string>
</resources>
</code>```

Spanish strings (es locale), /values-es/strings.xml:

```<code><resources>
    <string name="hello_world">¡Hola Mundo!</string>
</resources>
</code>```

Then you can do:

```<code>// Get a string resource from your app's Resources
String hello = getResources().getString(R.string.hello_world);

// Or supply a string resource to a method that requires a string
TextView textView = new TextView(this);
textView.setText(R.string.hello_world);
</code>```

All examples and further reading can be found at the Android developer site: https://developer.android.com/training/basics/supporting-devices/languages.html

Title: Locale not working properly

Body:
I have a different string for English, French and spanish. Even after setting the Locale to French, the string being displayed is still in English.
I create a string resource file under values directory named values-fr-rFR.
My code is the following:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Configuration c = getResources().getConfiguration();
        c.setLocale(new Locale("fr", "FR"));
        getApplicationContext().createConfigurationContext(c);
        TextView textId = (TextView)findViewById(R.id.helloId);
        textId.setText(R.string.hello);
    }

Can someone say what is wrong in my code? Here you can that I have changed the Locale to "fr". But the string being displayed in textView textId is still in English.

Body:
You need to make sure that you have a xml file with the localized version of the text you want to use. For instance, if you reference the Android docs:

English strings (default locale), /values/strings.xml:

<resources>
    <string name="hello_world">Hello World!</string>
</resources>

Spanish strings (es locale), /values-es/strings.xml:

<resources>
    <string name="hello_world">¡Hola Mundo!</string>
</resources>

Then you can do:

// Get a string resource from your app's Resources
String hello = getResources().getString(R.string.hello_world);

// Or supply a string resource to a method that requires a string
TextView textView = new TextView(this);
textView.setText(R.string.hello_world);

All examples and further reading can be found at the Android developer site: https://developer.android.com/training/basics/supporting-devices/languages.html


问:
Accessing array elements using the associative index and numbered index
Is it possible to define an array where I can access the elements via their string and numeric index?</p>

答:
You can do this. </p>

```<code>$arr = array(1 => 'Numerical', 'two' => 'string');
echo $arr[1]; //Numerical
echo $arr['two']; //String
</code>```

Body:
You can do this.

$arr = array(1 => 'Numerical', 'two' => 'string');
echo $arr[1]; //Numerical
echo $arr['two']; //String


问:
How to push nested Objects into individual elements in an array?
The following API returns some JSON data:

https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=bananas

I am trying to push the properties (also objects) of the Pages object into a single array. Each object should be its own element in the array.

For example query.pages should be pushed into an array like [38940{}, 284306{}, ...]

Im doing this so that I can run through the array using ForEach and populate the DOM with the required data.

Thanks in advance!

答:
```<code>// result is the json from https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=bananas

const singleArray = Object.keys(result.query.pages).reduce((acc, id) => {
  acc.push(result.query.pages[id]);
  return acc;
}, []);
</code>```


问:
Need help from an experienced with preg_replace () function
As you know ereg_replace is deprecated now.
I tried to pass to preg_replace but nothing works as before with ereg_replace.

I want to change the ereg_replace here:

```<code>$test = ereg_replace("%5C%22", "%22", $test);

$tar = ereg_replace(" ", "", $tar);

$test2 = ereg_replace("#EM#", $tar, $test2);

$su = ereg_replace("&emar&", $tar, $su);
</code>```

I've edited with preg_replace like this but I don't know if it's correct

```<code>$test = preg_replace('/%5C%22/', '%22', $test, -1);

$tar = preg_replace(/ /, '', $tar, -1);

$test2 = preg_replace('/#EM#/', $tar, $test2, -1);

$su = preg_replace('/&emar&/', $tar, $su, -1);
</code>```

this one :

```<code>$test2 = preg_replace('/#EM#/', $tar, $test2, -1);
</code>```

is correct or I change to:

```<code>$test2 = preg_replace('/\#EM\#/', $tar, $test2, -1);
</code>```

Thank you.

答:
The only difference in your examples would be that you need to add Delimiters.

http://php.net/manual/en/regexp.reference.delimiters.php

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~).

But, that being said, in your case it will be more performant and simpler to use str_replace as you are not really using any regular expression pattern.

Body:
As you know ereg_replace is deprecated now.
I tried to pass to preg_replace but nothing works as before with ereg_replace.

I want to change the ereg_replace here:

$test = ereg_replace("%5C%22", "%22", $test);

$tar = ereg_replace(" ", "", $tar);

$test2 = ereg_replace("#EM#", $tar, $test2);

$su = ereg_replace("&emar&", $tar, $su);

I've edited with preg_replace like this but I don't know if it's correct

$test = preg_replace('/%5C%22/', '%22', $test, -1);

$tar = preg_replace(/ /, '', $tar, -1);

$test2 = preg_replace('/#EM#/', $tar, $test2, -1);

$su = preg_replace('/&emar&/', $tar, $su, -1);

this one :

$test2 = preg_replace('/#EM#/', $tar, $test2, -1);

is correct or I change to:

$test2 = preg_replace('/\#EM\#/', $tar, $test2, -1);

Thank you.


问:
Easy way to write contents of a Java InputStream to an OutputStream
I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).

So, given an InputStream in and an OutputStream out, is there a simpler way to write the following?

```<code>byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
}
</code>```

答:
I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.</p>

```<code>byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}
</code>```

OwnerDisplayName: Matt Sheppard

Body:
I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).

So, given an InputStream in and an OutputStream out, is there a simpler way to write the following?

byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
}

Body:
I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.

byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}

OwnerDisplayName: Mike Stone


问:
buildroot error when compiling wpa_supplicant
I've got an error while building wpa_supplicant with buildroot

```<code>home@debian-host:/build/buildroot# make
>>> wpa_supplicant 2.6 Building
PATH="/build/buildroot/output/host/bin:/build/buildroot/output/host/sbin:/build/buildroot/output/host/usr/bin:/build/buildroot/output/host/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" CFLAGS="-D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64  -Os  -I/build/buildroot/output/host/usr/arm-astrokitpi3-linux-gnueabihf/sysroot/usr/include/libnl3/" LDFLAGS="" BINDIR=/usr/sbin LIBS="" LIBS_c="" LIBS_p="" /usr/bin/make -j5 CC="/build/buildroot/output/host/usr/bin/arm-astrokitpi3-linux-gnueabihf-gcc" -C /build/buildroot/output/build/wpa_supplicant-2.6/wpa_supplicant
make[1]: Entering directory '/build/buildroot/output/build/wpa_supplicant-2.6/wpa_supplicant'
../src/common/sae.o : Dans la fonction « sae_cn_confirm.isra.2 » :
sae.c:(.text+0x15c) : référence indéfinie vers « crypto_bignum_to_bin »
sae.c:(.text+0x18c) : référence indéfinie vers « crypto_bignum_to_bin »
../src/common/sae.o : Dans la fonction « sae_cn_confirm_ffc » :
...
...
sae.c:(.text+0x1c44) : référence indéfinie vers « crypto_bignum_cmp »
sae.c:(.text+0x1c64) : référence indéfinie vers « crypto_ec_point_cmp »
collect2: erreur : ld a retourné 1 code d'état d'exécution
Makefile:1689: recipe for target 'wpa_supplicant' failed
make[1]: *** [wpa_supplicant] Error 1
make[1]: Leaving directory '/build/buildroot/output/build/wpa_supplicant-2.6/wpa_supplicant'
package/pkg-generic.mk:216: recipe for target '/build/buildroot/output/build/wpa_supplicant-2.6/.stamp_built' failed
make: *** [/build/buildroot/output/build/wpa_supplicant-2.6/.stamp_built] Error 2
</code>```

any idea ?
thanks

答: Please select the OpenSSL package in "Target packages > Libraries > Crypto".</p>

Body:
I've got an error while building wpa_supplicant with buildroot

home@debian-host:/build/buildroot# make
>>> wpa_supplicant 2.6 Building
PATH="/build/buildroot/output/host/bin:/build/buildroot/output/host/sbin:/build/buildroot/output/host/usr/bin:/build/buildroot/output/host/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" CFLAGS="-D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64  -Os  -I/build/buildroot/output/host/usr/arm-astrokitpi3-linux-gnueabihf/sysroot/usr/include/libnl3/" LDFLAGS="" BINDIR=/usr/sbin LIBS="" LIBS_c="" LIBS_p="" /usr/bin/make -j5 CC="/build/buildroot/output/host/usr/bin/arm-astrokitpi3-linux-gnueabihf-gcc" -C /build/buildroot/output/build/wpa_supplicant-2.6/wpa_supplicant
make[1]: Entering directory '/build/buildroot/output/build/wpa_supplicant-2.6/wpa_supplicant'
../src/common/sae.o : Dans la fonction « sae_cn_confirm.isra.2 » :
sae.c:(.text+0x15c) : référence indéfinie vers « crypto_bignum_to_bin »
sae.c:(.text+0x18c) : référence indéfinie vers « crypto_bignum_to_bin »
../src/common/sae.o : Dans la fonction « sae_cn_confirm_ffc » :
...
...
sae.c:(.text+0x1c44) : référence indéfinie vers « crypto_bignum_cmp »
sae.c:(.text+0x1c64) : référence indéfinie vers « crypto_ec_point_cmp »
collect2: erreur : ld a retourné 1 code d'état d'exécution
Makefile:1689: recipe for target 'wpa_supplicant' failed
make[1]: *** [wpa_supplicant] Error 1
make[1]: Leaving directory '/build/buildroot/output/build/wpa_supplicant-2.6/wpa_supplicant'
package/pkg-generic.mk:216: recipe for target '/build/buildroot/output/build/wpa_supplicant-2.6/.stamp_built' failed
make: *** [/build/buildroot/output/build/wpa_supplicant-2.6/.stamp_built] Error 2

any idea ?
thanks