问:
Validating password using regex c#
This must be simple and I expect it working in the same way but it's not helping me out.

```<code>using System;
using System.Text.RegularExpressions;
</code>```

I am in a need of password validation regular expression with certain conditions where -

1) It must contain at least a number

2) one upper case letter

3) 8 characters long.

```<code>public class Program
{
     public static bool IsValidPassword(string plainText) {
            Regex regex = new Regex(@"^(.{0,7}|[^0-9]*|[^A-Z])$");
            Match match = regex.Match(plainText);
            return match.Success;
}
    public static void Main()
    {
        Console.WriteLine(IsValidPassword("shing"));    //logs 'True' always
    }
}
</code>```

I've taken regex from this source- Password must be 8 characters including 1 uppercase letter, 1 special character, alphanumeric characters

Issue is that it returns 'True' always and the string that I am sending to method is not valid.

Help me if I am doing something wrong with the regex.

Please play with it here- https://dotnetfiddle.net/lEFYGJ

答:
I have created a simple method to validate all kind of password. You can edit your limit on that. Kindly find the code given below.</p>

```<code>private bool ValidatePassword(string password, out string ErrorMessage)
{
    var input = password;
    ErrorMessage = string.Empty;

    if (string.IsNullOrWhiteSpace(input))
    {
        throw new Exception("Password should not be empty");
    }

    var hasNumber = new Regex(@"[0-9]+");
    var hasUpperChar = new Regex(@"[A-Z]+");
    var hasMiniMaxChars = new Regex(@".{8,15}");
    var hasLowerChar = new Regex(@"[a-z]+");
    var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

    if (!hasLowerChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one lower case letter";
        return false;
    }
    else if (!hasUpperChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one upper case letter";
        return false;
    }
    else if (!hasMiniMaxChars.IsMatch(input))
    {
        ErrorMessage = "Password should not be less than or greater than 12 characters";
        return false;
    }
    else if (!hasNumber.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one numeric value";
        return false;
    }

    else if (!hasSymbols.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one special case characters";
        return false;
    }
    else
    {
        return true;
    }
}
</code>```

Title: Validating password using regex c#

Body:
This must be simple and I expect it working in the same way but it's not helping me out.

using System;
using System.Text.RegularExpressions;

I am in a need of password validation regular expression with certain conditions where -

1) It must contain at least a number

2) one upper case letter

3) 8 characters long.

public class Program
{
     public static bool IsValidPassword(string plainText) {
            Regex regex = new Regex(@"^(.{0,7}|[^0-9]*|[^A-Z])$");
            Match match = regex.Match(plainText);
            return match.Success;
}
    public static void Main()
    {
        Console.WriteLine(IsValidPassword("shing"));    //logs 'True' always
    }
}

I've taken regex from this source- Password must be 8 characters including 1 uppercase letter, 1 special character, alphanumeric characters

Issue is that it returns 'True' always and the string that I am sending to method is not valid.

Help me if I am doing something wrong with the regex.

Please play with it here- https://dotnetfiddle.net/lEFYGJ

Body:
I have created a simple method to validate all kind of password. You can edit your limit on that. Kindly find the code given below.

private bool ValidatePassword(string password, out string ErrorMessage)
{
    var input = password;
    ErrorMessage = string.Empty;

    if (string.IsNullOrWhiteSpace(input))
    {
        throw new Exception("Password should not be empty");
    }

    var hasNumber = new Regex(@"[0-9]+");
    var hasUpperChar = new Regex(@"[A-Z]+");
    var hasMiniMaxChars = new Regex(@".{8,15}");
    var hasLowerChar = new Regex(@"[a-z]+");
    var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

    if (!hasLowerChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one lower case letter";
        return false;
    }
    else if (!hasUpperChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one upper case letter";
        return false;
    }
    else if (!hasMiniMaxChars.IsMatch(input))
    {
        ErrorMessage = "Password should not be less than or greater than 12 characters";
        return false;
    }
    else if (!hasNumber.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one numeric value";
        return false;
    }

    else if (!hasSymbols.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one special case characters";
        return false;
    }
    else
    {
        return true;
    }
}


来源: stackexchange

问:
tomcat access log get my eth0 ip?
```<code><Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
       prefix="localhost_access_log" suffix=".txt"
       pattern="%t %a %A %p %r %q %s %B  %D %{User-Agent}i %{Referer}i"
       resolveHosts="false" />
</code>```

This is my server.xml ,then i found the result is like this:

[29/Mar/2017:10:36:16 +0800] 192.168.5.149 127.0.0.1 80 GET /favicon.ico HTTP/1.1  404 0  0 Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0 -

in the server.xml %A just give me the loop ip, but i want eth0 ip ..

So what should i do? Thanks a lot!

答:
Check host name:

$ hostname
yourhost
```

<ol start="2">
<li>Edit /etc/hosts and add:</li>
</ol>

<pre class="lang-none prettyprint-override"><code>192.168.5.1    yourhost
</code>```

FYI, Tomcat source code:

/**
 * write local IP address - %A
 */
protected static class LocalAddrElement implements AccessLogElement {

    private static final String LOCAL_ADDR_VALUE;

    static {
        String init;
        try {
            init = InetAddress.getLocalHost().getHostAddress();
        } catch (Throwable e) {
            ExceptionUtils.handleThrowable(e);
            init = "127.0.0.1";
        }
        LOCAL_ADDR_VALUE = init;
    }

    @Override
    public void addElement(StringBuilder buf, Date date, Request request,
            Response response, long time) {
        buf.append(LOCAL_ADDR_VALUE);
    }
}
```

ContentLicense: CC BY-SA 3.0

Title: tomcat access log get my eth0 ip?

Body:
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
       prefix="localhost_access_log" suffix=".txt"
       pattern="%t %a %A %p %r %q %s %B  %D %{User-Agent}i %{Referer}i"
       resolveHosts="false" />

This is my server.xml ,then i found the result is like this:

[29/Mar/2017:10:36:16 +0800] 192.168.5.149 127.0.0.1 80 GET /favicon.ico HTTP/1.1  404 0  0 Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0 -

in the server.xml %A just give me the loop ip, but i want eth0 ip ..

So what should i do? Thanks a lot!

Body:
Check host name:

$ hostname
yourhost

Edit /etc/hosts and add:

192.168.5.1    yourhost

FYI, Tomcat source code:

/**
 * write local IP address - %A
 */
protected static class LocalAddrElement implements AccessLogElement {

    private static final String LOCAL_ADDR_VALUE;

    static {
        String init;
        try {
            init = InetAddress.getLocalHost().getHostAddress();
        } catch (Throwable e) {
            ExceptionUtils.handleThrowable(e);
            init = "127.0.0.1";
        }
        LOCAL_ADDR_VALUE = init;
    }

    @Override
    public void addElement(StringBuilder buf, Date date, Request request,
            Response response, long time) {
        buf.append(LOCAL_ADDR_VALUE);
    }
}


问:
How to display a ForeignKey field as a selection field in django template
I need to display a foreignKey field as a selection field in Django template, which will show all the available records as a dropdown. On considering the case of querying to database every time on selecting the field, which is the best method to achieve above goal to make a selection field from ForeignKey field.</p>

答:
Use ModelChoiceField https://docs.djangoproject.com/en/1.10/ref/forms/fields/#django.forms.ModelChoiceField

```<code>class MyForm(forms.ModelForm):
    myfield = forms.ModelChoiceField(queryset=...)
</code>```

Body:
Use ModelChoiceField https://docs.djangoproject.com/en/1.10/ref/forms/fields/#django.forms.ModelChoiceField

class MyForm(forms.ModelForm):
    myfield = forms.ModelChoiceField(queryset=...)


问:
Julia parallel computing over multiple nodes in cluster
I am running some jobs on a shared cluster and I've been trying to use more than 1 node at a time. While using julia -p #processors works for the cores on one node, it doesn't find the other nodes.
The cluster is using SGE and I tried a lot of different ways to make the nodes work, but only one was working. Is there an easy way built in Julia to launch Julia with julia -mpi 32 or something similar?

Using

```<code>using ClusterManagers
println(nworkers(),nprocs(),Sys.CPU_CORES)
ClusterManagers.addprocs_sge(16)
ClusterManagers.addprocs_sge(15)
println(nworkers(),nprocs(),Sys.CPU_CORES)
</code>```

doesn't work (I have submitted a job reserving 2 nodes with 16 cores each on the SGE), the output file of the job is empty and instead I get 16  different output files julia-70755.o8252776.* (* = 1...16) with the following text:

```<code>julia_worker:9009#192.168.17.206
Master process (id 1) could not connect within 60.0 seconds.
exiting.
</code>```

Starting Julia with julia --machinefile $PE_HOSTFILE also failed with:

```<code>Warning: Permanently added the RSA host key for IP address '192.168.18.10' to th
e list of known hosts.
ERROR: connect: invalid argument (EINVAL)
 in uv_error at ./libuv.jl:68 [inlined]
 in connect!(::TCPSocket, ::IPv4, ::UInt16) at ./socket.jl:652
 in connect!(::TCPSocket, ::SubString{String}, ::UInt16) at ./socket.jl:688
 in connect at ./stream.jl:959 [inlined]
 in connect_to_worker(::SubString{String}, ::Int16) at ./managers.jl:483
 in connect(::Base.SSHManager, ::Int64, ::WorkerConfig) at ./managers.jl:425
 in create_worker(::Base.SSHManager, ::WorkerConfig) at ./multi.jl:1786
 in setup_launched_worker(::Base.SSHManager, ::WorkerConfig, ::Array{Int64,1}) a
