问:
Scanner : Exception in thread "main" java.util.NoSuchElementException
I'm trying to create an Utility Class to take inputs from the Standard Console using java.util.Scanner

```<code>package dbasics;

import java.util.*;

public class Utils {

    public static int getNumericInput() {
        System.out.println("Enter a integer ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.close();
        return n;
    }

    public static int[] getNumericArrayInput(int n) {
        //System.out.println("Enter "+n+"  integers seperated by a whitespace ");
         int[] numbers = new int[n];
         Scanner scanner = new Scanner(System.in);
         for (int i = 0; i < n; i++) {
                 numbers[i] =scanner.nextInt();
             }

         scanner.close();
         return numbers;
    }

}
</code>```

While calling the static methods in another class the method getNumericInput() works fine however the following method getNumericArrayInput(int n) results in an exception.

```<code>package dbasics;

public class Demo {

    public static void main(String[] args) {

        int n = Utils.getNumericInput();
        System.out.println("Number "+n);
        int arr[] = Utils.getNumericArrayInput(n);
        for(int i : arr) {
            System.out.println(i);
        }
    }

}
</code>```

Running this results in following exception

```<code>Enter a integer
5
Number 5
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at dbasics.Utils.getNumericArrayInput(Utils.java:21)
    at dbasics.Demo.main(Demo.java:9)
</code>```

The intresting thing I have noticed is if I comment out the first input procedure the array input works fine

答:
You are closing Scanner in your function that is causing in Exception:
Try this:

```<code>import java.util.*;

class Utils {

    public static int getNumericInput() {
        System.out.println("Enter a integer ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        return n;
    }

    public static int[] getNumericArrayInput(int n) {
         int[] numbers = new int[n];
         Scanner scanner = new Scanner(System.in);
         for (int i = 0; i < n; i++) {
                 numbers[i] =scanner.nextInt();
             }

         scanner.close();
         return numbers;
    }

}
public class cn {

    public static void main(String[] args) {

        int n = Utils.getNumericInput();
        System.out.println("Number "+n);
        try{
        int arr[] = Utils.getNumericArrayInput(n);

        for(int i : arr) {
            System.out.println(i);
        }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        }
    }
</code>```

For more information please read this link

Body:
I'm trying to create an Utility Class to take inputs from the Standard Console using java.util.Scanner

package dbasics;

import java.util.*;

public class Utils {

    public static int getNumericInput() {
        System.out.println("Enter a integer ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.close();
        return n;
    }

    public static int[] getNumericArrayInput(int n) {
        //System.out.println("Enter "+n+"  integers seperated by a whitespace ");
         int[] numbers = new int[n];
         Scanner scanner = new Scanner(System.in);
         for (int i = 0; i < n; i++) {
                 numbers[i] =scanner.nextInt();
             }

         scanner.close();
         return numbers;
    }

}

While calling the static methods in another class the method getNumericInput() works fine however the following method getNumericArrayInput(int n) results in an exception.

package dbasics;

public class Demo {

    public static void main(String[] args) {

        int n = Utils.getNumericInput();
        System.out.println("Number "+n);
        int arr[] = Utils.getNumericArrayInput(n);
        for(int i : arr) {
            System.out.println(i);
        }
    }

}

Running this results in following exception

Enter a integer
5
Number 5
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at dbasics.Utils.getNumericArrayInput(Utils.java:21)
    at dbasics.Demo.main(Demo.java:9)

The intresting thing I have noticed is if I comment out the first input procedure the array input works fine

Body:
You are closing Scanner in your function that is causing in Exception:
Try this:

import java.util.*;

class Utils {

    public static int getNumericInput() {
        System.out.println("Enter a integer ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        return n;
    }

    public static int[] getNumericArrayInput(int n) {
         int[] numbers = new int[n];
         Scanner scanner = new Scanner(System.in);
         for (int i = 0; i < n; i++) {
                 numbers[i] =scanner.nextInt();
             }

         scanner.close();
         return numbers;
    }

}
public class cn {

    public static void main(String[] args) {

        int n = Utils.getNumericInput();
        System.out.println("Number "+n);
        try{
        int arr[] = Utils.getNumericArrayInput(n);

        for(int i : arr) {
            System.out.println(i);
        }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        }
    }

For more information please read this link


来源: stackexchange

问:
concatenate multi-index dataframe with dataframe
I am trying to concatenate 2 dataframe df1 and df2
df1 is a multiindex dataframe and df2 has less rows than df1

```<code>import pandas as pd
import numpy as np
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df1 = pd.DataFrame(np.random.randn(8), index=index)

df1
Out[15]:
                     0
first second
bar   one    -0.185560
      two    -2.358254
baz   one     1.130550
      two     1.441708
foo   one    -1.163076
      two     1.776814
qux   one    -0.811836
      two     0.389500

df2 = pd.DataFrame(data=[0,1,0,1],index=['bar','baz','foo', 'qux'],columns=['label'])

df2
Out[18]:
     label
bar      0
baz      1
foo      0
qux      1
</code>```

The desired result would be something like:

```<code>df3
Out[18]:
                     0      label
first second
bar   one    -0.185560          0
      two    -2.358254          0
baz   one     1.130550          1
      two     1.441708          1
foo   one    -1.163076          0
      two     1.776814          0
qux   one    -0.811836          1
      two     0.389500          1
</code>```

答:
Another method is to just reset_index on the second level, you can then just add the column which will align on the first level index values, and then set the index back again:

```<code>In[52]:
df3 = df1.reset_index(level=1)
df3['label'] = df2['label']
df3 = df3.set_index([df3.index, 'second'])
df3

Out[52]:
                     0  label
first second
bar   one     0.957417      0
      two    -0.466755      0
baz   one     1.064326      1
      two     1.036983      1
foo   one    -1.319737      0
      two     0.064465      0
qux   one    -0.237232      1
      two    -0.511889      1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to concatenate 2 dataframe df1 and df2
df1 is a multiindex dataframe and df2 has less rows than df1

import pandas as pd
import numpy as np
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df1 = pd.DataFrame(np.random.randn(8), index=index)

df1
Out[15]:
                     0
first second
bar   one    -0.185560
      two    -2.358254
baz   one     1.130550
      two     1.441708
foo   one    -1.163076
      two     1.776814
qux   one    -0.811836
      two     0.389500

df2 = pd.DataFrame(data=[0,1,0,1],index=['bar','baz','foo', 'qux'],columns=['label'])

df2
Out[18]:
     label
bar      0
baz      1
foo      0
qux      1

The desired result would be something like:

df3
Out[18]:
                     0      label
first second
bar   one    -0.185560          0
      two    -2.358254          0
baz   one     1.130550          1
      two     1.441708          1
foo   one    -1.163076          0
      two     1.776814          0
qux   one    -0.811836          1
      two     0.389500          1

Body:
Another method is to just reset_index on the second level, you can then just add the column which will align on the first level index values, and then set the index back again:

In[52]:
df3 = df1.reset_index(level=1)
df3['label'] = df2['label']
df3 = df3.set_index([df3.index, 'second'])
df3

Out[52]:
                     0  label
first second
bar   one     0.957417      0
      two    -0.466755      0
baz   one     1.064326      1
      two     1.036983      1
foo   one    -1.319737      0
      two     0.064465      0
qux   one    -0.237232      1
      two    -0.511889      1


问:
Undefined behavior while using vectors (STL), Please explain the below code output behind reason
This one may well work with some compilers/OS, and crash with others. Same code with "List" it's working fine, While using "vector" only I am facing undefined behavior output.
Is STL (vector) is safe??

Note: This is not a real-time code, I am just going through some sample programs that's it.

```<code>#include <vector>
#include <iostream>

using namespace std;

int main() {
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  for (vector<int>::iterator i = v.begin();
       i != v.end(); i++) {
    cout << *i << endl;
    if (*i == 1) {
      v.push_back(5);
    }
  }
}
</code>```

Output with vector:
1
0
3
4
0
0
4113
0
858851888
943206709
2617
.
.
1
2
3
4
5
5

```<code>#include <list>
#include <iostream>

using namespace std;

int main() {
  list<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  for (list<int>::iterator i = v.begin();
       i != v.end(); i++) {
    cout << *i << endl;
    if (*i == 1) {
      v.push_back(5);
    }
  }
}
</code>```

Output with list:
1
2
3
4
5

答:
The line in the loop:

```<code>v.push_back(5);
</code>```

might invalidate the iterator i (in the case a re-allocation is needed), so since then ++i is undefined behaviour.

One possibility to fix this is to reserve the vector first, so that the reallocation does not happen:

```<code>  vector<int> v;
  v.reserve(5); // reserve enough to keep all the pushed items
  v.push_back(1);
  ...
</code>```

Body:
This one may well work with some compilers/OS, and crash with others. Same code with "List" it's working fine, While using "vector" only I am facing undefined behavior output.
Is STL (vector) is safe??

Note: This is not a real-time code, I am just going through some sample programs that's it.

#include <vector>
#include <iostream>

using namespace std;

int main() {
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  for (vector<int>::iterator i = v.begin();
       i != v.end(); i++) {
    cout << *i << endl;
    if (*i == 1) {
      v.push_back(5);
    }
  }
}

Output with vector:
1
0
3
4
0
0
4113
0
858851888
943206709
2617
.
.
1
2
3
4
5
5

#include <list>
#include <iostream>

using namespace std;

int main() {
  list<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  for (list<int>::iterator i = v.begin();
       i != v.end(); i++) {
    cout << *i << endl;
    if (*i == 1) {
      v.push_back(5);
    }
  }
}

Output with list:
1
2
3
4
5

Body:
The line in the loop:

v.push_back(5);

might invalidate the iterator i (in the case a re-allocation is needed), so since then ++i is undefined behaviour.

One possibility to fix this is to reserve the vector first, so that the reallocation does not happen:

  vector<int> v;
  v.reserve(5); // reserve enough to keep all the pushed items
  v.push_back(1);
  ...


问:
JQuery not adding class on click
I'm struggeling with some code, I have code to when I click a
 element it changes the iframe src and removes the class 'active' of all the elements in the .html file and then add the class 'active' to the clicked element.

But the class 'active' never gets added to the clicked element.

JAVASCRIPT

```<code>function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(this).addClass('active');
};
</code>```

HTML

```<code><li class="w-100" id="http://whatever.com/" onclick="return loadIframe(this.id);">
    <p>