t ./multi.jl:1733
 in (::Base.##669#673{Base.SSHManager,Array{Int64,1}})() at ./task.jl:360
 in sync_end() at ./task.jl:311
 in macro expansion at ./task.jl:327 [inlined]
 in #addprocs_locked#665(::Array{Any,1}, ::Function, ::Base.SSHManager) at ./mul
ti.jl:1688
 in (::Base.#kw##addprocs_locked)(::Array{Any,1}, ::Base.#addprocs_locked, ::Bas
e.SSHManager) at ./<missing>:0
 in #addprocs#664(::Array{Any,1}, ::Function, ::Base.SSHManager) at ./multi.jl:1
658
 in (::Base.#kw##addprocs)(::Array{Any,1}, ::Base.#addprocs, ::Base.SSHManager)
at ./<missing>:0
 in #addprocs#764(::Bool, ::Cmd, ::Int64, ::Array{Any,1}, ::Function, ::Array{An
y,1}) at ./managers.jl:112
 in process_options(::Base.JLOptions) at ./client.jl:227
 in _start() at ./client.jl:321
UndefRefError()
</code>```

I was suggested to use the MPI.jl package, but it doesn't look to me like it really supports the julia parallel syntax, at the way I'm using it by just writing @sync @parallel before a for loop that I want to run in parallel (i.e. Metropolis-Montecarlo).

答:
You might want to read the julia docs on parallel computing where there is a section on cluster managers.  Also, take a look at ClusterManagers.jl where SGE is supported:</p>

```<code>julia> using ClusterManagers
julia> ClusterMangers.addprocs_sge(5)
</code>```

Body:
I am running some jobs on a shared cluster and I've been trying to use more than 1 node at a time. While using julia -p #processors works for the cores on one node, it doesn't find the other nodes.
The cluster is using SGE and I tried a lot of different ways to make the nodes work, but only one was working. Is there an easy way built in Julia to launch Julia with julia -mpi 32 or something similar?

Using

using ClusterManagers
println(nworkers(),nprocs(),Sys.CPU_CORES)
ClusterManagers.addprocs_sge(16)
ClusterManagers.addprocs_sge(15)
println(nworkers(),nprocs(),Sys.CPU_CORES)

doesn't work (I have submitted a job reserving 2 nodes with 16 cores each on the SGE), the output file of the job is empty and instead I get 16  different output files julia-70755.o8252776.* (* = 1...16) with the following text:

julia_worker:9009#192.168.17.206
Master process (id 1) could not connect within 60.0 seconds.
exiting.

Starting Julia with julia --machinefile $PE_HOSTFILE also failed with:

Warning: Permanently added the RSA host key for IP address '192.168.18.10' to th
e list of known hosts.
ERROR: connect: invalid argument (EINVAL)
 in uv_error at ./libuv.jl:68 [inlined]
 in connect!(::TCPSocket, ::IPv4, ::UInt16) at ./socket.jl:652
 in connect!(::TCPSocket, ::SubString{String}, ::UInt16) at ./socket.jl:688
 in connect at ./stream.jl:959 [inlined]
 in connect_to_worker(::SubString{String}, ::Int16) at ./managers.jl:483
 in connect(::Base.SSHManager, ::Int64, ::WorkerConfig) at ./managers.jl:425
 in create_worker(::Base.SSHManager, ::WorkerConfig) at ./multi.jl:1786
 in setup_launched_worker(::Base.SSHManager, ::WorkerConfig, ::Array{Int64,1}) a
t ./multi.jl:1733
 in (::Base.##669#673{Base.SSHManager,Array{Int64,1}})() at ./task.jl:360
 in sync_end() at ./task.jl:311
 in macro expansion at ./task.jl:327 [inlined]
 in #addprocs_locked#665(::Array{Any,1}, ::Function, ::Base.SSHManager) at ./mul
ti.jl:1688
 in (::Base.#kw##addprocs_locked)(::Array{Any,1}, ::Base.#addprocs_locked, ::Bas
e.SSHManager) at ./<missing>:0
 in #addprocs#664(::Array{Any,1}, ::Function, ::Base.SSHManager) at ./multi.jl:1
658
 in (::Base.#kw##addprocs)(::Array{Any,1}, ::Base.#addprocs, ::Base.SSHManager)
at ./<missing>:0
 in #addprocs#764(::Bool, ::Cmd, ::Int64, ::Array{Any,1}, ::Function, ::Array{An
y,1}) at ./managers.jl:112
 in process_options(::Base.JLOptions) at ./client.jl:227
 in _start() at ./client.jl:321
UndefRefError()

I was suggested to use the MPI.jl package, but it doesn't look to me like it really supports the julia parallel syntax, at the way I'm using it by just writing @sync @parallel before a for loop that I want to run in parallel (i.e. Metropolis-Montecarlo).

Body:
You might want to read the julia docs on parallel computing where there is a section on cluster managers.  Also, take a look at ClusterManagers.jl where SGE is supported:

julia> using ClusterManagers
julia> ClusterMangers.addprocs_sge(5)


问:
Making a new object, cannot be applied to type (int)
I have a ProcessHeap class that has two fields:

Heap: an array of type Process which represents the heap

Size: the number of elements in the heap

My constructor and attributes look like this:

```<code>private Process[] heap;
private int size;
private static int counter = 0;

//Paramaterized construct
    public ProcessHeap(Process[] heap, int size) {
        this.heap = heap;
        this.size = size;
</code>```

The problem is, we were given a driver and at the start of the driver I am getting an error particularly on (HEAP_SIZE)

This is the line:

```<code>final int HEAP_SIZE = 100;
ProcessHeap heap = new ProcessHeap(HEAP_SIZE); // gives this error:
</code>```

The error upon mouse-over states:

ProcessHeap (Process[], int) in ProcessHeap cannot be applied to (int)

答:
Your constructor ProcessHeap is taking 2 parameters (an array and an integer), you are passing only one...

So you need either to change the params in the constructor:

ProcessHeap(Process[] heap, int size)  and remove the arraay, OR overload it defining a new one taking only an integer.

Body:
I have a ProcessHeap class that has two fields:

Heap: an array of type Process which represents the heap

Size: the number of elements in the heap

My constructor and attributes look like this:

private Process[] heap;
private int size;
private static int counter = 0;

//Paramaterized construct
    public ProcessHeap(Process[] heap, int size) {
        this.heap = heap;
        this.size = size;

The problem is, we were given a driver and at the start of the driver I am getting an error particularly on (HEAP_SIZE)

This is the line:

final int HEAP_SIZE = 100;
ProcessHeap heap = new ProcessHeap(HEAP_SIZE); // gives this error:

The error upon mouse-over states:

ProcessHeap (Process[], int) in ProcessHeap cannot be applied to (int)


问:
MySql database doesn't submit the values of my form
My database doesn't submit my values of my form, when I enter values into my form it shows nothing at all the varchar value columns and at the integer value columns there is a 0.   After I submit values

database

I'm using xampp.

```<code>   <?php
 error_reporting(0);

$con = mysqli_connect("localhost","root",'',"bwl_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dbhost = 'localhost';
$user = 'root';
$password = 'root123';
$database = 'bwl_db';

$Name =  $_POST['Name'];
$Surname =  $_POST['Surname'];
$Email =  $_POST['Email'];
$Telephone = $_POST['Telephone'];
$ID_Number = $_POST['ID_Number'];

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)
VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

mysqli_close($con);

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

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <title>BWL | Registration </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>
    <!-- favicon -->
    <link rel="icon" type="image/png" href="images/favicon.png">
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <!-- Fontawesome  -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- responsive css -->
    <link rel="stylesheet" type="text/css" href="css/responsive.css"> </head>

<body>

    <div class="registaration-logo">
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
        <img src="images/translogo.png" alt=" ">
            </div>
        </div>
    </div>

    <form class="form-registration" action="reg_db.php" method="post">
              <h2> Registration </h2>
        <div class="form-group-row">
            <label for="Name" class="col-2 col-form-label">Name</label>
            <div class="col-10">
                <input class="form-control" name="Name" type="text" id="Name" placeholder="Enter Name"> </div>
        </div>
        <div class="form-group-row">
            <label for="Surname" class="col-2 col-form-label">Surname</label>
            <div class="col-10">
                <input class="form-control" name="Surname"  type="text" id="Surname" placeholder="Enter Surname"> </div>
        </div>
        <div class="form-group-row">
            <label for="Email" class="col-2 col-form-label">Email</label>
            <div class="col-10">
                <input class="form-control" name="Email"  type="email" id="Email" placeholder="Enter email"> </div>
        </div>
        <div class="form-group-row">
            <label for="Confirm Email" class="col-2 col-form-label"> Confirm Email</label>
            <div class="col-10">
                <input class="form-control"  type="email" id="Confirm Email" placeholder="Confirm email"> </div>
        </div>
        <div class="form-group-row">
            <label for="Telephone" class="col-2 col-form-label">Telephone Number</label>
            <div class="col-10">
                <input class="form-control" name="Telephone"  type="tel" id="telephone" placeholder="Enter Telephone Number"> </div>
        </div>
        <div class="form-group-row">
            <label for="ID_Number" class="col-2 col-form-label">ID Number</label>
            <div class="col-10">
                <input class="form-control" name="ID_Number"  type="text" id="id-number" placeholder="Enter ID Number"> </div>
        </div>
        <div class="form-group-row">
            <div class="col-sm-10">
                    <a href="verify.html" class="btn btn-default1" role="button" type="submit">Submit</a>
            </div>
        </div>

        <div class="panel panel-default">
  <div class="panel-body">
    <h3> Disclaimer</h3>
      <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
  </div>
        </div>
 </form>

</body>

</html>

 VERIFY.HTML PAGE
    <!DOCTYPE html>
<html lang="en">

<head>
    <title>BWL | Verify </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>
    <!-- favicon -->
    <link rel="icon" type="image/png" href="images/favicon.png">
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <!-- Fontawesome  -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- responsive css -->
    <link rel="stylesheet" type="text/css" href="css/responsive.css"> </head>

<body>

   <div class="verify">
  <div class="jumbotron">
    <h2>Thank You</h2>
    <p>We will send you your login information when you are verified.</p>
  </div>
       </div>
</body>

</html>
</code>```

答:
Your not using a submit-button you are just using a href so your data isn't submitted. Change your last line of the form to this:

```<code><div class="form-group-row">
    <div class="col-sm-10">
         <input class="btn btn-default1" type="submit" value="Submit" />
    </div>
</div>
</code>```

Body:
My database doesn't submit my values of my form, when I enter values into my form it shows nothing at all the varchar value columns and at the integer value columns there is a 0.   After I submit values

database

I'm using xampp.

   <?php
 error_reporting(0);

$con = mysqli_connect("localhost","root",'',"bwl_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dbhost = 'localhost';
$user = 'root';
$password = 'root123';
$database = 'bwl_db';

$Name =  $_POST['Name'];
$Surname =  $_POST['Surname'];
$Email =  $_POST['Email'];
$Telephone = $_POST['Telephone'];
$ID_Number = $_POST['ID_Number'];

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)
VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

mysqli_close($con);

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

?>

<!DOCTYPE html>

    <title>BWL | Registration </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>

    <link rel="icon" type="image/png" href="images/favicon.png">

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

    <link rel="stylesheet" href="css/font-awesome.min.css">

    <link rel="stylesheet" type="text/css" href="css/responsive.css">

    <form class="form-registration" action="reg_db.php" method="post">

 Registration

            Name

                <input class="form-control" name="Name" type="text" id="Name" placeholder="Enter Name">

            Surname

                <input class="form-control" name="Surname"  type="text" id="Surname" placeholder="Enter Surname">

            Email

                <input class="form-control" name="Email"  type="email" id="Email" placeholder="Enter email">

             Confirm Email

                <input class="form-control"  type="email" id="Confirm Email" placeholder="Confirm email">

            Telephone Number

                <input class="form-control" name="Telephone"  type="tel" id="telephone" placeholder="Enter Telephone Number">

            ID Number

                <input class="form-control" name="ID_Number"  type="text" id="id-number" placeholder="Enter ID Number">

                    Submit

 Disclaimer

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

 </form>

 VERIFY.HTML PAGE
    <!DOCTYPE html>

    <title>BWL | Verify </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>

    <link rel="icon" type="image/png" href="images/favicon.png">

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

    <link rel="stylesheet" href="css/font-awesome.min.css">

    <link rel="stylesheet" type="text/css" href="css/responsive.css">

Thank You

We will send you your login information when you are verified.

Body:
Your not using a submit-button you are just using a href so your data isn't submitted. Change your last line of the form to this:

<div class="form-group-row">
    <div class="col-sm-10">
         <input class="btn btn-default1" type="submit" value="Submit" />
    </div>
</div>


问:
Can't cast context to CustomCallBack interface in FragmentAdapter of a Fragment
I have problem when I cast the context in the FragmentAdapter of a Fragment. My app process is:
- When I click on navigation list item (Nav One) it will show the fragment with the recyclerview and cardview.
- When I click on the image of cardview list item I want get an action to show the Toast message or do something with a costom interface named (CustomCallBack).
This is my code:

MainActivity.java

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

    private Toolbar toolbar;
    private ListView lvNavigation;
    private DrawerLayout mDrawer;
    private NavigationView mNavigation;
    private LinearLayout llMianContain;
    String[] navigation = new String[]{"Nav One","Nav Two", "Nav Three","Nav Four"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        lvNavigation = (ListView) findViewById(R.id.lv_listView);
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        mNavigation= (NavigationView) findViewById(R.id.navigation_view);
        llMianContain = (LinearLayout) findViewById(R.id.ll_main_content);

        setSupportActionBar(toolbar);
        lvNavigation.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, navigation));
        lvNavigation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                replaceFragment(i);
                lvNavigation.setItemChecked(i, true);
                hideDrawer();
            }
        });

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.open, R.string.close);
        mDrawer.setDrawerListener(toggle);
        toggle.syncState();
    }
    private void replaceFragment(int position){
        Fragment fragment = null;
        switch (position){
            case 0:
                fragment = new OneFragment();
                break;
            case 1:
                fragment = new TwoFragment();
                break;
            case 2:
                fragment = new ThreeFragment();
                break;
            case 3:
                fragment= new FourFragment();
                break;
            default:
                fragment = new OneFragment();
                break;
        }
        if(null!= fragment){
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.ll_main_content, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    }
    private void hideDrawer(){
        mDrawer.closeDrawer(GravityCompat.START);
    }
    private void showDrawer(){
        mDrawer.openDrawer(GravityCompat.START);
    }
    @Override
    public void onBackPressed() {
        if (mDrawer.isDrawerOpen(GravityCompat.START))
            hideDrawer();
        else
            super.onBackPressed();
    }
}
</code>```

OneFragment.java

```<code>public class OneFragment extends Fragment implements FragmentOneAdapter.CustomCallBack{

    private ArrayList<ListItem> listItems;
    private RecyclerView recyclerView;
    private FragmentOneAdapter adapter;

    public OneFragment() { }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.fragment_one, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        listItems = new ArrayList<>();
        for(int i=0;i<40;i++){
            listItems.add(new ListItem(R.drawable.ic_account_circle_black_48dp, "MY NAME "+ i));
        }
        adapter = new FragmentOneAdapter(listItems, getActivity());
        recyclerView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onProfileClick(int position) {
        Toast.makeText(getActivity(), "position "+ position, Toast.LENGTH_SHORT).show();
    }
}
</code>```

FragmentAdapter.java

```<code>public class FragmentOneAdapter extends RecyclerView.Adapter<FragmentOneAdapter.FragmentOneViewHolder> {

    private ArrayList<ListItem> listItems;
    private Context context;
    final CustomCallBack customCallBack;

    public FragmentOneAdapter(ArrayList<ListItem> listItems, Context context){
        this.listItems = listItems;
        this.context = context;
        this.customCallBack = (CustomCallBack) context;
    }
    @Override
    public FragmentOneViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_one_item, parent,false);
        FragmentOneViewHolder holder = new FragmentOneViewHolder(view);

        return holder;
    }
    @Override
    public void onBindViewHolder(FragmentOneViewHolder holder, int position) {
        holder.tvName.setText(listItems.get(position).getName());
        holder.ivProfile.setImageResource(listItems.get(position).getProfile());
    }
    @Override
    public int getItemCount() {
        return listItems.size();
    }
    class FragmentOneViewHolder extends RecyclerView.ViewHolder{
        TextView tvName;
        ImageView ivProfile;
        LinearLayout llFooter;

        public FragmentOneViewHolder(View itemView) {
            super(itemView);
            tvName = (TextView) itemView.findViewById(R.id.tv_name);
            ivProfile = (ImageView) itemView.findViewById(R.id.iv_profile);
            llFooter= (LinearLayout) itemView.findViewById(R.id.ll_footer);

            ivProfile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    customCallBack.onProfileClick(getAdapterPosition());
                }
            });
        }
    }

//    MY Custom CallBack
    interface CustomCallBack{
        void onProfileClick(int position);
    }
}
</code>```

答:
Hmm,

So your Fragment is implementing CustomCallBack interface

Why don't you just pass the Fragment object itself to the adapter?

for example, in the FragmentOneAdapter.java,

change:

```<code>public FragmentOneAdapter(ArrayList<ListItem> listItems, Context context) ===> public FragmentOneAdapter(ArrayList<ListItem> listItems, CustomCallBack callback)
</code>```

then:

```<code>this.customCallBack = (CustomCallBack) context; ===> this.customCallBack = callback;
</code>```

Obviously, now in OneFragment.java,

just pass 'this' as parameter as the Fragment itself is the CustomCallBack:

```<code>adapter = new FragmentOneAdapter(listItems, getActivity()); ===> adapter = new FragmentOneAdapter(listItems, this);
</code>```

Body:
I have problem when I cast the context in the FragmentAdapter of a Fragment. My app process is:
- When I click on navigation list item (Nav One) it will show the fragment with the recyclerview and cardview.
- When I click on the image of cardview list item I want get an action to show the Toast message or do something with a costom interface named (CustomCallBack).
This is my code:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ListView lvNavigation;
    private DrawerLayout mDrawer;
    private NavigationView mNavigation;
    private LinearLayout llMianContain;
    String[] navigation = new String[]{"Nav One","Nav Two", "Nav Three","Nav Four"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        lvNavigation = (ListView) findViewById(R.id.lv_listView);
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        mNavigation= (NavigationView) findViewById(R.id.navigation_view);
        llMianContain = (LinearLayout) findViewById(R.id.ll_main_content);

        setSupportActionBar(toolbar);
        lvNavigation.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, navigation));
        lvNavigation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                replaceFragment(i);
                lvNavigation.setItemChecked(i, true);
                hideDrawer();
            }
        });

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.open, R.string.close);
        mDrawer.setDrawerListener(toggle);
        toggle.syncState();
    }
    private void replaceFragment(int position){
        Fragment fragment = null;
        switch (position){
            case 0:
                fragment = new OneFragment();
                break;
            case 1:
                fragment = new TwoFragment();
                break;
            case 2:
                fragment = new ThreeFragment();
                break;
            case 3:
                fragment= new FourFragment();
                break;
            default:
                fragment = new OneFragment();
                break;
        }
        if(null!= fragment){
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.ll_main_content, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    }
    private void hideDrawer(){
        mDrawer.closeDrawer(GravityCompat.START);
    }
    private void showDrawer(){
        mDrawer.openDrawer(GravityCompat.START);
    }
    @Override
    public void onBackPressed() {
        if (mDrawer.isDrawerOpen(GravityCompat.START))
            hideDrawer();
        else
            super.onBackPressed();
    }
}

OneFragment.java

public class OneFragment extends Fragment implements FragmentOneAdapter.CustomCallBack{

    private ArrayList<ListItem> listItems;
    private RecyclerView recyclerView;
    private FragmentOneAdapter adapter;