        <i class="fa fa-id-badge" aria-hidden="true"></i>
        <span class="nav-label">Intranet</span>

    </p>
</li>
</code>```

答:
you could pass the context (element) to the handler. I expect this to work:

```<code>loadIframe(this.id, this)
</code>```

And,

```<code>function loadIframe(url, element){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(element).addClass('active');
};
</code>```

Let me know if that works for you.

Stray comment: I am not sure if it is a good practice to call url an id. You might find data-attributes useful. Attributes like data-id = "". In fact I would call it data-url.

Title: JQuery not adding class on click

Body:
I'm struggeling with some code, I have code to when I click a
 element it changes the iframe src and removes the class 'active' of all the elements in the .html file and then add the class 'active' to the clicked element.

But the class 'active' never gets added to the clicked element.

JAVASCRIPT

function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(this).addClass('active');
};

HTML

        Intranet

Body:
you could pass the context (element) to the handler. I expect this to work:

loadIframe(this.id, this)

And,

function loadIframe(url, element){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(element).addClass('active');
};

Let me know if that works for you.

Stray comment: I am not sure if it is a good practice to call url an id. You might find data-attributes useful. Attributes like data-id = "". In fact I would call it data-url.


问:
Where is log file of mongodb in mac
I installed mongodb in my mac and following is the way I installed. Where is my mongodb log file located?

```<code>$ tar xzf mongodb-osx-x86_64-2.2.3.tgz
$ sudo mv mongodb-osx-x86_64-2.2.3 /usr/local/mongodb

$ sudo mkdir -p /data/db
$ sudo chown 'whoami' /data/db

$ vim .bash_profile

  export MONGO_PATH=/usr/local/mongodb
  export PATH=$PATH:$MONGO_PATH/bin
</code>```

Where is the settings file of mongodb located which stores all this information.

答:
From the mongo shell you can find the path for data, log and config using: </p>

```<code>   db.serverCmdLineOpts()
</code>```

Title: Where is log file of mongodb in mac

Body:
I installed mongodb in my mac and following is the way I installed. Where is my mongodb log file located?

$ tar xzf mongodb-osx-x86_64-2.2.3.tgz
$ sudo mv mongodb-osx-x86_64-2.2.3 /usr/local/mongodb

$ sudo mkdir -p /data/db
$ sudo chown 'whoami' /data/db

$ vim .bash_profile

  export MONGO_PATH=/usr/local/mongodb
  export PATH=$PATH:$MONGO_PATH/bin

Where is the settings file of mongodb located which stores all this information.

Body:
From the mongo shell you can find the path for data, log and config using:

   db.serverCmdLineOpts()


问:
include based on route Laravel
How do I include a file based on which route "category" is used with blade with Laravel? I'm basically trying to do this in the sub nav part of my view template:

app/views/layouts/default.blade.php

```<code>@if (Route::resource() == 'tasks')
    @include('navs.task')
@elseif (Route::resource() == 'projs')
    @include('navs.proj')
@elseif (Route::resource() == 'miscs')
    @include('navs.misc')
@else
    @include('navs.info')
@endif
</code>```

but that throws the error "Undefined class constant 'resource' "

答:
Very late, but i think using Request::is is an easier way.

```<code>@if (Route::is('tasks'))
   @include('navs.task')
@elseif (Route::is('projs'))
   @include('nav.proj')
@elseif (Route::is('miscs'))
    @include('nav.misc')
@else
    @include('nav.info')
@endif
</code>```

Also this is alot of if else's use Switch case instead.

Title: include based on route Laravel

Body:
How do I include a file based on which route "category" is used with blade with Laravel? I'm basically trying to do this in the sub nav part of my view template:

app/views/layouts/default.blade.php

@if (Route::resource() == 'tasks')
    @include('navs.task')
@elseif (Route::resource() == 'projs')
    @include('navs.proj')
@elseif (Route::resource() == 'miscs')
    @include('navs.misc')
@else
    @include('navs.info')
@endif

but that throws the error "Undefined class constant 'resource' "

Body:
Very late, but i think using Request::is is an easier way.

@if (Route::is('tasks'))
   @include('navs.task')
@elseif (Route::is('projs'))
   @include('nav.proj')
@elseif (Route::is('miscs'))
    @include('nav.misc')
@else
    @include('nav.info')
@endif

Also this is alot of if else's use Switch case instead.


问:
Put form to the left and right side in card class with bootstrap 4
I want to label and select element in the same line and i successed with form-inline. And then i want to put them to the left and right side with text-left and text-right like this code but do not work.

Can you help me guys? Thank you

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

 Our Products

                <form class="form-inline">

                    Showing
                    <select class="form-control">
                      <option>10</option>
                      <option>25</option>
                      <option>50</option>
                      <option>100</option>
                    </select>
                      entries

                </form>

                <form class="form-inline">

                    Search:
                    <input type="search" class="form-control">

                </form>

                #
                Name
                Category
                Company
                Date

                  1
                  Cocomax
                  Minuman
                  PT. Asiatic Agro Industry
                  Published, 2017/08/12

```

答:
Use pull-right on the form. See also Left align and right align within div in Bootstrap

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

 Our Products

                <form class="form-inline">

                    Showing
                    <select class="form-control">
                      <option>10</option>
                      <option>25</option>
                      <option>50</option>
                      <option>100</option>
                    </select>
                      entries

                </form>

                <form class="form-inline pull-right">

                    Search:
                    <input type="search" class="form-control">

                </form>

                #
                Name
                Category
                Company
                Date

                  1
                  Cocomax
                  Minuman
                  PT. Asiatic Agro Industry
                  Published, 2017/08/12

```

Body:
Use pull-right on the form. See also Left align and right align within div in Bootstrap

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<!-- Our Products Table -->
      <div class="col-md-8">
        <div class="card">
          <div class="card-header text-secondary">
            <h6><i class="fa fa-table"></i> Our Products</h6>
          </div>
          <div class="card-body">
            <div class="row mb-2 text-muted">
              <div class="col-md-6 text-left">
                <form class="form-inline">
                  <div class="form-group">
                    <label for="showRows">Showing &nbsp;</label>
                    <select class="form-control">
                      <option>10</option>
                      <option>25</option>
                      <option>50</option>
                      <option>100</option>
                    </select>
                    <label>&nbsp; entries</label>
                  </div>
                </form>
              </div>
              <div class="col-md-6 text-right">
                <form class="form-inline pull-right">
                  <div class="form-group">
                    <label for="showSearch">Search: &nbsp;</label>
                    <input type="search" class="form-control">
                  </div>
                </form>
              </div>
            </div>
            <table class="table table-bordered table-sm border border-top-0">
              <thead class="bg-light text-secondary">
                <th>#</th>
                <th>Name</th>
                <th>Category</th>
                <th>Company</th>
                <th>Date</th>
              </thead>
              <tbody>
                <tr>
                  <td>1</td>
                  <td>Cocomax</td>
                  <td>Minuman</td>
                  <td>PT. Asiatic Agro Industry</td>
                  <td>Published, 2017/08/12</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="card-footer text-muted">

          </div>
        </div>
      </div>
      <!-- End our products table -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>


问:
Insert Selected data in database
Basically I want to insert a Foreign key acc_id in patient_info table from account_info table.

I have managed to retrieve the data from my database. Now I want to insert it in another table as Foreign key. I have following code :

```<code> try {
    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
        while($row  = $stmt->fetch(PDO::FETCH_OBJ))
        {
            // Assign each row of data to associative array
                $data[] = $row;
        }

        // Return data as JSON
            echo json_encode($data);
 }
</code>```

How can I insert the value in the table?
this is the full code :

```<code><?php
header('Access-Control-Allow-Origin: *');

 // Define database connection parameters
 $hn      = 'localhost';
 $un      = 'root';
 $pwd     = '';
 $db      = 'ringabell';
 $cs      = 'utf8';

 // Set up the PDO parameters
 $dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
 $opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);

 // Retrieve specific parameter from supplied URL
 $key  = strip_tags($_REQUEST['key']);
$data = array();