    public OneFragment() { }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.fragment_one, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        listItems = new ArrayList<>();
        for(int i=0;i<40;i++){
            listItems.add(new ListItem(R.drawable.ic_account_circle_black_48dp, "MY NAME "+ i));
        }
        adapter = new FragmentOneAdapter(listItems, getActivity());
        recyclerView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onProfileClick(int position) {
        Toast.makeText(getActivity(), "position "+ position, Toast.LENGTH_SHORT).show();
    }
}

FragmentAdapter.java

public class FragmentOneAdapter extends RecyclerView.Adapter<FragmentOneAdapter.FragmentOneViewHolder> {

    private ArrayList<ListItem> listItems;
    private Context context;
    final CustomCallBack customCallBack;

    public FragmentOneAdapter(ArrayList<ListItem> listItems, Context context){
        this.listItems = listItems;
        this.context = context;
        this.customCallBack = (CustomCallBack) context;
    }
    @Override
    public FragmentOneViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_one_item, parent,false);
        FragmentOneViewHolder holder = new FragmentOneViewHolder(view);

        return holder;
    }
    @Override
    public void onBindViewHolder(FragmentOneViewHolder holder, int position) {
        holder.tvName.setText(listItems.get(position).getName());
        holder.ivProfile.setImageResource(listItems.get(position).getProfile());
    }
    @Override
    public int getItemCount() {
        return listItems.size();
    }
    class FragmentOneViewHolder extends RecyclerView.ViewHolder{
        TextView tvName;
        ImageView ivProfile;
        LinearLayout llFooter;

        public FragmentOneViewHolder(View itemView) {
            super(itemView);
            tvName = (TextView) itemView.findViewById(R.id.tv_name);
            ivProfile = (ImageView) itemView.findViewById(R.id.iv_profile);
            llFooter= (LinearLayout) itemView.findViewById(R.id.ll_footer);

            ivProfile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    customCallBack.onProfileClick(getAdapterPosition());
                }
            });
        }
    }

//    MY Custom CallBack
    interface CustomCallBack{
        void onProfileClick(int position);
    }
}

Body:
Hmm,

So your Fragment is implementing CustomCallBack interface

Why don't you just pass the Fragment object itself to the adapter?

for example, in the FragmentOneAdapter.java,

change:

public FragmentOneAdapter(ArrayList<ListItem> listItems, Context context) ===> public FragmentOneAdapter(ArrayList<ListItem> listItems, CustomCallBack callback)

then:

this.customCallBack = (CustomCallBack) context; ===> this.customCallBack = callback;

Obviously, now in OneFragment.java,

just pass 'this' as parameter as the Fragment itself is the CustomCallBack:

adapter = new FragmentOneAdapter(listItems, getActivity()); ===> adapter = new FragmentOneAdapter(listItems, this);


问:
php cake find() using OR condition
I need a basic "or" in my if else condition in php cake.

```<code>$oTourRecords =  $this->Record->find('all', array(
    'conditions' => array(
        'record.builder_name' => 'rey',
            'or' => array(
                'record.builder_name' => 'norbert',
            )
         )
     )
);
</code>```

basically i need to get if the record contain builder_name = rey or "norbert"
this one returns null.

答:
You can do it in several ways:</p>

```<code>$oTourRecords =  $this->Record->findAllByBuilderNameOrBuilderName('rey', 'norbert');

$oTourRecords =  $this->Record->find('all', array(
        'conditions' => array(
            'OR' => array(
                    'record.builder_name' => 'norbert',
                    'record.builder_name' => 'rey',
                )
        )
     ));

$oTourRecords =  $this->Record->find('all', array(
        'conditions' => array('record.builder_name IN ' => array('norbert','rey'))
 ));
</code>```

Title: php cake find() using OR condition

Body:
I need a basic "or" in my if else condition in php cake.

$oTourRecords =  $this->Record->find('all', array(
    'conditions' => array(
        'record.builder_name' => 'rey',
            'or' => array(
                'record.builder_name' => 'norbert',
            )
         )
     )
);

basically i need to get if the record contain builder_name = rey or "norbert"
this one returns null.

Body:
You can do it in several ways:

$oTourRecords =  $this->Record->findAllByBuilderNameOrBuilderName('rey', 'norbert');

$oTourRecords =  $this->Record->find('all', array(
        'conditions' => array(
            'OR' => array(
                    'record.builder_name' => 'norbert',
                    'record.builder_name' => 'rey',
                )
        )
     ));

$oTourRecords =  $this->Record->find('all', array(
        'conditions' => array('record.builder_name IN ' => array('norbert','rey'))
 ));


问:
Element wise addition in spark rdd
I have an RDD of RDD[Array[Array[Double]]]. So essentially each element is a matrix. I need to do element wise addition.

so if the first element of the rdd is

```<code>    1 2
    3 4
</code>```

and second element is

```<code>   5 6
   7 8
</code>```

at the end i need to have

```<code>   6 8
   10 12
</code>```

I have looked into zip but not sure if I can use it for this case.

答:
Yes, you can use zip, but you'll have to use it twice, once for the rows and once for the columns:</p>

```<code>val rdd = sc.parallelize(List(Array(Array(1.0,2.0),Array(3.0,4.0)),
                              Array(Array(5.0,6.0),Array(7.0,8.0))))

rdd.reduce((a,b) => a.zip(b).map {case (c,d) => c.zip(d).map{ case (x,y) => x+y}})
</code>```

Title: Element wise addition in spark rdd

Body:
I have an RDD of RDD[Array[Array[Double]]]. So essentially each element is a matrix. I need to do element wise addition.

so if the first element of the rdd is

    1 2
    3 4

and second element is

   5 6
   7 8

at the end i need to have

   6 8
   10 12

I have looked into zip but not sure if I can use it for this case.

Body:
Yes, you can use zip, but you'll have to use it twice, once for the rows and once for the columns:

val rdd = sc.parallelize(List(Array(Array(1.0,2.0),Array(3.0,4.0)),
                              Array(Array(5.0,6.0),Array(7.0,8.0))))

rdd.reduce((a,b) => a.zip(b).map {case (c,d) => c.zip(d).map{ case (x,y) => x+y}})


问:
How do you update float data type in SQL column to hold numbers with upto 20 scale
I have a SQL table with a column having float data type with default precision.
I want this column to hold data with upto 20 digits after the decimal point.

How do I update existing column to do this?

答:
Just put decimal(precision, scale), replacing the precision and scale with your desired values.

ALTER TABLE TableName ALTER COLUMN ColumnName decimal(24,20)


问:
Function returns -nan
I have this code. Why does it produce -nan upon returning a value in main program?

```<code>#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    return powf(result, (float)1/(float)3);
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}
</code>```

This confuses me. As I far as I know, I use suitable data type.

答:
cplusplus reference say:

The NaN values are used to identify undefined or non-representable
  values for floating-point elements, such as the square root of
  negative numbers or the result of 0/0.

The argument can be used by library implementations to distinguish
  different NaN values in a implementation-specific manner.

Title: Function returns -nan

Body:
I have this code. Why does it produce -nan upon returning a value in main program?

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    return powf(result, (float)1/(float)3);
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}

This confuses me. As I far as I know, I use suitable data type.


问:
Bootstrap Carousel Not Responding (Jquery placed correctly)
I am currently facing issues in regards to Bootstrap's carousel not responding the navigation buttons being pressed. The majority of my search answers was that Jquery was not correctly BEFORE the Bootstrap CDN. I have tried even copy-pasting other snippets of code from answers and the navigation button still does not respond correctly to clicks.

```<code><head>
<meta charset="utf-8">
<title><!--title--></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css" type="text/css"/>
</head>
</code>```

Only the first image loads correctly, and the carousel seems to be "frozen."

Any help would be greatly appreciated.

Fiddle: https://jsfiddle.net/7dv1wm1w/

答:
I don't see Bootstrap's Javascript file, so that's your answer, why the carousel doesn't work.

On the getbootstrap.com you can find all the needed files. These which you always need are CSS and JS. Otherwise Bootstrap won't work.

```<code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</code>```

Body:
I am currently facing issues in regards to Bootstrap's carousel not responding the navigation buttons being pressed. The majority of my search answers was that Jquery was not correctly BEFORE the Bootstrap CDN. I have tried even copy-pasting other snippets of code from answers and the navigation button still does not respond correctly to clicks.

<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css" type="text/css"/>

Only the first image loads correctly, and the carousel seems to be "frozen."

Any help would be greatly appreciated.

Fiddle: https://jsfiddle.net/7dv1wm1w/

Body:
I don't see Bootstrap's Javascript file, so that's your answer, why the carousel doesn't work.

On the getbootstrap.com you can find all the needed files. These which you always need are CSS and JS. Otherwise Bootstrap won't work.

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


问:
JSON Split - Place array text into li during interval
My task is to take the 3 different color lists in the jsonObj and place them into a
. They should only appear one at a time, every second. For the sake of the fiddle, I put it to every 5 seconds.

I haven't gotten to the 2nd or 3rd list of colors yet because while I can list out my 1st color list, they're appending outside of the listItem I've created for them. The code it spits it is:

var jsonObj = '{"one":["red","green","blue"], "two":["red","green","blue"], "three":["orange","purple","hotpink"]}',
  object = JSON.parse(jsonObj),
  cOne = object.one,
  cTwo = object.two,
  cThree = object.three,
  i = 0,
  timer;

$('body').append('
');

timer = setInterval(function() {

  $.each(cOne, function() {
    var list = $('body ul'),
      listItem = $(list).append('
'),
      html = $(listItem).append(cOne[i]);

    if (i < cOne.length) {
      i++;
      $(cOne[i]).split("");
      list.append(html);

    } else if (i = cOne.length) {
      i = 0;
    }

  });

}, 5 * 1000);

timer;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Also available at https://jsfiddle.net/ep76ba3u/

What it does:

```<code><ul>
<li></li>
"red"
<li></li>
"blue"
</ul>
</code>```

What it should look like:

```<code><ul>
<li>red</li>
<li>blue</li>
</ul>
</code>```

I've tried rearranging it all. I've tried using wrap, innerWrap. I've tried just using text() and a few other methods. I started working on it at 3am and its 5am now... brain is fried. Any idea how to get this moving is appreciated.

答:
I feel compelled to put in an answer which should perform better by cache of the jQuery objects and processes the objects and each color in them, hitting DOM once for each color.

```<code>var jsonObj = '{"one":["red","green","blue"], "two":["red","cyan","darkblue"], "three":["orange","purple","hotpink"]}',
  objects = JSON.parse(jsonObj);

// set timer values
var basetime = 1000;
var delaytime = basetime;
// cache the ul list
var myul = $('<ul/>').appendTo('body');
//process outer objects
$.each(objects, function(key, item) {
  // process color array held in item
  $.each(item, function(index, color) {
    setTimeout(function() {
      $('<li/>').text(color).css('color', color).appendTo(myul);
    }, delaytime);
    delaytime = delaytime + basetime;
  });
});
</code>```

Test it out here https://jsfiddle.net/MarkSchultheiss/yb1w3o73/

Body:
My task is to take the 3 different color lists in the jsonObj and place them into a
. They should only appear one at a time, every second. For the sake of the fiddle, I put it to every 5 seconds.

I haven't gotten to the 2nd or 3rd list of colors yet because while I can list out my 1st color list, they're appending outside of the listItem I've created for them. The code it spits it is:

var jsonObj = '{"one":["red","green","blue"], "two":["red","green","blue"], "three":["orange","purple","hotpink"]}',
  object = JSON.parse(jsonObj),
  cOne = object.one,
  cTwo = object.two,
  cThree = object.three,
  i = 0,
  timer;

$('body').append('
');

timer = setInterval(function() {

  $.each(cOne, function() {
    var list = $('body ul'),
      listItem = $(list).append('
'),
      html = $(listItem).append(cOne[i]);

    if (i < cOne.length) {
      i++;
      $(cOne[i]).split("");
      list.append(html);

    } else if (i = cOne.length) {
      i = 0;
    }

  });

}, 5 * 1000);

timer;

Also available at https://jsfiddle.net/ep76ba3u/

What it does:

"red"

"blue"

What it should look like:

red

blue

I've tried rearranging it all. I've tried using wrap, innerWrap. I've tried just using text() and a few other methods. I started working on it at 3am and its 5am now... brain is fried. Any idea how to get this moving is appreciated.

Body:
I feel compelled to put in an answer which should perform better by cache of the jQuery objects and processes the objects and each color in them, hitting DOM once for each color.

var jsonObj = '{"one":["red","green","blue"], "two":["red","cyan","darkblue"], "three":["orange","purple","hotpink"]}',
  objects = JSON.parse(jsonObj);

// set timer values
var basetime = 1000;
var delaytime = basetime;
// cache the ul list
var myul = $('<ul/>').appendTo('body');
//process outer objects
$.each(objects, function(key, item) {
  // process color array held in item
  $.each(item, function(index, color) {
    setTimeout(function() {
      $('<li/>').text(color).css('color', color).appendTo(myul);
    }, delaytime);
    delaytime = delaytime + basetime;
  });
});

Test it out here https://jsfiddle.net/MarkSchultheiss/yb1w3o73/


答:
When you call your function with negative one the base is equal to -2 and the exponent is 1/3 (non-integer).

According to the specification for powf:

pow(base, exponent) returns NaN and raises FE_INVALID if base is finite and negative and exponent is finite and non-integer.

Which explains why your function is returning NaN.

If you're trying to calculuate the cubic root I suggest you use cbrt instead.

Title: Function returns -nan


问:
What setting has to be done to connect with database with this connection string given below?
In my .exe setup having connection string

```<code>Data Source=SERVER;Initial Catalog=POS_Chimur;User ID=sa;Integrated security=false
</code>```

I have to install database for this exe what settings will be needed according to above connectionString.

Till now I have installed sql server with default instance with name of pc SERVER. Still i am unable to connect with above connection string.

答:
I see two things mainly:

You are connecting with SQL Server login

Go to SQL Server Management studio

Connect to the database server with administrative account you know and that works

right mouse click on the server in the 'Object Explorer' window

choose security

In the Server authentication group, choose 'SQL Server and Windows Authentication mode'

Restart SQL Server

This account is sa and doesn't have a password

Go to SQL Server Management studio

connect to the database server with administrative account you know and that works

unfold the server object [-]

unfold the Security folder [-]

unfold the Logins folder => find sa login

right click on it and click Properties

In General section uncheck the Enforce password policy checkbox and clean the passwords in both text boxes

In Status section, make sure that Login is Enabled and that the Permissions to connect is set to Grant

click Ok

confirm, that you want to create a login with blank password (which is obviously always a risk)

After performing those steps, please log out, and try to log in again, but change the Authentication drop down value to 'SQL Server Authentication' and try to login with sa and empty password, if it works, then the connection string should be fine too.

Body:
In my .exe setup having connection string

Data Source=SERVER;Initial Catalog=POS_Chimur;User ID=sa;Integrated security=false

I have to install database for this exe what settings will be needed according to above connectionString.

Till now I have installed sql server with default instance with name of pc SERVER. Still i am unable to connect with above connection string.


问:
Pandas: how to add missing columns to a DataFrame when assigning Series as row
I have a bunch of Pandas Series which are produced one at a time, and I want to assign each of them as a row in a DataFrame, with the columns of the DataFrame being the union of all Series index values.

For example:

```<code>import numpy as np
import pandas as pd

# the names of all series are known in advance
df = pd.DataFrame(index=['A', 'B'])

# in reality there are many long series, not just two
a = pd.Series({'v':0, 'w':1, 'x':2, 'y':3}, name='A')
b = pd.Series({              'x':4, 'y':5, 'z':6}, name='B')

# generate and assign each series as one row in the frame
for row in (a,b):
    # create new columns - this is what I want to eliminate
    for column in row.index.difference(df.columns):
        df[column] = np.nan

    df.loc[row.name] = row

print(df)
</code>```

This produces the desired result:

```<code>     v    w    x    y    z
A  0.0  1.0  2.0  3.0  NaN
B  NaN  NaN  4.0  5.0  6.0
</code>```

But without the for column loop, it produces an empty DataFrame with no columns.

I am looking to eliminate the for column loop.  I don't know all the columns ahead of time.  I also hoped to assign np.nan to all the new columns in a vectorized way, but that doesn't work due to an old issue I submitted here: https://github.com/pandas-dev/pandas/issues/13658

答:
pd.DataFrame.set_value will automatically add the columns.

```<code>df = pd.DataFrame()

# in reality there are many long series, not just two
a = pd.Series({'v':0, 'w':1, 'x':2, 'y':3}, name='A')
b = pd.Series({              'x':4, 'y':5, 'z':6}, name='B')

# generate and assign each series as one row in the frame
for row in (a,b):
    for i, v in row.iteritems():
        df.set_value(row.name, i, v)

print(df)

     v    w    x    y    z
A  0.0  1.0  2.0  3.0  NaN
B  NaN  NaN  4.0  5.0  6.0
</code>```

This is still a loop, but set_value is pretty zippy.

time test

small data

```<code>df = pd.DataFrame()
los = [pd.Series(1, [i], name=i) for i in range(10)]

stmt1 = """
for row in los:
    for column in row.index.difference(df.columns):
        df[column] = np.nan

    df.loc[row.name, row.index] = row
"""

stmt2 = """
for row in los:
    for col, value in row.iteritems():
        df.set_value(row.name, col, value)
"""

setup = """
from __main__ import df, los, np
"""

print(timeit(stmt1, setup, number=100))
print(timeit(stmt2, setup, number=100))

0.5426401197910309
0.01039268122985959
</code>```

large data

```<code>df = pd.DataFrame()
los = [pd.Series(1, [i], name=i) for i in range(1000)]

stmt1 = """
for row in los:
    for column in row.index.difference(df.columns):
        df[column] = np.nan

    df.loc[row.name, row.index] = row
"""

stmt2 = """
for row in los:
    for col, value in row.iteritems():
        df.set_value(row.name, col, value)
"""

setup = """
from __main__ import df, los, np
"""

print(timeit(stmt1, setup, number=100))
print(timeit(stmt2, setup, number=100))

63.69273182330653
1.1242545540444553
</code>```

Body:
I have a bunch of Pandas Series which are produced one at a time, and I want to assign each of them as a row in a DataFrame, with the columns of the DataFrame being the union of all Series index values.

For example:

import numpy as np
import pandas as pd

# the names of all series are known in advance
df = pd.DataFrame(index=['A', 'B'])

# in reality there are many long series, not just two
a = pd.Series({'v':0, 'w':1, 'x':2, 'y':3}, name='A')
b = pd.Series({              'x':4, 'y':5, 'z':6}, name='B')

# generate and assign each series as one row in the frame
for row in (a,b):
    # create new columns - this is what I want to eliminate
    for column in row.index.difference(df.columns):
        df[column] = np.nan

    df.loc[row.name] = row

print(df)

This produces the desired result:

     v    w    x    y    z
A  0.0  1.0  2.0  3.0  NaN
B  NaN  NaN  4.0  5.0  6.0

But without the for column loop, it produces an empty DataFrame with no columns.

I am looking to eliminate the for column loop.  I don't know all the columns ahead of time.  I also hoped to assign np.nan to all the new columns in a vectorized way, but that doesn't work due to an old issue I submitted here: https://github.com/pandas-dev/pandas/issues/13658

Body:
pd.DataFrame.set_value will automatically add the columns.

df = pd.DataFrame()

# in reality there are many long series, not just two
a = pd.Series({'v':0, 'w':1, 'x':2, 'y':3}, name='A')
b = pd.Series({              'x':4, 'y':5, 'z':6}, name='B')

# generate and assign each series as one row in the frame
for row in (a,b):
    for i, v in row.iteritems():
        df.set_value(row.name, i, v)

print(df)

     v    w    x    y    z
A  0.0  1.0  2.0  3.0  NaN
B  NaN  NaN  4.0  5.0  6.0

This is still a loop, but set_value is pretty zippy.

time test

small data

df = pd.DataFrame()
los = [pd.Series(1, [i], name=i) for i in range(10)]

stmt1 = """
for row in los:
    for column in row.index.difference(df.columns):
        df[column] = np.nan

    df.loc[row.name, row.index] = row
"""

stmt2 = """
for row in los:
    for col, value in row.iteritems():
        df.set_value(row.name, col, value)
"""

setup = """
from __main__ import df, los, np
"""

print(timeit(stmt1, setup, number=100))
print(timeit(stmt2, setup, number=100))

0.5426401197910309
0.01039268122985959

large data

df = pd.DataFrame()
los = [pd.Series(1, [i], name=i) for i in range(1000)]

stmt1 = """
for row in los:
    for column in row.index.difference(df.columns):
        df[column] = np.nan

    df.loc[row.name, row.index] = row
"""

stmt2 = """
for row in los:
    for col, value in row.iteritems():
        df.set_value(row.name, col, value)
"""

setup = """
from __main__ import df, los, np
"""

print(timeit(stmt1, setup, number=100))
print(timeit(stmt2, setup, number=100))

63.69273182330653
1.1242545540444553


问:
how to make runnable instance to wait in one thread and notify by some othrer threads?
in the below code, one runnable instance is waiting to get notify. how to  notify this thread by some other thread should i use method or one more class which contains thread to notify.. i am stuck here please help...</p>

```<code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.cgi.sample.jms.requestor.RequestorApplication.Runner;

public class RequestorApplication {

    public static String correlationId;

    static ArrayList<Runner> list = new ArrayList<Runner>();

    static Map<Long, Runner> map = new HashMap<Long, Runner>();

    static Runner runner;

    public static void main(String args[]) throws Exception {

        RequestorApplication application = new RequestorApplication();

        application.waiter(map);

        System.out.println("All the threads are started");
    }

    public void waiter(Map<Long, Runner> map) {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 2; i++) {

            Runner instance = new Runner();

            System.out.println("Executing thread " + " with " + Thread.currentThread().getName());

            long threadId = Thread.currentThread().getId();

            String threadname = Thread.currentThread().getName();

            executor.execute(instance);

            RequestorApplication.runner = instance;

            synchronized (RequestorApplication.runner) {

                map.put(threadId, RequestorApplication.runner);

                try {
                    RequestorApplication.runner.wait();
                    // notifier(map);
                    System.out.println(threadname + "  Thread entered into waiting state!!!");
                    // Thread.currentThread().wait();
                    System.out.println(threadname + "  Thread woke up from wait!!!!!");

                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }
        }

    }

    public void notifier(Map<Long, Runner> map) {
        synchronized (RequestorApplication.runner) {

            for (Map.Entry<Long, Runner> entry : map.entrySet()) {

                System.out.println("stored threads in map are--->" + map.get(entry.getKey()));

                entry.getValue().notify();
            }

        }

    }

    class Runner implements Runnable {
        public void run() {
            System.out.println("runner invoked");

        }

    }

}
</code>```

答: @Gray is right but it's best to retrieve futures using a completionService rather than directly so that you can minimize waiting. CompletionService allows you to get the value from a future as future objects become available.</p>

Body:
in the below code, one runnable instance is waiting to get notify. how to  notify this thread by some other thread should i use method or one more class which contains thread to notify.. i am stuck here please help...

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.cgi.sample.jms.requestor.RequestorApplication.Runner;

public class RequestorApplication {

    public static String correlationId;

    static ArrayList<Runner> list = new ArrayList<Runner>();

    static Map<Long, Runner> map = new HashMap<Long, Runner>();

    static Runner runner;

    public static void main(String args[]) throws Exception {

        RequestorApplication application = new RequestorApplication();

        application.waiter(map);

        System.out.println("All the threads are started");
    }

    public void waiter(Map<Long, Runner> map) {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 2; i++) {

            Runner instance = new Runner();

            System.out.println("Executing thread " + " with " + Thread.currentThread().getName());

            long threadId = Thread.currentThread().getId();

            String threadname = Thread.currentThread().getName();

            executor.execute(instance);

            RequestorApplication.runner = instance;

            synchronized (RequestorApplication.runner) {

                map.put(threadId, RequestorApplication.runner);

                try {
                    RequestorApplication.runner.wait();
                    // notifier(map);
                    System.out.println(threadname + "  Thread entered into waiting state!!!");
                    // Thread.currentThread().wait();
                    System.out.println(threadname + "  Thread woke up from wait!!!!!");

                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }
        }

    }

    public void notifier(Map<Long, Runner> map) {
        synchronized (RequestorApplication.runner) {

            for (Map.Entry<Long, Runner> entry : map.entrySet()) {

                System.out.println("stored threads in map are--->" + map.get(entry.getKey()));

                entry.getValue().notify();
            }

        }

    }

    class Runner implements Runnable {
        public void run() {
            System.out.println("runner invoked");

        }

    }

}


问:
what does "executable" property defined in plugin configuration mean?
I come across a POM.xml, confused by the following part of it:

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.5.0</version>
    <executions>
        <execution>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <executable>java</executable>
        <mainClass>com.example.Main</mainClass>
        <additionalClasspathElements>${basedir}/target/conf,${basedir}/../conf</additionalClasspathElements>
    </configuration>
</plugin>
</code>```

what the above executable do? is it okay for me to remove the line?

答:
The simply answer to this is cause executable is not a valid configuration for the goal java...See the docs.

Only for the goal exec goal there is a parameter executable...

Body:
I come across a POM.xml, confused by the following part of it:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.5.0</version>
    <executions>
        <execution>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <executable>java</executable>
        <mainClass>com.example.Main</mainClass>
        <additionalClasspathElements>${basedir}/target/conf,${basedir}/../conf</additionalClasspathElements>
    </configuration>
</plugin>

what the above executable do? is it okay for me to remove the line?


问:
Spring Boot fails to load resources from subdirectories
I want to save different css and js files in different subdirectories and this is my directory structure

Then I tried import all these files into my index.html file (which is mapped by "/") but none of them were imported properly. What should I configure to enable Spring boot to search for resources recursively in all subdirectories under "resources"? Also what should I do if I also want to put all html templates in subdirectories?

Body:
You should remove the ../static/ as spring boot automatically expose all directories and sub-directories in the static folder on your main endpoint (default /).

so for example use:

<script src="js/jquery-1.11.8.min.js" ... />


问:
Draw contours correctly on the image (OpenCV/Python)
I am trying to draw contours around my test image. I am using canny edge detection in the background.

The findContours method works fine for my image but when I try to do drawContours method on that image. It does not show anything.

Here is what I have tried

```<code>import cv2
import numpy as np

image = cv2.imread('/path/to/image.jpg')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (11, 11), 0)
cv2.imshow("blurred", blurred)

canny = cv2.Canny(blurred, 30, 150)

(_, cnts, _) = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

print "Contours in the image, %d" % (len(cnts))

shape = image.copy()
cv2.drawContours(shape.copy(), cnts, -1, (0, 255, 0), 2)
cv2.imshow("Edges", shape)
</code>```

From what I gather from the docs, the fourth argument to the method drawContours would be used to specify the colour of the edge to be drawn over. But it does not show anything for instead of the green edge that I am expecting.

len(cnts) returns 2 for me

Here is the image I am trying it out with

I am using opencv version 3.0.0

Relevant SO question

EDIT: After changing the 3rd argument for cv2.findContours() to cv2.CHAIN_APPROX_NONE, it is still not showing the final green edges(or any colour for that matter) on the final cv2.imshow("Edges", shape) image. Here is what I get from the canny edge image

答:
You have to modify the last to lines of your code to:

You are already storing a copy of image in shape

```<code>shape = image.copy()
</code>```

So why do you use shape.copy() in cv2.drawContours() again?

Replace it as follows:

```<code>cv2.drawContours(shape, cnts, -1, (0, 255, 0), 2)
cv2.imshow("Edges", shape)
</code>```

NOTE: You already have copied the image once, so use it to draw the contours. You don't have to use a copied version of the copied image.

This is what you get as a result:

ContentLicense: CC BY-SA 4.0

Body:
I am trying to draw contours around my test image. I am using canny edge detection in the background.

The findContours method works fine for my image but when I try to do drawContours method on that image. It does not show anything.

Here is what I have tried

import cv2
import numpy as np

image = cv2.imread('/path/to/image.jpg')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (11, 11), 0)
cv2.imshow("blurred", blurred)

canny = cv2.Canny(blurred, 30, 150)

(_, cnts, _) = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

print "Contours in the image, %d" % (len(cnts))

shape = image.copy()
cv2.drawContours(shape.copy(), cnts, -1, (0, 255, 0), 2)
cv2.imshow("Edges", shape)

From what I gather from the docs, the fourth argument to the method drawContours would be used to specify the colour of the edge to be drawn over. But it does not show anything for instead of the green edge that I am expecting.

len(cnts) returns 2 for me

Here is the image I am trying it out with

I am using opencv version 3.0.0

Relevant SO question

EDIT: After changing the 3rd argument for cv2.findContours() to cv2.CHAIN_APPROX_NONE, it is still not showing the final green edges(or any colour for that matter) on the final cv2.imshow("Edges", shape) image. Here is what I get from the canny edge image

Body:
You have to modify the last to lines of your code to:

You are already storing a copy of image in shape

shape = image.copy()

So why do you use shape.copy() in cv2.drawContours() again?

Replace it as follows:

cv2.drawContours(shape, cnts, -1, (0, 255, 0), 2)
cv2.imshow("Edges", shape)

NOTE: You already have copied the image once, so use it to draw the contours. You don't have to use a copied version of the copied image.

This is what you get as a result:


问:
403 Permission error on Ajax Call in Yii?
I am new to Yii. I have created a module which has below codes:

Controller's Code:

```<code>public function accessRules()
{
    return array(
        array('allow',  // allow all users to perform 'index' and 'view' actions
            'actions'=>array('index','view'),
            'users'=>array('*'),
        ),
        array('allow', // allow authenticated user to perform 'create' and 'update' actions
            'actions'=>array('create','update'),
            'users'=>array('@'),
        ),
        array('allow', // allow admin user to perform 'admin' and 'delete' actions
            'actions'=>array('admin','delete','ajaxdialog'),
            'users'=>array('*'),
        ),
        array('deny',  // deny all users
            'users'=>array('*'),
        ),
    );
}
</code>```

AND here is action i want to use by ajax call:

```<code>public function actionAjaxdialog()
{
    $user_id =  $_POST['image_id'];
    $is_active = $_POST['status'];
    $model = $this->loadModel($image_id);
    $model->is_active = $is_active;
    $model->update();
}
</code>```

view's code:

```<code>$(document).ready(function(){
$('.changeStatus').live('click',function(){
    var status = $(this).attr('status');
    if(status==1)
    {
        status=0;
    }
    else
    {
        status=1;
    }
    var id = $(this).attr('image_id');
    var $link = $(this);

    $.ajax({

        type: "POST",
        url:    "<?php echo Yii::app()->createUrl('Gallery/Ajaxdialog'); ?>",
        data:  {image_id:id,status:status},
        success: function(msg)
        {
            if(status==0)
            {
                $link.attr('status','0');
                $link.attr('title','In-active :: click to activate.');
                $link.children('img').attr('src','/images/wrong.png');
                AfterStatusChange('Image has been de-activated sucessfully.');
                $link.parent().parent().removeClass('selected');
            }
            else
            {
                $link.attr('status','1');
                $link.attr('title','Active :: click to de-activate.');
                $link.children('img').attr('src','/images/right.png');
                AfterStatusChange('Image has been activated sucessfully.');
                $link.parent().parent().removeClass('selected');
            }

        },
        error: function(xhr){
            //alert("failure"+xhr.readyState+this.url)
            alert("failure"+xhr.responseText);
        }
    });

});
});
</code>```

I am working on localhost, i have update ".htaccess" file with following code:

```<code>deny from all
Allow from localhost
</code>```

It always gives me the following error when i tries to run it:

"Access forbidden"

Please help me how can i resolve this issue.

答:
add the csrfToken in ajax data.</p>

```<code>$.ajax({

        type: "POST",
        url:    "<?php echo Yii::app()->createUrl('Gallery/Ajaxdialog'); ?>",
        data:  {<?= Yii::$app->request->csrfParam; ?> : '<?= Yii::$app->request->csrfToken; ?>',image_id:id,status:status},
        success: function(msg)
        {
            if(status==0)
            {
                $link.attr('status','0');
                $link.attr('title','In-active :: click to activate.');
                $link.children('img').attr('src','/images/wrong.png');
                AfterStatusChange('Image has been de-activated sucessfully.');
                $link.parent().parent().removeClass('selected');
            }
            else
            {
                $link.attr('status','1');
                $link.attr('title','Active :: click to de-activate.');
                $link.children('img').attr('src','/images/right.png');
                AfterStatusChange('Image has been activated sucessfully.');
                $link.parent().parent().removeClass('selected');
            }

        },
        error: function(xhr){
            //alert("failure"+xhr.readyState+this.url)
            alert("failure"+xhr.responseText);
        }
    });
</code>```

Body:
I am new to Yii. I have created a module which has below codes:

Controller's Code:

public function accessRules()
{
    return array(
        array('allow',  // allow all users to perform 'index' and 'view' actions
            'actions'=>array('index','view'),
            'users'=>array('*'),
        ),
        array('allow', // allow authenticated user to perform 'create' and 'update' actions
            'actions'=>array('create','update'),
            'users'=>array('@'),
        ),
        array('allow', // allow admin user to perform 'admin' and 'delete' actions
            'actions'=>array('admin','delete','ajaxdialog'),
            'users'=>array('*'),
        ),
        array('deny',  // deny all users
            'users'=>array('*'),
        ),
    );
}

AND here is action i want to use by ajax call:

public function actionAjaxdialog()
{
    $user_id =  $_POST['image_id'];
    $is_active = $_POST['status'];
    $model = $this->loadModel($image_id);
    $model->is_active = $is_active;
    $model->update();
}

view's code:

$(document).ready(function(){
$('.changeStatus').live('click',function(){
    var status = $(this).attr('status');
    if(status==1)
    {
        status=0;
    }
    else
    {
        status=1;
    }
    var id = $(this).attr('image_id');
    var $link = $(this);

    $.ajax({

        type: "POST",
        url:    "<?php echo Yii::app()->createUrl('Gallery/Ajaxdialog'); ?>",
        data:  {image_id:id,status:status},
        success: function(msg)
        {
            if(status==0)
            {
                $link.attr('status','0');
                $link.attr('title','In-active :: click to activate.');
                $link.children('img').attr('src','/images/wrong.png');
                AfterStatusChange('Image has been de-activated sucessfully.');
                $link.parent().parent().removeClass('selected');
            }
            else
            {
                $link.attr('status','1');
                $link.attr('title','Active :: click to de-activate.');
                $link.children('img').attr('src','/images/right.png');
                AfterStatusChange('Image has been activated sucessfully.');
                $link.parent().parent().removeClass('selected');
            }

        },
        error: function(xhr){
            //alert("failure"+xhr.readyState+this.url)
            alert("failure"+xhr.responseText);
        }
    });

});
});

I am working on localhost, i have update ".htaccess" file with following code:

deny from all
Allow from localhost

It always gives me the following error when i tries to run it:

"Access forbidden"

Please help me how can i resolve this issue.

Body:
add the csrfToken in ajax data.

$.ajax({

        type: "POST",
        url:    "<?php echo Yii::app()->createUrl('Gallery/Ajaxdialog'); ?>",
        data:  {<?= Yii::$app->request->csrfParam; ?> : '<?= Yii::$app->request->csrfToken; ?>',image_id:id,status:status},
        success: function(msg)
        {
            if(status==0)
            {
                $link.attr('status','0');
                $link.attr('title','In-active :: click to activate.');
                $link.children('img').attr('src','/images/wrong.png');
                AfterStatusChange('Image has been de-activated sucessfully.');
                $link.parent().parent().removeClass('selected');
            }
            else
            {
                $link.attr('status','1');
                $link.attr('title','Active :: click to de-activate.');
                $link.children('img').attr('src','/images/right.png');
                AfterStatusChange('Image has been activated sucessfully.');
                $link.parent().parent().removeClass('selected');
            }

        },
        error: function(xhr){
            //alert("failure"+xhr.readyState+this.url)
            alert("failure"+xhr.responseText);
        }
    });


问:
AspectJ expose annotation value using AspectJ annotations
I'm using AspectJ annotations instead of writing actual aspect files. I want to expose an annotation value to my advice.

I currently have this but it it doesn't expose the values inside MyAnnotation

```<code>@Before("execution(@MyAnnotation * * (..))")
public void intercept(JoinPoint jp) {
 ...
}
</code>```

What I was thinking was something like this:

```<code>@Before("execution(@MyAnnotation * * (..)) && @this(MyAnnotation)")
public void intercept(JoinPoint jp, MyAnnotation myAnnotation) {
 ...
}
</code>```

This clearly has a syntax error but was wondering if I was close. I can't seem to find an example syntax when using AspectJ annotations to do this.

答:
You are using type, when you should be using an identifier. The correct code is:</p>

```<code>@Before("execution(@MyAnnotation * * (..)) && @this(myAnnotation)")
public void intercept(JoinPoint jp, MyAnnotation myAnnotation) {
 ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using AspectJ annotations instead of writing actual aspect files. I want to expose an annotation value to my advice.

I currently have this but it it doesn't expose the values inside MyAnnotation

@Before("execution(@MyAnnotation * * (..))")
public void intercept(JoinPoint jp) {
 ...
}

What I was thinking was something like this:

@Before("execution(@MyAnnotation * * (..)) && @this(MyAnnotation)")
public void intercept(JoinPoint jp, MyAnnotation myAnnotation) {
 ...
}

This clearly has a syntax error but was wondering if I was close. I can't seem to find an example syntax when using AspectJ annotations to do this.

Body:
You are using type, when you should be using an identifier. The correct code is:

@Before("execution(@MyAnnotation * * (..)) && @this(myAnnotation)")
public void intercept(JoinPoint jp, MyAnnotation myAnnotation) {
 ...
}


问:
recursive batch-file for movin *.doc, *.pdf, etc
I recovered the files from a HDD with windows 7 installed
now I have a mess in a folder, with thousands and thousands of files and folders, I really don't know much about batch coding but by watching some youtube videos I could get to the next below, but that batch-file only looks for files in the current folder where I execute the batch, I want it to look in the folders inside that folder and so..
Sorry for my bad English</p>

```<code>@echo off

move /y "*.xml" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\xml"

move /y "*.pdf" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\documentos"

move /y "*.cat" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\cat"

move /y "*.dll" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\dll"
</code>```

答:
```<code>@echo off
SETLOCAL
for /D /R %%a in (*) do (
 pushd "%%a"
 move /y "*.xml" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\xml"
 move /y "*.pdf" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\documentos"
 move /y "*.cat" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\cat"
 move /y "*.dll" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\dll"
popd
)
</code>```

This should execute the series of commands in all directories from the source.

The SETLOCAL is optional - it ensures that any changes to the environment are discarded when the bathc ends. There are none in this case, but it's common practice regardless.

The for /d instruction assigns each directoryname matching the mask * in turn to %%a. The pushd temporarily sets the default directory to that name, the move instructions are executed and the popd restores the original directory.

Be careful though - remember that if any file x.ext is found more than once, the very last one with that name will be moved, replacing any others.

Perhaps

```<code>xcopy /s *.xml "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\"
</code>```

may help. It will copy all .xml files from the source to the destination, building the same directory structure under the destination directory as exists under the source directory. In that way, you'd have a copy of the original files in case there is a duplicated name. Obviously,  you would need to repet the instruction for each filetype you require.

Body:
I recovered the files from a HDD with windows 7 installed
now I have a mess in a folder, with thousands and thousands of files and folders, I really don't know much about batch coding but by watching some youtube videos I could get to the next below, but that batch-file only looks for files in the current folder where I execute the batch, I want it to look in the folders inside that folder and so..
Sorry for my bad English

@echo off

move /y "*.xml" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\xml"

move /y "*.pdf" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\documentos"

move /y "*.cat" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\cat"

move /y "*.dll" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\dll"

Body:
@echo off
SETLOCAL
for /D /R %%a in (*) do (
 pushd "%%a"
 move /y "*.xml" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\xml"
 move /y "*.pdf" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\documentos"
 move /y "*.cat" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\cat"
 move /y "*.dll" "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\dll"
popd
)

This should execute the series of commands in all directories from the source.

The SETLOCAL is optional - it ensures that any changes to the environment are discarded when the bathc ends. There are none in this case, but it's common practice regardless.

The for /d instruction assigns each directoryname matching the mask * in turn to %%a. The pushd temporarily sets the default directory to that name, the move instructions are executed and the popd restores the original directory.

Be careful though - remember that if any file x.ext is found more than once, the very last one with that name will be moved, replacing any others.

Perhaps

xcopy /s *.xml "D:\backUP_arqui\Recovered data 03-10 20_23_41\Deep Scan result\"

may help. It will copy all .xml files from the source to the destination, building the same directory structure under the destination directory as exists under the source directory. In that way, you'd have a copy of the original files in case there is a duplicated name. Obviously,  you would need to repet the instruction for each filetype you require.


问:
Chart.js Multiple dataset
I have a problem with Chart.js.

I want an an alert show me the ID value set in the dataset when I click on a point in the chart.

I have tried using getElementsAtEvent(evt);, but it doesn't work as I expected.

Can somebody help me? Thanks!

var ctx = document.getElementById("myChart");
var color = ["#ff6384", "#5959e6", "#2babab", "#8c4d15", "#8bc34a", "#607d8b", "#009688"];

var scatterChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
        label: 'Linea A',
        backgroundColor: "transparent",
        borderColor: color[1],
        pointBackgroundColor: color[1],
        pointBorderColor: color[1],
        pointHoverBackgroundColor: color[1],
        pointHoverBorderColor: color[1],
        data: [{
          x: "2014-09-02",
          y: 90,
          id: '1A'
        }, {
          x: "2014-11-02",
          y: 96,
          id: '2A'
        }, {
          x: "2014-12-03",
          y: 97,
          id: '3A'
        }]
      },
      {
        label: 'Linea B',
        backgroundColor: "transparent",
        borderColor: color[2],
        pointBackgroundColor: color[2],
        pointBorderColor: color[2],
        pointHoverBackgroundColor: color[2],
        pointHoverBorderColor: color[2],
        data: [{
          x: "2014-09-01",
          y: 96,
          id: "1B"
        }, {
          x: "2014-10-04",
          y: 95.8,
          id: "2B"
        }, {
          x: "2014-11-06",
          y: 99,
          id: "3B"
        }]
      }
    ]
  },
  options: {
    title: {
      display: true,
      text: 'Polveri',
      fontSize: 18
    },
    legend: {
      display: true,
      position: "bottom"
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'MM/YY',
            'second': 'MM/YY',
            'minute': 'MM/YY',
            'hour': 'MM/YY',
            'day': 'MM/YY',
            'week': 'MM/YY',
            'month': 'MM/YY',
            'quarter': 'MM/YY',
            'year': 'MM/YY',
          },
          tooltipFormat: "DD/MM/YY"
        }
      }]
    }
  }
});