 switch($key)

{
   // Add a new record to the technologies table
  case "create":

     // Sanitise URL supplied value
     $acc_id                = filter_var($_REQUEST['acc_id'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_fname               = filter_var($_REQUEST['p_fname'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_lname               = filter_var($_REQUEST['p_lname'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_gender              = filter_var($_REQUEST['p_gender'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_condition           = filter_var($_REQUEST['p_condition'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_emergencycontact    = filter_var($_REQUEST['p_emergencycontact'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_birthdate           = filter_var($_REQUEST['p_birthdate'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);

try{

    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
    while($row  = $stmt->fetch(PDO::FETCH_OBJ))
        {
            // Assign each row of data to associative array
                $data[] = $row;
        }

        // Return data as JSON
            echo json_encode($data);

    $sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
                            VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";

        $stmt    = $pdo->prepare($sql);

        $stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
        $stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
        $stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
        $stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
        $stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
        $stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
        $stmt->bindParam(':acc_id', $acc_id, PDO::PARAM_STR);

        $stmt->execute();

         echo json_encode(array('message' => 'Congratulations the record was added to the database'));

}
     // Catch any errors in running the prepared statement
     catch(PDOException $e)
     {
        echo $e->getMessage();
     }

 break;
}
?>
</code>```

I am getting this error:

```<code>ERROR SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
</code>```

I am getting the error here which links back to the php file:

```<code>load()
{
  this.http.get('http://localhost:10080/ionic/patients.php')
  .map(res => res.json())
  .subscribe(data =>
  {
     this.items = data;
  });
}
</code>```

Solution: insert slected data as Foreign key and SQLSTATE[23000]: Integrity constraint violation: 1048

答:
I'm pretty sure you could improve your code by removing your while loop and instead go like :

```<code>$data = $stmt->fetchAll(PDO::FETCH_OBJ);
</code>```

Are you sure you're getting expected JSON (tried any var_dump of $data before printing it ?) ?

Isn't it just a simple problem with JavaScript ? Have you tried to use the data you're supposed to get in your JavaScript part ?

It might be a problem of setting headers inside your XMLHttpRequest, and JavaScript doesn't care and give you the JSON anyway...

Now obvious questions :

I can't see where you connect to your database. Are you connected ?

You're trying to insert an ID, does MySQL allow you to INSERT auto increment value ? (in which case, isn't acc_id an Int ?)

You're sending values through $_REQUEST, are you sure you're getting anything through $_REQUEST (btw, check $_GET and $_POST)

I hope it helps

Title: Insert Selected data in database

Body:
Basically I want to insert a Foreign key acc_id in patient_info table from account_info table.

I have managed to retrieve the data from my database. Now I want to insert it in another table as Foreign key. I have following code :

 try {
    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
        while($row  = $stmt->fetch(PDO::FETCH_OBJ))
        {
            // Assign each row of data to associative array
                $data[] = $row;
        }

        // Return data as JSON
            echo json_encode($data);
 }

How can I insert the value in the table?
this is the full code :

<?php
header('Access-Control-Allow-Origin: *');

 // Define database connection parameters
 $hn      = 'localhost';
 $un      = 'root';
 $pwd     = '';
 $db      = 'ringabell';
 $cs      = 'utf8';

 // Set up the PDO parameters
 $dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
 $opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);

 // Retrieve specific parameter from supplied URL
 $key  = strip_tags($_REQUEST['key']);
$data = array();

 switch($key)

{
   // Add a new record to the technologies table
  case "create":

     // Sanitise URL supplied value
     $acc_id                = filter_var($_REQUEST['acc_id'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_fname               = filter_var($_REQUEST['p_fname'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_lname               = filter_var($_REQUEST['p_lname'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_gender              = filter_var($_REQUEST['p_gender'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_condition           = filter_var($_REQUEST['p_condition'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_emergencycontact    = filter_var($_REQUEST['p_emergencycontact'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
     $p_birthdate           = filter_var($_REQUEST['p_birthdate'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);

try{

    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
    while($row  = $stmt->fetch(PDO::FETCH_OBJ))
        {
            // Assign each row of data to associative array
                $data[] = $row;
        }

        // Return data as JSON
            echo json_encode($data);

    $sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
                            VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";

        $stmt    = $pdo->prepare($sql);

        $stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
        $stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
        $stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
        $stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
        $stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
        $stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
        $stmt->bindParam(':acc_id', $acc_id, PDO::PARAM_STR);

        $stmt->execute();

         echo json_encode(array('message' => 'Congratulations the record was added to the database'));

}
     // Catch any errors in running the prepared statement
     catch(PDOException $e)
     {
        echo $e->getMessage();
     }

 break;
}
?>

I am getting this error:

ERROR SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)

I am getting the error here which links back to the php file:

load()
{
  this.http.get('http://localhost:10080/ionic/patients.php')
  .map(res => res.json())
  .subscribe(data =>
  {
     this.items = data;
  });
}

Solution: insert slected data as Foreign key and SQLSTATE[23000]: Integrity constraint violation: 1048

Body:
I'm pretty sure you could improve your code by removing your while loop and instead go like :

$data = $stmt->fetchAll(PDO::FETCH_OBJ);

Are you sure you're getting expected JSON (tried any var_dump of $data before printing it ?) ?

Isn't it just a simple problem with JavaScript ? Have you tried to use the data you're supposed to get in your JavaScript part ?

It might be a problem of setting headers inside your XMLHttpRequest, and JavaScript doesn't care and give you the JSON anyway...

Now obvious questions :

I can't see where you connect to your database. Are you connected ?

You're trying to insert an ID, does MySQL allow you to INSERT auto increment value ? (in which case, isn't acc_id an Int ?)

You're sending values through $_REQUEST, are you sure you're getting anything through $_REQUEST (btw, check $_GET and $_POST)

I hope it helps


问:
VS Task Runner Explorer - Node Sass could not find a binding
When opening the Visual Studio Task Runner Explorer, the gulpfile.js fails to load and this error is emitted in the Output window.

```<code>Failed to run "C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\Gulpfile.js"...
cmd.exe /c gulp --tasks-simple
C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\node-sass\lib\binding.js:15
      throw new Error(errors.missingBinary());
      ^
Error: Missing binding C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\node-sass\vendor\win32-ia32-47\binding.node
Node Sass could not find a binding for your current environment: Windows 32-bit with Node.js 5.x
Found bindings for the following environments:
  - Windows 64-bit with Node.js 6.x
This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to build the binding for your current environment.
    at module.exports (C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\node-sass\lib\binding.js:15:13)
    at Object.<anonymous> (C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\node-sass\lib\index.js:14:35)
    at Module._compile (module.js:397:26)
    at Object.Module._extensions..js (module.js:404:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\gulp-sass\index.js:187:21)
    at Module._compile (module.js:397:26)
</code>```

Running gulp runs the tasks and my SASS compiles fine.

I tried reinstalling node, I have also ensured only one npm runnable is in the Windows path and I've deleted the node_modules folder and run npm install a few times, also tried npm rebuild node-sass.

All these millions of cool new front-end tools and libraries seem to be hugely broadening the surface of "things to go wrong", not very productive at all compared to previous projects.

Luke

答:
For Visual Studio 2017 the category name is different. Instead of External Web Tools it is now called "Web Package management"

Visual Studio 2017 External Tools npm Not working

Body:
When opening the Visual Studio Task Runner Explorer, the gulpfile.js fails to load and this error is emitted in the Output window.

Failed to run "C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\Gulpfile.js"...
cmd.exe /c gulp --tasks-simple
C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\node-sass\lib\binding.js:15
      throw new Error(errors.missingBinary());
      ^
Error: Missing binding C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\node-sass\vendor\win32-ia32-47\binding.node
Node Sass could not find a binding for your current environment: Windows 32-bit with Node.js 5.x
Found bindings for the following environments:
  - Windows 64-bit with Node.js 6.x
This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to build the binding for your current environment.
    at module.exports (C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\node-sass\lib\binding.js:15:13)
    at Object.<anonymous> (C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\node-sass\lib\index.js:14:35)
    at Module._compile (module.js:397:26)
    at Object.Module._extensions..js (module.js:404:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\DATA\Git\MyApp\MyBiz.MyApp\MyBiz.MyApp.WebsiteCore\node_modules\gulp-sass\index.js:187:21)
    at Module._compile (module.js:397:26)

Running gulp runs the tasks and my SASS compiles fine.

I tried reinstalling node, I have also ensured only one npm runnable is in the Windows path and I've deleted the node_modules folder and run npm install a few times, also tried npm rebuild node-sass.

All these millions of cool new front-end tools and libraries seem to be hugely broadening the surface of "things to go wrong", not very productive at all compared to previous projects.

Luke


问:
Wait for CSS property to change before asserting the change
I'm using python webdriver and I'm trying to make the system wait until the border colour of a password field has changed after a submit button has been clicked. The colour fades from one to the other and I can get the desired result using this: -

```<code>password_border_colour_after_click = ""
count = 0
while password_border_colour_after_click != "rgba(169, 68, 66, 1)":
    password_border_colour_after_click = self.driver.find_element_by_name("password").value_of_css_property('border-bottom-color')
    time.sleep(0.1)
    count += 1
    if password_border_colour_after_click == "rgba(169, 68, 66, 1)":
        break
    elif count > 50:
        break
assert password_border_colour_after_click == "rgba(169, 68, 66, 1)"
</code>```

It feels a bit clunky and is probably awful code so I was thinking there must be a way to package it all up in a wait command, but I can't get the syntax right.

Is it possible?

答:
I don't know how to do this in Python since I'm not that familiar with the language, but in C# you can create delegate functions that act like custom ExpectedConditions which you can use with the WebDriverWait class.

The WebDriverWait class waits n amount of seconds before throwing an exception.

Example (psuedo) code in C#:

```<code>public static class CustomExpectedConditions
{
    public static Func<IWebDriver, bool> ElementAttributeContains(By locator, string attributeName, string expectedValue)
    {
        return (driver) => driver.FindElement(locator).GetAttribute(attributeName).Contains(expectedValue);
    }
}
</code>```

This allows you to use it like:

```<code>var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(CustomExpectedConditions.ElementAttributeContains(By.Name("password"), "style", "rgba(169, 68, 66, 1)"));
</code>```

I found this sample code for custom expected conditions in Python:

```<code>class element_has_css_class(object):
"""An expectation for checking that an element has a particular css class.

locator - used to find the element
returns the WebElement once it has the particular css class
"""
def __init__(self, locator, css_class):
  self.locator = locator
  self.css_class = css_class

def __call__(self, driver):
  element = driver.find_element(*self.locator)   # Finding the referenced element
  if self.css_class in element.get_attribute("class"):
      return element
  else:
      return False

# Wait until an element with id='myNewInput' has class 'myCSSClass'
wait = WebDriverWait(driver, 10)
element = wait.until(element_has_css_class((By.ID, 'myNewInput'), "myCSSClass"))
</code>```

Hope this will get you started in the right direction

Body:
I'm using python webdriver and I'm trying to make the system wait until the border colour of a password field has changed after a submit button has been clicked. The colour fades from one to the other and I can get the desired result using this: -

password_border_colour_after_click = ""
count = 0
while password_border_colour_after_click != "rgba(169, 68, 66, 1)":
    password_border_colour_after_click = self.driver.find_element_by_name("password").value_of_css_property('border-bottom-color')
    time.sleep(0.1)
    count += 1
    if password_border_colour_after_click == "rgba(169, 68, 66, 1)":
        break
    elif count > 50:
        break
assert password_border_colour_after_click == "rgba(169, 68, 66, 1)"

It feels a bit clunky and is probably awful code so I was thinking there must be a way to package it all up in a wait command, but I can't get the syntax right.

Is it possible?

Body:
I don't know how to do this in Python since I'm not that familiar with the language, but in C# you can create delegate functions that act like custom ExpectedConditions which you can use with the WebDriverWait class.

The WebDriverWait class waits n amount of seconds before throwing an exception.

Example (psuedo) code in C#:

public static class CustomExpectedConditions
{
    public static Func<IWebDriver, bool> ElementAttributeContains(By locator, string attributeName, string expectedValue)
    {
        return (driver) => driver.FindElement(locator).GetAttribute(attributeName).Contains(expectedValue);
    }
}

This allows you to use it like:

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(CustomExpectedConditions.ElementAttributeContains(By.Name("password"), "style", "rgba(169, 68, 66, 1)"));

I found this sample code for custom expected conditions in Python:

class element_has_css_class(object):
"""An expectation for checking that an element has a particular css class.

locator - used to find the element
returns the WebElement once it has the particular css class
"""
def __init__(self, locator, css_class):
  self.locator = locator
  self.css_class = css_class

def __call__(self, driver):
  element = driver.find_element(*self.locator)   # Finding the referenced element
  if self.css_class in element.get_attribute("class"):
      return element
  else:
      return False

# Wait until an element with id='myNewInput' has class 'myCSSClass'
wait = WebDriverWait(driver, 10)
element = wait.until(element_has_css_class((By.ID, 'myNewInput'), "myCSSClass"))

Hope this will get you started in the right direction


问:
hive reach max worker and cannot connect to hiveserver2
when i use beeline connect to hiveserver2 ,the err msg is like this.
I have connect to the hiveserver2 before.
This error is show after i connect to hiveserver2 some times.
and i can connect use jdbc:hive2://

```<code>beeline> !connect jdbc:hive2://master:10000
</code>```

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/local/hive/lib/log4j-slf4j-impl-2.4.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/local/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
Connecting to jdbc:hive2://master:10000
Enter username for jdbc:hive2://master:10000:
Enter password for jdbc:hive2://master:10000:
17/11/14 22:09:36 [main]: WARN jdbc.HiveConnection: Failed to connect to master:10000
Unexpected end of file when reading from HS2 server. The root cause might be too many concurrent connections. Please ask the administrator to check the number of active connections, and adjust hive.server2.thrift.max.worker.threads if applicable.
Error: Could not open client transport with JDBC Uri: jdbc:hive2://master:10000: null (state=08S01,code=0)

hive-site.xml is set like this

```<code><property>
 39         <name>hive.server2.thrift.min.worker.threads</name>
 40         <value>5</value>
 41     </property>
 42     <property>
 43         <name>hive.server2.thrift.max.worker.threads</name>
 44         <value>500</value>
 45     </property>
 46     <property>
 47         <name>hive.server2.thrift.bind.host</name>
 48         <value>master</value>
 49     </property>
 50     <property>
 51         <name>hive.server2.thrift.port</name>
 52         <value>10000</value>
 53     </property>
</code>```

i have check the netstat that 10000 port is listening.
even if i restart the hadoop server and hiveserver2,the problem is not solved.
how can i know how many connection is active or can i clear the thread pool?
The active will not be closed when i shutdown the hiveserver and hadoop and linux system?

答:
It works fine on my environment:

```<code>$ netstat -an | grep 10000
tcp4       0      0  *.10000                *.*                    LISTEN
</code>```

hive-site.xml

set nosasl for not using SASLTransport

```<code><property>
    <name>hive.server2.authentication</name>
    <value>NOSASL</value> <!-- default NONE is for SASLTranspor
</property>

 <property>
    <name>hive.server2.enable.doAs</name>
    <value>false</value> <!-- Execute query as hiveserver2 proc
</property>
</code>```

and

```<code>!connect jdbc:hive2://localhost:10000/default;auth=noSasl hive password org.apache.hive.jdbc.HiveDriver
</code>```

REFERENCES

This is Japanese blog but it would be helpful: http://tagomoris.hatenablog.com/entry/20131226/1388044783

Body:
when i use beeline connect to hiveserver2 ,the err msg is like this.
I have connect to the hiveserver2 before.
This error is show after i connect to hiveserver2 some times.
and i can connect use jdbc:hive2://

beeline> !connect jdbc:hive2://master:10000

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/local/hive/lib/log4j-slf4j-impl-2.4.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/local/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
Connecting to jdbc:hive2://master:10000
Enter username for jdbc:hive2://master:10000:
Enter password for jdbc:hive2://master:10000:
17/11/14 22:09:36 [main]: WARN jdbc.HiveConnection: Failed to connect to master:10000
Unexpected end of file when reading from HS2 server. The root cause might be too many concurrent connections. Please ask the administrator to check the number of active connections, and adjust hive.server2.thrift.max.worker.threads if applicable.
Error: Could not open client transport with JDBC Uri: jdbc:hive2://master:10000: null (state=08S01,code=0)

hive-site.xml is set like this

<property>
 39         <name>hive.server2.thrift.min.worker.threads</name>
 40         <value>5</value>
 41     </property>
 42     <property>
 43         <name>hive.server2.thrift.max.worker.threads</name>
 44         <value>500</value>
 45     </property>
 46     <property>
 47         <name>hive.server2.thrift.bind.host</name>
 48         <value>master</value>
 49     </property>
 50     <property>
 51         <name>hive.server2.thrift.port</name>
 52         <value>10000</value>
 53     </property>

i have check the netstat that 10000 port is listening.
even if i restart the hadoop server and hiveserver2,the problem is not solved.
how can i know how many connection is active or can i clear the thread pool?
The active will not be closed when i shutdown the hiveserver and hadoop and linux system?

Body:
It works fine on my environment:

$ netstat -an | grep 10000
tcp4       0      0  *.10000                *.*                    LISTEN

hive-site.xml

set nosasl for not using SASLTransport

<property>
    <name>hive.server2.authentication</name>
    <value>NOSASL</value> <!-- default NONE is for SASLTranspor
</property>

 <property>
    <name>hive.server2.enable.doAs</name>
    <value>false</value> <!-- Execute query as hiveserver2 proc
</property>

and

!connect jdbc:hive2://localhost:10000/default;auth=noSasl hive password org.apache.hive.jdbc.HiveDriver

REFERENCES

This is Japanese blog but it would be helpful: http://tagomoris.hatenablog.com/entry/20131226/1388044783


问:
Ajax fails when sending a data object to the NodeJs server
when pressing a button this code gets executed

```<code>function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}
</code>```

and the server is listening on this

```<code>app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});
</code>```

Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.

Even when writing res.send("Success"); the client will log "Error". What am I missing?

Update:
I installed the body parser middleware and use this code now

my app.js

```<code>const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});
</code>```

my route

```<code>module.exports = function (app) {

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};
</code>```

and my client function

```<code>function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}
</code>```

And when executing the Ajax call the client still runs into .fail()

答:
Client request is : </p>

```<code>function submitData() {
        $.ajax({
            type: 'POST',
            url: '/questionnaire/submit', // listen to a route
            dataType: "json",
            data: {
                satisfactory: "house",
                improvement: "bla",
                rating: "this is a text"
            }
        }).done(function () {
            $(location).attr('href', '/sendOff'); // redirect to another route
        }).fail(function () {
            console.log("Error");
        });
    }
</code>```

<p>and the server is listening on this Using bodyParser middleware in your node backend
: </p>

```<code>app.post('/questionnaire/submit', function (req, res) {
    var data = req.body; // Get the data object from the Ajax call

    console.log(data);

    res.end(); // Send nothing back
});
</code>```

Body:
when pressing a button this code gets executed

function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}

and the server is listening on this

app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});

Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.

Even when writing res.send("Success"); the client will log "Error". What am I missing?

Update:
I installed the body parser middleware and use this code now

my app.js

const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});

my route

module.exports = function (app) {

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};

and my client function

function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

And when executing the Ajax call the client still runs into .fail()

Body:
Client request is :

function submitData() {
        $.ajax({
            type: 'POST',
            url: '/questionnaire/submit', // listen to a route
            dataType: "json",
            data: {
                satisfactory: "house",
                improvement: "bla",
                rating: "this is a text"
            }
        }).done(function () {
            $(location).attr('href', '/sendOff'); // redirect to another route
        }).fail(function () {
            console.log("Error");
        });
    }

and the server is listening on this Using bodyParser middleware in your node backend
:

app.post('/questionnaire/submit', function (req, res) {
    var data = req.body; // Get the data object from the Ajax call

    console.log(data);

    res.end(); // Send nothing back
});


问:
How can I implement Text which will support styles object in this reusable component?

I've found this small library on github. I would like to make some changes on it. How can I add a text that supports style object inside the radio button (this component)? So  when use it on the other screens can implement any text inside it and change the default styles. At the moment it doesn't include even default text implementation. Here is the code.

import React, { Component } from 'react'
import { StyleSheet, TouchableOpacity } from 'react-native'
import { View } from 'react-native-animatable'
import PropTypes from 'prop-types'

const DEFAULT_SIZE_MULTIPLIER = 0.7
const DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER = 0.2

export default class RadioButton extends Component {
  static propTypes = {
    size: PropTypes.number,
    innerColor: PropTypes.string,
    outerColor: PropTypes.string,
    isSelected: PropTypes.bool,
    onPress: PropTypes.func
  }

  static defaultProps = {
    size: 35,
    innerColor: 'dodgerblue',
    outerColor: 'dodgerblue',
    isSelected: false,
    onPress: () => null
  }

  render () {
    const { size, innerColor, outerColor, isSelected, onPress } = this.props
    const outerStyle = {
      borderColor: outerColor,
      width: size + size * DEFAULT_SIZE_MULTIPLIER,
      height: size + size * DEFAULT_SIZE_MULTIPLIER,
      borderRadius: (size + size * DEFAULT_SIZE_MULTIPLIER) / 2,
      borderWidth: size * DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER
    }

    const innerStyle = {
      width: size,
      height: size,
      borderRadius: size / 2,
      backgroundColor: innerColor
    }

    return (
      <TouchableOpacity style={[styles.radio, outerStyle]} onPress={onPress}>
        {isSelected ? <View style={innerStyle} {...this.props} /> : null}
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  radio: {
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center'
  }
})
```

How can I implement that new feature that was described in the above?

答:
This shows how to make it works step by step.

firstly, code:

/// 1) Make a composition component
export default class RadioButtonText extends Component {
  static propTypes = {
    /// 2) Make all RadioButton props as this classes' props
    ...RadioButton.propTypes,

    /// 3) Two new props, one for string of text, one for text style.
    text: PropTypes.string,
    textStyle: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.number,
    ]),
  }

  static defaultProps = {
      ...RadioButton.defaultProps,
  }

  render() {
    return (
      <View>

        <RadioButton {...this.props} />

        <Text style={this.props.textStyle}>{this.props.text}</Text>
      </View>
    )
  }
}
```

<h2>Steps:</h2>

<ol>
<li>Make a composition component.</li>
</ol>

<p>Make a new component except of modify open source, for your easier control and understand. The base idea is: Left side as <code><RadioButton /></code>, Right side as <code><Text /></code>, everything looks good.</p>

<ol start="2">
<li>Make all <code><RadioButton /></code> props as this classes' props</li>
</ol>

<p>So we can pass-in props from new component <code><RadioButtonText /></code> into <code><RadioButton /></code>, for every props such as <code>size</code>, <code>innerColor</code>, <code>outerColor</code>.</p>

<ol start="3">
<li>Two new props, one for string of text, one for text style.</li>
</ol>

<p>That is all you need for your requirement. Although these two props will pass into <code><RadioButton /></code> too, it doesn't matter at all (no effect).</p>

<ol start="4">
<li>Pass every props into <code><RadioButton /></code></li>
<li>Apply text string, and style</li>
</ol>

<hr>

<h2>Usage:</h2>

<pre class="lang-js prettyprint-override"><code><RadioButtonText
  {/* props for RadioButton */}
  size={10}
  isSelected={false}
  {/* props for RadioButtonText */}
  text='Radio Text!'
  textStyle={{fontSize: 18}}
/>
</code>```

Body:
I've found this small library on github. I would like to make some changes on it. How can I add a text that supports style object inside the radio button (this component)? So  when use it on the other screens can implement any text inside it and change the default styles. At the moment it doesn't include even default text implementation. Here is the code.

import React, { Component } from 'react'
import { StyleSheet, TouchableOpacity } from 'react-native'
import { View } from 'react-native-animatable'
import PropTypes from 'prop-types'

const DEFAULT_SIZE_MULTIPLIER = 0.7
const DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER = 0.2

export default class RadioButton extends Component {
  static propTypes = {
    size: PropTypes.number,
    innerColor: PropTypes.string,
    outerColor: PropTypes.string,
    isSelected: PropTypes.bool,
    onPress: PropTypes.func
  }

  static defaultProps = {
    size: 35,
    innerColor: 'dodgerblue',
    outerColor: 'dodgerblue',
    isSelected: false,
    onPress: () => null
  }

  render () {
    const { size, innerColor, outerColor, isSelected, onPress } = this.props
    const outerStyle = {
      borderColor: outerColor,
      width: size + size * DEFAULT_SIZE_MULTIPLIER,
      height: size + size * DEFAULT_SIZE_MULTIPLIER,
      borderRadius: (size + size * DEFAULT_SIZE_MULTIPLIER) / 2,
      borderWidth: size * DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER
    }

    const innerStyle = {
      width: size,
      height: size,
      borderRadius: size / 2,
      backgroundColor: innerColor
    }

    return (
      <TouchableOpacity style={[styles.radio, outerStyle]} onPress={onPress}>
        {isSelected ? <View style={innerStyle} {...this.props} /> : null}
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  radio: {
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center'
  }
})

How can I implement that new feature that was described in the above?

Body:
This shows how to make it works step by step.

firstly, code:

/// 1) Make a composition component
export default class RadioButtonText extends Component {
  static propTypes = {
    /// 2) Make all RadioButton props as this classes' props
    ...RadioButton.propTypes,

    /// 3) Two new props, one for string of text, one for text style.
    text: PropTypes.string,
    textStyle: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.number,
    ]),
  }

  static defaultProps = {
      ...RadioButton.defaultProps,
  }

  render() {
    return (
      <View>
        <!-- 4) Pass every props into RadioButton -->
        <RadioButton {...this.props} />
        <!-- 5) Apply text string, and style -->
        <Text style={this.props.textStyle}>{this.props.text}</Text>
      </View>
    )
  }
}

Steps:

Make a composition component.

Make a new component except of modify open source, for your easier control and understand. The base idea is: Left side as <RadioButton />, Right side as <Text />, everything looks good.

Make all <RadioButton /> props as this classes' props

So we can pass-in props from new component <RadioButtonText /> into <RadioButton />, for every props such as size, innerColor, outerColor.

Two new props, one for string of text, one for text style.

That is all you need for your requirement. Although these two props will pass into <RadioButton /> too, it doesn't matter at all (no effect).

Pass every props into <RadioButton />

Apply text string, and style

Usage:

<RadioButtonText
  {/* props for RadioButton */}
  size={10}
  isSelected={false}
  {/* props for RadioButtonText */}
  text='Radio Text!'
  textStyle={{fontSize: 18}}
/>


问:
How do CDNs work?
I am new to webdev and would like to understand how CDNs work?

Specifically how do CDNs achieve performance in retrieving the content? Is the content stored on disk, in a database in binary format, or on disk but the location stored in the database?

How is the data kept in sync? Does the end user only push new/updated content to one location and the CDN takes care of synchronizing the content?

When is it wise to use a CDN and are there any other alternatives aside from storing the data on disk?

答:
A content delivery network or content distribution network (CDN) is a globally distributed network of proxy servers deployed in multiple data centers.

CDNs are very useful for a multitude of reasons. For website owners who have visitors in multiple geographic locations, content will be delivered faster to these users as there is less distance to travel. CDN users also benefit from the ability to easily scale up and down much more easily due to traffic spikes. On average, 80% of a website consist of static resources therefore when using a CDN, there is much less load on the origin server.

Source

Title: How do CDNs work?


问:
Lifetime of the pointers
I was watching the video of Symbio C++ Seminar with Herb Sutter - (Thrill of a) Lifetime 20.6.2016,
https://www.youtube.com/watch?v=7b75rcHg7z0&t=917s

The following code  has been written from the video 11::24.
p1, p2, and p3 pointers must be invalidated when the scope goes out.
It must give error when trying to dereference the pointers.

I'm using online https://wandbox.org/ environment. Both gcc and clang is giving the following results. Which must be wrong.

Can someone check the same code on Visual Stdio.

Thanks

```<code>#include <iostream>
using namespace std;
#include <vector>
#include <memory>
#include <cstdio>
#include <cassert>
#include <string>
#include <iterator>
#include <algorithm>
#include <array>

int* p1 = nullptr; int* p2 = nullptr; int* p3 = nullptr;

int main() {
    {
        int i = 1;
        struct MyStruct { char a; int i; char c;} s = {'a', 2, 'c'};
        array<int,7> arr = {0,1,2,3,4,5,6};
        p1 = &i;
        p2 = &s.i;
        p3 = & arr[2];
        *p1 =*p2= *p3 = 42;
        cout << *p1 << *p2 << *p3 << endl;
    }
    *p1 = 1; // This must give error
    *p2 = 2;
    *p3 = 3;
    cout << *p1 << *p2 << *p3 << endl;
}
</code>```

This is the output:

```<code>424242
123
</code>```

答: Visual C++17 also fails to detect the undefined behavior, and gives the same output.</p>

Title: Lifetime of the pointers

Body:
I was watching the video of Symbio C++ Seminar with Herb Sutter - (Thrill of a) Lifetime 20.6.2016,
https://www.youtube.com/watch?v=7b75rcHg7z0&t=917s

The following code  has been written from the video 11::24.
p1, p2, and p3 pointers must be invalidated when the scope goes out.
It must give error when trying to dereference the pointers.

I'm using online https://wandbox.org/ environment. Both gcc and clang is giving the following results. Which must be wrong.

Can someone check the same code on Visual Stdio.

Thanks

#include <iostream>
using namespace std;
#include <vector>
#include <memory>
#include <cstdio>
#include <cassert>
#include <string>
#include <iterator>
#include <algorithm>
#include <array>

int* p1 = nullptr; int* p2 = nullptr; int* p3 = nullptr;

int main() {
    {
        int i = 1;
        struct MyStruct { char a; int i; char c;} s = {'a', 2, 'c'};
        array<int,7> arr = {0,1,2,3,4,5,6};
        p1 = &i;
        p2 = &s.i;
        p3 = & arr[2];
        *p1 =*p2= *p3 = 42;
        cout << *p1 << *p2 << *p3 << endl;
    }
    *p1 = 1; // This must give error
    *p2 = 2;
    *p3 = 3;
    cout << *p1 << *p2 << *p3 << endl;
}

This is the output:

424242
123


问:
Groovy script is working in script console but not in build
I have a groovy script which works in the script console but not in my pipeline when I call it as groovy script (it's coming from my shared library):

```<code>#!/usr/bin/env groovy
import jenkins.model.*
import hudson.model.*
import jenkins.*
import hudson.*
import java.lang.*

def call(String jobname, String build_string) {
  echo "Hello, ${jobname}."
  echo "Hello, ${build_string}."

  //Jenkins.instance.getAllItems(AbstractItem.class).each { println(it.fullName) };

  def job = Jenkins.instance.items.find { it.name == 'test' }
  echo "Hello, ${job}."

    for (build in job.builds) {
        def log = build.log
        if (log.contains('hey')) {
            println "${job.name}: ${build.id}"
        }
    }
}
</code>```

I use some hardcoded variables to be sure, I have a job named 'test' and it contains ('hey') in the output. Then the jobname and buildid is printed and this is working fine in the script console.

But when I call it in the pipeline with: filterOutput env.JOB_NAME , 'a' I get:

```<code>[test] Running shell script
+ echo hey
hey
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (getOutput)
[Pipeline] echo
Hello, test.
[Pipeline] echo
Hello, a.
[Pipeline] echo
Hello, false.
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: builds for class: java.lang.Boolean
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:33)
</code>```

What am I doing wrong? Why is this working in my console and not in my build?

答:
As you see in your prints you have

```<code>.....
[Pipeline] echo
Hello, false.
....
</code>```

and then you try to do

```<code>for (build in job.builds) {
    def log = build.log
    if (log.contains('hey')) {
        println "${job.name}: ${build.id}"
    }
}
</code>```

where your job = false, so you try to do false.builds, that doesn't exists.

Proof job before for and you should be ok.

Body:
I have a groovy script which works in the script console but not in my pipeline when I call it as groovy script (it's coming from my shared library):

#!/usr/bin/env groovy
import jenkins.model.*
import hudson.model.*
import jenkins.*
import hudson.*
import java.lang.*

def call(String jobname, String build_string) {
  echo "Hello, ${jobname}."
  echo "Hello, ${build_string}."

  //Jenkins.instance.getAllItems(AbstractItem.class).each { println(it.fullName) };

  def job = Jenkins.instance.items.find { it.name == 'test' }
  echo "Hello, ${job}."

    for (build in job.builds) {
        def log = build.log
        if (log.contains('hey')) {
            println "${job.name}: ${build.id}"
        }
    }
}

I use some hardcoded variables to be sure, I have a job named 'test' and it contains ('hey') in the output. Then the jobname and buildid is printed and this is working fine in the script console.

But when I call it in the pipeline with: filterOutput env.JOB_NAME , 'a' I get:

[test] Running shell script
+ echo hey
hey
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (getOutput)
[Pipeline] echo
Hello, test.
[Pipeline] echo
Hello, a.
[Pipeline] echo
Hello, false.
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: builds for class: java.lang.Boolean
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:33)

What am I doing wrong? Why is this working in my console and not in my build?

Body:
As you see in your prints you have

.....
[Pipeline] echo
Hello, false.
....

and then you try to do

for (build in job.builds) {
    def log = build.log
    if (log.contains('hey')) {
        println "${job.name}: ${build.id}"
    }
}

where your job = false, so you try to do false.builds, that doesn't exists.

Proof job before for and you should be ok.


问:
Mysql query with and conditions
I've two tables,

table 1

```<code>userid  filter
thiru   1
thiru   2
thiru   3
raja    1
raja    2
</code>```

table 2

```<code>headline    filter1 filter2
test          1       3
test2         1       2
</code>```

If I want to select the users applicable for filters.

when i select test - thiru is applicable ( filter1 and filter2 ) matching

when i select test2 - thiru and raja are applicable ( filter1 and filter2 ) matching.

Basically the filters are with and condition.

Here is the query that i tried:

```<code>select userid
  from table1
 where filter in (select filter1
                    from table2
                   where headline = 'test')
   and filter in (select filter2
                    from table2
                   where headline = 'test');
</code>```

Please give me the query for this.
Thanks in advance.

答:
Found a solution and here is what worked:

```<code>SELECT userid FROM table1
WHERE (filter IN (SELECT filter1 FROM table2 WHERE headline = 'test')
OR filter IN (SELECT filter2 FROM table2 WHERE headline = 'test'));
</code>```

Adding a 'OR' between two queries worked.

Title: Mysql query with and conditions

Body:
I've two tables,

table 1

userid  filter
thiru   1
thiru   2
thiru   3
raja    1
raja    2

table 2

headline    filter1 filter2
test          1       3
test2         1       2

If I want to select the users applicable for filters.

when i select test - thiru is applicable ( filter1 and filter2 ) matching

when i select test2 - thiru and raja are applicable ( filter1 and filter2 ) matching.

Basically the filters are with and condition.

Here is the query that i tried:

select userid
  from table1
 where filter in (select filter1
                    from table2
                   where headline = 'test')
   and filter in (select filter2
                    from table2
                   where headline = 'test');

Please give me the query for this.
Thanks in advance.

Body:
Found a solution and here is what worked:

SELECT userid FROM table1
WHERE (filter IN (SELECT filter1 FROM table2 WHERE headline = 'test')
OR filter IN (SELECT filter2 FROM table2 WHERE headline = 'test'));

Adding a 'OR' between two queries worked.

ContentLicense: CC BY-SA 4.0


问:
Doctrine get single latest row of Detail for each Master
I have QueryBuilder like this

```<code>$query = $this->getEntityManager()
  ->createQueryBuilder()
  ->select('partial master.{id,name}, partial detail.{id,name}')
  ->from('AppBundle:Master', 'master')
  ->leftJoin('master.detail', 'detail')
  ->orderBy('detail.id','DESC')
  ->getQuery();
return $query->getArrayResult();
</code>```

master relation is OneToMany, detail relation is ManyToOne.
I'm trying to get a single row of detail with detail id is higher or lower. What Querybuilder to make this possible?
example I have data like this:

```<code>1.A, 1.B, 1.C, 2.A, 3.A, 3.C
</code>```

I want Result like this below

```<code>1.A, 2.A, 3.A
</code>```

答:
To get the latest detail for each master row you ca use following DQL</p>

```<code>SELECT m,a
FROM AppBundle\Entity\Master m
    LEFT JOIN m.detail a
    LEFT JOIN AppBundle\Entity\Detail b
    WITH a.master = b.master
    AND a.id < b.id
WHERE b.id IS NULL
</code>```

Body:
I have QueryBuilder like this

$query = $this->getEntityManager()
  ->createQueryBuilder()
  ->select('partial master.{id,name}, partial detail.{id,name}')
  ->from('AppBundle:Master', 'master')
  ->leftJoin('master.detail', 'detail')
  ->orderBy('detail.id','DESC')
  ->getQuery();
return $query->getArrayResult();

master relation is OneToMany, detail relation is ManyToOne.
I'm trying to get a single row of detail with detail id is higher or lower. What Querybuilder to make this possible?
example I have data like this:

1.A, 1.B, 1.C, 2.A, 3.A, 3.C

I want Result like this below

1.A, 2.A, 3.A

Body:
To get the latest detail for each master row you ca use following DQL

SELECT m,a
FROM AppBundle\Entity\Master m
    LEFT JOIN m.detail a
    LEFT JOIN AppBundle\Entity\Detail b
    WITH a.master = b.master
    AND a.id < b.id
WHERE b.id IS NULL


问:
Why I get auth::check() null after redirect
my laravel version 5.4.36
PHP Version: 7.0.10
wamp 3

when I login auth::check() return 1 but after I redirect to  other view or controller auth::check() return null I create new project whit lavavel 5.5 but not fix how can fix my problem?
what can i do?

user.php

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'ID','Email','first_name','Last_name' ,'username', 'password','typeofuser',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password',
];
}
</code>```

kernel.php

```<code> class Kernel extends HttpKernel
                {
                /**
                 * The application's global HTTP middleware stack.
                 *
                 * These middleware are run during every request to your application.
                 *
                 * @var array
                 */
                protected $middleware = [

\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
                    \App\Http\Middleware\TrimStrings::class,

\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
                    \Illuminate\Session\Middleware\StartSession::class,
                ];

                /**
                 * The application's route middleware groups.
                 *
                 * @var array
                 */
                protected $middlewareGroups = [
                    'web' => [
                        \App\Http\Middleware\EncryptCookies::class,

            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
                        \Illuminate\Session\Middleware\StartSession::class,
                       //  \Illuminate\Session\Middleware\AuthenticateSession::class,
                        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
                        \App\Http\Middleware\VerifyCsrfToken::class,
                        \Illuminate\Routing\Middleware\SubstituteBindings::class,
                    ],

                    'api' => [
                        'throttle:60,1',
                        'bindings',
                    ],
                ];

                /**
                 * The application's route middleware.
                 *
                 * These middleware may be assigned to groups or used individually.
                 *
                 * @var array
                 */
                protected $routeMiddleware = [
                    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
                    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
                    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
                    'can' => \Illuminate\Auth\Middleware\Authorize::class,
                    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
                    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
                ];
                }
</code>```

part of web.php

```<code>Route::get('/Admin', function () {
   return view('Adminlogin');
});

Route::group(['middleware' => ['web']], function () {
Route::get('/StartExamInfo/{id}', 'ExamController@Info');
Route::post('/Exam', 'ExamController@Start');
Route::post('/result','resultController@Add');

});
</code>```

logincontroller.php

```<code>namespace App\Http\Controllers;

use App\admin;
use App\students;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\hash;
use Validator;
class LoginController extends Controller
{
public function Login(Request $request)
{

    if (Auth::guard('web')->attempt(['username' => $request->username , 'password' => $request->password , 'typeofuser' => 1 ]))
    {
        $admin = new admin();
        $admin->username = $request->username;
        $admin->getuser();
        $user = [$admin->ID,$admin->firstname,$admin->lastname,$admin->email,$admin->phonenumber,$admin->pic,$admin->expirtime];
        return view('Admin_home',['user'=>$user]);
    }
    if (Auth::guard('web')->attempt(['username' => $request->username , 'password' => $request->password , 'typeofuser' => 2 ]))
    {
        $std = new students();
        $std->username = $request->username;
        $std->getuser();
        $user = [$std->ID,$std->firstname,$std->lastname,$std->email,$std->pic,$std->expirtime];
        return view('Student_home',['user'=>$user]);
    }
    else
   return view('AdminLogin');

    //$v = validator::make($request->all());
    //
    //$admin->auth($request->username,$request->password);
}

public function logout()
{
    Auth::logout();
    return view('AdminLogin');
}
}
</code>```

答:
You are trying to access your POSTed data in a wrong way. You should take posted user's entry with $request object. Also, you can authenticate the user with a single auth condition. When the user has authenticated, check its typeofuser field with two simple conditions. Something like this:

```<code>public function Login(Request $request)
    {
        $credential = $request->only(['username', 'password']);
        if (!Auth::attempt($credential))
            return 'Username or Password is incorrect.';

        // Now you can access to authenticated user model with `users` method in request object
        $user = $request->user();
        if($user->typeofuser == 1)
        {
            $admin = new admin();
            $admin->username = $credential['username'];
            $admin->getuser();
            $user = [$admin->ID,$admin->firstname,$admin->lastname,$admin->email,$admin->phonenumber,$admin->pic,$admin->expirtime];
            return view('Admin_home',['user'=>$user]);
        }
        elseif ($user->typeofuser == 2)
        {
            $std = new students();
            $std->username = $credential['username'];
            $std->getuser();
            $user = [$std->ID,$std->firstname,$std->lastname,$std->email,$std->pic,$std->expirtime];
            return view('Student_home',['user'=>$user]);
        }
        else
            return view('AdminLogin');
    }
</code>```

Body:
my laravel version 5.4.36
PHP Version: 7.0.10
wamp 3

when I login auth::check() return 1 but after I redirect to  other view or controller auth::check() return null I create new project whit lavavel 5.5 but not fix how can fix my problem?
what can i do?

user.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'ID','Email','first_name','Last_name' ,'username', 'password','typeofuser',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password',
];
}

kernel.php

 class Kernel extends HttpKernel
                {
                /**
                 * The application's global HTTP middleware stack.
                 *
                 * These middleware are run during every request to your application.
                 *
                 * @var array
                 */
                protected $middleware = [

\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
                    \App\Http\Middleware\TrimStrings::class,

\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
                    \Illuminate\Session\Middleware\StartSession::class,
                ];

                /**
                 * The application's route middleware groups.
                 *
                 * @var array
                 */
                protected $middlewareGroups = [
                    'web' => [
                        \App\Http\Middleware\EncryptCookies::class,

            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
                        \Illuminate\Session\Middleware\StartSession::class,
                       //  \Illuminate\Session\Middleware\AuthenticateSession::class,
                        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
                        \App\Http\Middleware\VerifyCsrfToken::class,
                        \Illuminate\Routing\Middleware\SubstituteBindings::class,
                    ],

                    'api' => [
                        'throttle:60,1',
                        'bindings',
                    ],
                ];

                /**
                 * The application's route middleware.
                 *
                 * These middleware may be assigned to groups or used individually.
                 *
                 * @var array
                 */
                protected $routeMiddleware = [
                    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
                    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
                    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
                    'can' => \Illuminate\Auth\Middleware\Authorize::class,
                    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
                    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
                ];
                }

part of web.php

Route::get('/Admin', function () {
   return view('Adminlogin');
});

Route::group(['middleware' => ['web']], function () {
Route::get('/StartExamInfo/{id}', 'ExamController@Info');
Route::post('/Exam', 'ExamController@Start');
Route::post('/result','resultController@Add');

});

logincontroller.php

namespace App\Http\Controllers;

use App\admin;
use App\students;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\hash;
use Validator;
class LoginController extends Controller
{
public function Login(Request $request)
{

    if (Auth::guard('web')->attempt(['username' => $request->username , 'password' => $request->password , 'typeofuser' => 1 ]))
    {
        $admin = new admin();
        $admin->username = $request->username;
        $admin->getuser();
        $user = [$admin->ID,$admin->firstname,$admin->lastname,$admin->email,$admin->phonenumber,$admin->pic,$admin->expirtime];
        return view('Admin_home',['user'=>$user]);
    }
    if (Auth::guard('web')->attempt(['username' => $request->username , 'password' => $request->password , 'typeofuser' => 2 ]))
    {
        $std = new students();
        $std->username = $request->username;
        $std->getuser();
        $user = [$std->ID,$std->firstname,$std->lastname,$std->email,$std->pic,$std->expirtime];
        return view('Student_home',['user'=>$user]);
    }
    else
   return view('AdminLogin');

    //$v = validator::make($request->all());
    //
    //$admin->auth($request->username,$request->password);
}

public function logout()
{
    Auth::logout();
    return view('AdminLogin');
}
}

Body:
You are trying to access your POSTed data in a wrong way. You should take posted user's entry with $request object. Also, you can authenticate the user with a single auth condition. When the user has authenticated, check its typeofuser field with two simple conditions. Something like this:

public function Login(Request $request)
    {
        $credential = $request->only(['username', 'password']);
        if (!Auth::attempt($credential))
            return 'Username or Password is incorrect.';

        // Now you can access to authenticated user model with `users` method in request object
        $user = $request->user();
        if($user->typeofuser == 1)
        {
            $admin = new admin();
            $admin->username = $credential['username'];
            $admin->getuser();
            $user = [$admin->ID,$admin->firstname,$admin->lastname,$admin->email,$admin->phonenumber,$admin->pic,$admin->expirtime];
            return view('Admin_home',['user'=>$user]);
        }
        elseif ($user->typeofuser == 2)
        {
            $std = new students();
            $std->username = $credential['username'];
            $std->getuser();
            $user = [$std->ID,$std->firstname,$std->lastname,$std->email,$std->pic,$std->expirtime];
            return view('Student_home',['user'=>$user]);
        }
        else
            return view('AdminLogin');
    }


问:
DPLYR based multiple subsetting
The following dataframe contains data regarding a marketing campaign.

```<code>Sl No   Success_Percentage  communication_type  Message
 1       35.46666667           email            Hello, Buy New Product
  2      32.32830821          email              Hi Buy New Product
  3       22.9226361           SMS               Hello World
  4       21.88888889          SMS               Hello, Buy New Product
  5       40.04085802          FB                Hi Buy New Product
  6       38.7283237            FB               Hello World
</code>```

I wish create a table as follows.

```<code>Success_Percentage  communication_type  Message
  22.9226361          SMS             Hello World
 21.88888889          SMS             Hello, Buy New Product
   35.46666667      email             Hello, Buy New Product
   32.32830821      email             Hi Buy New Product
   40.04085802       FB               Hi Buy New Product
    38.7283237        FB              Hello World
</code>```

I Have used dplyr package to achieve subsets.

```<code>  require(dplyr)
  dataframe%>%
  group_by(communication_type, Message)
  summarise_all(order(Success_Percentage))
</code>```

I am unable to obtain the above output. Note that Success % is randomly mixed(not in linear order as here)
I am unable to get the desired output.

答:
From your new table, it seems that you would like to arrange the table according to the communication_type and within each communication_type, you would like to arrange Success_Percentage in descending order.

Your dataset:

```<code>df <- structure(list(Sl_No = 1:6, Success_Percentage = c(35.46666667,
                                                         32.32830821, 22.9226361, 21.88888889, 40.04085802, 38.7283237
), communication_type = c("email", "email", "SMS", "SMS", "FB",
                          "FB"), Message = c("Hello, Buy New Product", "Hi Buy New Product",
                                             "Hello World", "Hello, Buy New Product", "Hi Buy New Product",
                                             "Hello World")), class = "data.frame", .Names = c("Sl_No", "Success_Percentage",
                                                                                "communication_type", "Message"), row.names = c(NA, -6L))
</code>```

Factorise communication_type in the order SMS, email and FB; and arrange accordingly:

```<code>df %>%
  mutate(communication_type = factor(communication_type, levels = c("SMS", "email", "FB"))) %>%
  arrange(communication_type, desc(Success_Percentage))
</code>```

Title: DPLYR based multiple subsetting

Body:
The following dataframe contains data regarding a marketing campaign.

Sl No   Success_Percentage  communication_type  Message
 1       35.46666667           email            Hello, Buy New Product
  2      32.32830821          email              Hi Buy New Product
  3       22.9226361           SMS               Hello World
  4       21.88888889          SMS               Hello, Buy New Product
  5       40.04085802          FB                Hi Buy New Product
  6       38.7283237            FB               Hello World

I wish create a table as follows.

Success_Percentage  communication_type  Message
  22.9226361          SMS             Hello World
 21.88888889          SMS             Hello, Buy New Product
   35.46666667      email             Hello, Buy New Product
   32.32830821      email             Hi Buy New Product
   40.04085802       FB               Hi Buy New Product
    38.7283237        FB              Hello World

I Have used dplyr package to achieve subsets.

  require(dplyr)
  dataframe%>%
  group_by(communication_type, Message)
  summarise_all(order(Success_Percentage))

I am unable to obtain the above output. Note that Success % is randomly mixed(not in linear order as here)
I am unable to get the desired output.

Body:
From your new table, it seems that you would like to arrange the table according to the communication_type and within each communication_type, you would like to arrange Success_Percentage in descending order.

Your dataset:

df <- structure(list(Sl_No = 1:6, Success_Percentage = c(35.46666667,
                                                         32.32830821, 22.9226361, 21.88888889, 40.04085802, 38.7283237
), communication_type = c("email", "email", "SMS", "SMS", "FB",
                          "FB"), Message = c("Hello, Buy New Product", "Hi Buy New Product",
                                             "Hello World", "Hello, Buy New Product", "Hi Buy New Product",
                                             "Hello World")), class = "data.frame", .Names = c("Sl_No", "Success_Percentage",
                                                                                "communication_type", "Message"), row.names = c(NA, -6L))

Factorise communication_type in the order SMS, email and FB; and arrange accordingly:

df %>%
  mutate(communication_type = factor(communication_type, levels = c("SMS", "email", "FB"))) %>%
  arrange(communication_type, desc(Success_Percentage))


问:
azure data lake u-sql pivot
I am loving Azure Data Lake but lack of documentation will probably slow down the adoption. I hope somebody out there have more experinnce on U-SQL than I do.

Trying to derive from what's available under Microsoft.Analytics.Interfaces and via U-SQL interpreter with not much luck. Dynamic sql does not seem to be supported to define the schema of a row set at run time and IUpdatableRow's schema is readonly so Processor approach is not viable. And there is no out of the box PIVOT capability in U-SQL.

I also thought that maybe I can process the rowset all together and write a custom outputter to pivot but couldn't figure it out.

There is probably a really easy way to do this as it is a standard pivot operation. How would you go about reshaping a rowset from I to II for an indeterminate number of ColA and ColB values in a performant way?

I

```<code>|ColA |ColB |ColC|
|1    |A    |30  |
|1    |B    |70  |
|1    |ZA   |12  |
|2    |C    |22  |
|2    |A    |13  |
</code>```

II

```<code>|ID   |A    |B    |C   |...... |ZA   |.....
|1    |30   |70   |0   |       |12   |
|2    |13   |0    |22  |...... |0    |.....
</code>```

答:
Here is one workaround that my team member come up with for a scenario where we don't know a number of columns ahead of time.

```<code>@t = SELECT *
     FROM(
        VALUES
        ( 1, "A", 30 ),
        ( 1, "B", 70 ),
        ( 1, "ZA", 12 ),
        ( 2, "C", 22 ),
        ( 2, "A", 13 ),
        ( 2, "ABC", 42)
     ) AS T(ColA, ColB, ColC);

@t1 =
    SELECT DISTINCT ColB
    FROM @t
ORDER BY ColB DESC
OFFSET 0 ROW;

@t1 =
    SELECT ARRAY_AGG(ColB) AS ColBArray
    FROM @t1;

@result =
    SELECT ColA,
           MAP_AGG(ColB, (int?) ColC) AS ColCMap
    FROM @t
    GROUP BY ColA;

@result =
    SELECT a.ColA,
           DPivotNS.DPivot.FillGapsAndConvert(a.ColCMap, b.ColBArray) AS Values
    FROM @result AS a
         CROSS JOIN
             @t1 AS b;

@result =
    SELECT ColA,
           ArrayColumn
    FROM
    (
    SELECT 0 AS ColA,
           ColBArray AS ArrayColumn,
           0 AS Ord
    FROM @t1
    UNION ALL
    SELECT ColA AS ColA,
           Values AS ArrayColumn,
           1 AS Ord
    FROM @result
    ) AS rs1
ORDER BY rs1.Ord
OFFSET 0 ROWS;

@result =
    SELECT ColA,
           String.Join(",", ArrayColumn) AS Values
    FROM @result;

OUTPUT @result
TO "result.csv"
USING Outputters.Csv(quoting:false);
</code>```

Here is UDF for above script:

```<code>    public static SqlArray<string> FillGapsAndConvert (SqlMap<string, int?> ColCMap, SqlArray<string> ColDArray)
        {
        var list = new LinkedList<string> ();
        foreach ( string colD in ColDArray )
            {
            int? currentCount = ColCMap[colD];
            int newCount = currentCount.HasValue ? currentCount.Value : 0;
            list.AddLast (newCount.ToString ());
            }
        return new SqlArray<string> (list);
        }
</code>```

Title: azure data lake u-sql pivot

Body:
I am loving Azure Data Lake but lack of documentation will probably slow down the adoption. I hope somebody out there have more experinnce on U-SQL than I do.

Trying to derive from what's available under Microsoft.Analytics.Interfaces and via U-SQL interpreter with not much luck. Dynamic sql does not seem to be supported to define the schema of a row set at run time and IUpdatableRow's schema is readonly so Processor approach is not viable. And there is no out of the box PIVOT capability in U-SQL.

I also thought that maybe I can process the rowset all together and write a custom outputter to pivot but couldn't figure it out.

There is probably a really easy way to do this as it is a standard pivot operation. How would you go about reshaping a rowset from I to II for an indeterminate number of ColA and ColB values in a performant way?

I

|ColA |ColB |ColC|
|1    |A    |30  |
|1    |B    |70  |
|1    |ZA   |12  |
|2    |C    |22  |
|2    |A    |13  |

II

|ID   |A    |B    |C   |...... |ZA   |.....
|1    |30   |70   |0   |       |12   |
|2    |13   |0    |22  |...... |0    |.....

Body:
Here is one workaround that my team member come up with for a scenario where we don't know a number of columns ahead of time.

@t = SELECT *
     FROM(
        VALUES
        ( 1, "A", 30 ),
        ( 1, "B", 70 ),
        ( 1, "ZA", 12 ),
        ( 2, "C", 22 ),
        ( 2, "A", 13 ),
        ( 2, "ABC", 42)
     ) AS T(ColA, ColB, ColC);

@t1 =
    SELECT DISTINCT ColB
    FROM @t
ORDER BY ColB DESC
OFFSET 0 ROW;

@t1 =
    SELECT ARRAY_AGG(ColB) AS ColBArray
    FROM @t1;

@result =
    SELECT ColA,
           MAP_AGG(ColB, (int?) ColC) AS ColCMap
    FROM @t
    GROUP BY ColA;

@result =
    SELECT a.ColA,
           DPivotNS.DPivot.FillGapsAndConvert(a.ColCMap, b.ColBArray) AS Values
    FROM @result AS a
         CROSS JOIN
             @t1 AS b;

@result =
    SELECT ColA,
           ArrayColumn
    FROM
    (
    SELECT 0 AS ColA,
           ColBArray AS ArrayColumn,
           0 AS Ord
    FROM @t1
    UNION ALL
    SELECT ColA AS ColA,
           Values AS ArrayColumn,
           1 AS Ord
    FROM @result
    ) AS rs1
ORDER BY rs1.Ord
OFFSET 0 ROWS;

@result =
    SELECT ColA,
           String.Join(",", ArrayColumn) AS Values
    FROM @result;

OUTPUT @result
TO "result.csv"
USING Outputters.Csv(quoting:false);

Here is UDF for above script:

    public static SqlArray<string> FillGapsAndConvert (SqlMap<string, int?> ColCMap, SqlArray<string> ColDArray)
        {
        var list = new LinkedList<string> ();
        foreach ( string colD in ColDArray )
            {
            int? currentCount = ColCMap[colD];
            int newCount = currentCount.HasValue ? currentCount.Value : 0;
            list.AddLast (newCount.ToString ());
            }
        return new SqlArray<string> (list);
        }