document.getElementById("myChart").onclick = function(evt) {
  var activePoints = scatterChart.getElementsAtEvent(evt);
  var firstPoint = activePoints[1];
  console.log(firstPoint._datasetIndex);
  console.log(firstPoint._index);
  var label = scatterChart.data.labels[firstPoint._index];
  console.log(scatterChart.data.datasets[0].data[0].id);
  var value = scatterChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
  if (firstPoint !== undefined)
    alert(label + ": " + value);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js">
</script>
<canvas id="myChart" width="400" height="100"></canvas></code>```

答:
You have to change your label variable assignment from,

```<code>var label = scatterChart.data.labels[firstPoint._index];
</code>```

To,

```<code>var label = scatterChart.data.datasets[firstPoint._index].label;
</code>```

And you may also need to change your alert statment as,

```<code>alert(label + ": " + value.x);
</code>```

Here is the working DEMO: https://jsfiddle.net/dt6c9jev/

Hope this helps!.

Title: Chart.js Multiple dataset

Body:
I have a problem with Chart.js.

I want an an alert show me the ID value set in the dataset when I click on a point in the chart.

I have tried using getElementsAtEvent(evt);, but it doesn't work as I expected.

Can somebody help me? Thanks!

var ctx = document.getElementById("myChart");
var color = ["#ff6384", "#5959e6", "#2babab", "#8c4d15", "#8bc34a", "#607d8b", "#009688"];

var scatterChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
        label: 'Linea A',
        backgroundColor: "transparent",
        borderColor: color[1],
        pointBackgroundColor: color[1],
        pointBorderColor: color[1],
        pointHoverBackgroundColor: color[1],
        pointHoverBorderColor: color[1],
        data: [{
          x: "2014-09-02",
          y: 90,
          id: '1A'
        }, {
          x: "2014-11-02",
          y: 96,
          id: '2A'
        }, {
          x: "2014-12-03",
          y: 97,
          id: '3A'
        }]
      },
      {
        label: 'Linea B',
        backgroundColor: "transparent",
        borderColor: color[2],
        pointBackgroundColor: color[2],
        pointBorderColor: color[2],
        pointHoverBackgroundColor: color[2],
        pointHoverBorderColor: color[2],
        data: [{
          x: "2014-09-01",
          y: 96,
          id: "1B"
        }, {
          x: "2014-10-04",
          y: 95.8,
          id: "2B"
        }, {
          x: "2014-11-06",
          y: 99,
          id: "3B"
        }]
      }
    ]
  },
  options: {
    title: {
      display: true,
      text: 'Polveri',
      fontSize: 18
    },
    legend: {
      display: true,
      position: "bottom"
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'MM/YY',
            'second': 'MM/YY',
            'minute': 'MM/YY',
            'hour': 'MM/YY',
            'day': 'MM/YY',
            'week': 'MM/YY',
            'month': 'MM/YY',
            'quarter': 'MM/YY',
            'year': 'MM/YY',
          },
          tooltipFormat: "DD/MM/YY"
        }
      }]
    }
  }
});

document.getElementById("myChart").onclick = function(evt) {
  var activePoints = scatterChart.getElementsAtEvent(evt);
  var firstPoint = activePoints[1];
  console.log(firstPoint._datasetIndex);
  console.log(firstPoint._index);
  var label = scatterChart.data.labels[firstPoint._index];
  console.log(scatterChart.data.datasets[0].data[0].id);
  var value = scatterChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
  if (firstPoint !== undefined)
    alert(label + ": " + value);
};

<canvas id="myChart" width="400" height="100"></canvas>

Body:
You have to change your label variable assignment from,

var label = scatterChart.data.labels[firstPoint._index];

To,

var label = scatterChart.data.datasets[firstPoint._index].label;

And you may also need to change your alert statment as,

alert(label + ": " + value.x);

Here is the working DEMO: https://jsfiddle.net/dt6c9jev/

Hope this helps!.


问:
Making a new object, cannot be applied to type (int)
I have a ProcessHeap class that has two fields:

Heap: an array of type Process which represents the heap

Size: the number of elements in the heap

My constructor and attributes look like this:

```<code>private Process[] heap;
private int size;
private static int counter = 0;

//Paramaterized construct
    public ProcessHeap(Process[] heap, int size) {
        this.heap = heap;
        this.size = size;
</code>```

The problem is, we were given a driver and at the start of the driver I am getting an error particularly on (HEAP_SIZE)

This is the line:

```<code>final int HEAP_SIZE = 100;
ProcessHeap heap = new ProcessHeap(HEAP_SIZE); // gives this error:
</code>```

The error upon mouse-over states:

ProcessHeap (Process[], int) in ProcessHeap cannot be applied to (int)

答:
In your ProcessHeap class, you don't have a constructor which takes int argument, so declare it as shown below:

```<code>public class ProcessHeap {

   private int heapSize;

    public ProcessHeap(int heapSize) {
      this.heapSize = heapSize;
    }

    //your other existing code

}
</code>```

Body:
I have a ProcessHeap class that has two fields:

Heap: an array of type Process which represents the heap

Size: the number of elements in the heap

My constructor and attributes look like this:

private Process[] heap;
private int size;
private static int counter = 0;

//Paramaterized construct
    public ProcessHeap(Process[] heap, int size) {
        this.heap = heap;
        this.size = size;

The problem is, we were given a driver and at the start of the driver I am getting an error particularly on (HEAP_SIZE)

This is the line:

final int HEAP_SIZE = 100;
ProcessHeap heap = new ProcessHeap(HEAP_SIZE); // gives this error:

The error upon mouse-over states:

ProcessHeap (Process[], int) in ProcessHeap cannot be applied to (int)

Body:
In your ProcessHeap class, you don't have a constructor which takes int argument, so declare it as shown below:

public class ProcessHeap {

   private int heapSize;

    public ProcessHeap(int heapSize) {
      this.heapSize = heapSize;
    }

    //your other existing code

}