问:
How to change button URL through JS?
I have been spending a lot of time researching how to change a button href dynamically in my website using JS.  I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.

I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.

One of the simplest solutions that should work was found here:
  How to make option selection change button link?

I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed.  I added window.onload() to prevent the JS from running before elements were loaded.

I am trying to do something similar with the following HTML & JS code:

HTML Code:

```<code><input type="hidden" id="input-book-type" value="GlassCrystal">

<br><br>

<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>

<br><br>

<input id="input-project-title" value="Optional Project Title">

<br><br>

<a class="button" id="design-button" href="http://">Design Now</a>
</code>```

JS Code:

```<code>window.onload = function() {

document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");

this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};

}
</code>```

JS Fiddle:
https://jsfiddle.net/w65c9x2d/

答:
I think your code to change the href is correct. However, the onload function is not immediately invoked for the code to work.

window.onload = function(e) {

  var booktype = document.getElementById("input-book-type");
  var pagesize = document.getElementById("select-page-size");
  var pagenum = document.getElementById("select-page-num");
  var projtitle = document.getElementById("input-project-title");

  document.getElementById("design-button").onclick = function() {
    this.href = "http://design.framesmile.com/?sessionid=guest&ref=" + booktype.value + pagesize.value + "*projectName=" + projtitle.value + " / ";
    console.log(this.href);
  };
}();// invoke the function```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="hidden" id="input-book-type" type="" value="GlassCrystal">

<br>
<br>

<select id="select-page-size">
  <option value="6x6">6" x 6"</option>
  <option value="10x10">10" x 10"</option>
</select>

<br>
<br>

<select id="select-page-num">
  <option value="20">20</option>
  <option value="22">22</option>
</select>

<br>
<br>

<input id="input-project-title" type="" value="Optional Project Title">

<br>
<br>

Design Now</code>```

Title: How to change button URL through JS?

Body:
I have been spending a lot of time researching how to change a button href dynamically in my website using JS.  I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.

I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.

One of the simplest solutions that should work was found here:
  How to make option selection change button link?

I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed.  I added window.onload() to prevent the JS from running before elements were loaded.

I am trying to do something similar with the following HTML & JS code:

HTML Code:

<input type="hidden" id="input-book-type" value="GlassCrystal">

<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>

<input id="input-project-title" value="Optional Project Title">

Design Now

JS Code:

window.onload = function() {

document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");

this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};

}

JS Fiddle:
https://jsfiddle.net/w65c9x2d/

Body:
I think your code to change the href is correct. However, the onload function is not immediately invoked for the code to work.

window.onload = function(e) {

  var booktype = document.getElementById("input-book-type");
  var pagesize = document.getElementById("select-page-size");
  var pagenum = document.getElementById("select-page-num");
  var projtitle = document.getElementById("input-project-title");

  document.getElementById("design-button").onclick = function() {
    this.href = "http://design.framesmile.com/?sessionid=guest&ref=" + booktype.value + pagesize.value + "*projectName=" + projtitle.value + " / ";
    console.log(this.href);
  };
}();// invoke the function

<input type="hidden" id="input-book-type" type="" value="GlassCrystal">

<br>
<br>

<select id="select-page-size">
  <option value="6x6">6" x 6"</option>
  <option value="10x10">10" x 10"</option>
</select>

<br>
<br>

<select id="select-page-num">
  <option value="20">20</option>
  <option value="22">22</option>
</select>

<br>
<br>

<input id="input-project-title" type="" value="Optional Project Title">

<br>
<br>

<a class="button" id="design-button" href="http://test/">Design Now</a>


来源: stackexchange

问:
Getting error PDO/SQL
I'm getting the following error

Link to DBconfig.php ->

Link to code ->

Can you guys please help me ;)

thank you!

My code ->

```<code><?php
    include '../header.php';
    include '../dbconfig.php';

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

        $naam = $_POST['naam'];
        $email = $_POST['email'];
        $wachtwoord = $_POST['wachtwoord'];

        $insert = $db->prepare("INSERT INTO klant(naam, adres, postcode, email, password)
        values(:name, :adres, :postcode, :woonplaats, :email, :pass) ");

        $insert->bindParam(':naam',$naam);
        $insert->bindParam(':adres',$adres);
        $insert->bindParam(':postcode',$postcode);
        $insert->bindParam(':woonplaats',$woonplaats);
        $insert->bindParam(':email',$email);
        $insert->bindParam(':wachtwoord',$wachtwoord);

        $insert->execute();
    }
?>
</code>```

答:
```<code>values(:name, :adres, :postcode, :woonplaats, :email, :pass) ");
</code>```

You have parameters :name and :pass but in your bindings you have spelled them in Dutch:

```<code>$insert->bindParam(':naam',$naam);
$insert->bindParam(':wachtwoord',$wachtwoord);
</code>```

PDO doesn't know how to translate parameter names between English and Dutch. :-)

ContentLicense: CC BY-SA 3.0

Title: Getting error PDO/SQL

Body:
I'm getting the following error

Link to DBconfig.php ->

Link to code ->

Can you guys please help me ;)

thank you!

My code ->

<?php
    include '../header.php';
    include '../dbconfig.php';

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

        $naam = $_POST['naam'];
        $email = $_POST['email'];
        $wachtwoord = $_POST['wachtwoord'];

        $insert = $db->prepare("INSERT INTO klant(naam, adres, postcode, email, password)
        values(:name, :adres, :postcode, :woonplaats, :email, :pass) ");

        $insert->bindParam(':naam',$naam);
        $insert->bindParam(':adres',$adres);
        $insert->bindParam(':postcode',$postcode);
        $insert->bindParam(':woonplaats',$woonplaats);
        $insert->bindParam(':email',$email);
        $insert->bindParam(':wachtwoord',$wachtwoord);

        $insert->execute();
    }
?>

Body:
values(:name, :adres, :postcode, :woonplaats, :email, :pass) ");

You have parameters :name and :pass but in your bindings you have spelled them in Dutch:

$insert->bindParam(':naam',$naam);
$insert->bindParam(':wachtwoord',$wachtwoord);

PDO doesn't know how to translate parameter names between English and Dutch. :-)


问:
APCu Adapter & Symfony 3.3 -> Error
I am trying to plug APCu into the Symfony 3.3 test project.
I am getting an error, when I add ApcuAdapter to AppKernel.php.
Here is the list of what I have done:

in ./app/AppKernel.php i have added a "new" line to $bundles in public function registerBundles():

```<code>public function registerBundles()
{
    $bundles = [
        ... ,
        new Symfony\Component\Cache\Adapter\ApcuAdapter()
    ];

    ...

    return $bundles;
}
</code>```

Opened the project's site. It shows an error:

Attempted to call an undefined method named "getName" of class "Symfony\Component\Cache\Adapter\ApcuAdapter".

(./ means the root folder of the project)

Please, tell me why does this error happen and how to plug this adapter into the symfony framework. Thank you.

答:
me have found the solution somewhere on the framework's website.

somehow, we should use not the Adapter, but the Simple instead.
seems very un-logical to me.

so, the Service now works and looks this way:

```<code>    <?php

    namespace AppBundle\Service;

    use Symfony\Component\Cache\Simple\ApcuCache;

    class ApcuTester
    {
        public function __construct
        (
        )
        {

        }

        public function testMe()
        {
            $cache = new ApcuCache();

            $TestVar_dv = 0;
            $TestVar_vn = 'TestVar';
            $TestVar = NULL;

            //$cache-> deleteItem($TestVar_vn); // dbg

            // Read
            if ( $cache->hasItem($TestVar_vn) )
            {
                $TestVar = $cache->get($TestVar_vn);
            }
            else
            {
                $cache->set($TestVar_vn, $TestVar_dv);
                $TestVar = $TestVar_dv;
            }

            // Modify
            $TestVar++;

            // Save
            $cache->set($TestVar_vn, $TestVar);

            // Return
            return $TestVar;
        }
    }
</code>```

And the Controller which executes this Service looks as this:

```<code>    <?php

    namespace AppBundle\Controller;

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;

    use AppBundle\Service\MessageGenerator;
    use AppBundle\Service\ApcuTester;

    class LuckyController extends Controller
    {
        /**
        * @Route("/lucky/number", name="lucky")
        */
        public function numberAction
        (
            Request $request,
            MessageGenerator $messageGenerator,
            ApcuTester $apcuTester
        )
        {
            $lucky_number = mt_rand(0, 100);

            $message = $messageGenerator->getHappyMessage();

            $testvar = $apcuTester->testMe();

            $tpl = 'default/lucky_number.html.twig';
            $tpl_vars =
            [
                'lucky_number' => $lucky_number,
                'message' => $message,
                'testvar' => $testvar
            ];

            return $this->render($tpl, $tpl_vars);
        }
    }
</code>```

If i wrote the same thing in pure PHP i would have done it an hour earlier :) Oh these crazy frameworks...

Title: APCu Adapter & Symfony 3.3 -> Error

Body:
I am trying to plug APCu into the Symfony 3.3 test project.
I am getting an error, when I add ApcuAdapter to AppKernel.php.
Here is the list of what I have done:

in ./app/AppKernel.php i have added a "new" line to $bundles in public function registerBundles():

public function registerBundles()
{
    $bundles = [
        ... ,
        new Symfony\Component\Cache\Adapter\ApcuAdapter()
    ];

    ...

    return $bundles;
}

Opened the project's site. It shows an error:

Attempted to call an undefined method named "getName" of class "Symfony\Component\Cache\Adapter\ApcuAdapter".

(./ means the root folder of the project)

Please, tell me why does this error happen and how to plug this adapter into the symfony framework. Thank you.

Body:
me have found the solution somewhere on the framework's website.

somehow, we should use not the Adapter, but the Simple instead.
seems very un-logical to me.

so, the Service now works and looks this way:

    <?php

    namespace AppBundle\Service;

    use Symfony\Component\Cache\Simple\ApcuCache;

    class ApcuTester
    {
        public function __construct
        (
        )
        {

        }

        public function testMe()
        {
            $cache = new ApcuCache();

            $TestVar_dv = 0;
            $TestVar_vn = 'TestVar';
            $TestVar = NULL;

            //$cache-> deleteItem($TestVar_vn); // dbg

            // Read
            if ( $cache->hasItem($TestVar_vn) )
            {
                $TestVar = $cache->get($TestVar_vn);
            }
            else
            {
                $cache->set($TestVar_vn, $TestVar_dv);
                $TestVar = $TestVar_dv;
            }

            // Modify
            $TestVar++;

            // Save
            $cache->set($TestVar_vn, $TestVar);

            // Return
            return $TestVar;
        }
    }

And the Controller which executes this Service looks as this:

    <?php

    namespace AppBundle\Controller;

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;

    use AppBundle\Service\MessageGenerator;
    use AppBundle\Service\ApcuTester;

    class LuckyController extends Controller
    {
        /**
        * @Route("/lucky/number", name="lucky")
        */
        public function numberAction
        (
            Request $request,
            MessageGenerator $messageGenerator,
            ApcuTester $apcuTester
        )
        {
            $lucky_number = mt_rand(0, 100);

            $message = $messageGenerator->getHappyMessage();

            $testvar = $apcuTester->testMe();

            $tpl = 'default/lucky_number.html.twig';
            $tpl_vars =
            [
                'lucky_number' => $lucky_number,
                'message' => $message,
                'testvar' => $testvar
            ];

            return $this->render($tpl, $tpl_vars);
        }
    }

If i wrote the same thing in pure PHP i would have done it an hour earlier :) Oh these crazy frameworks...


问:
CodeIgniter project .htaccess issue
I want to install a codeigniter project on a GoDaddy hosting.

I've followed the Godaddy Installation Tips instructions from the CodeIgniter Wiki.

In config.php

```<code>$config['index_page'] = "index.php?";
$config['uri_protocol'] = "QUERY_STRING";
</code>```

In .htaccess

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?$1 [L]
</code>```

I can access everything as such

```<code>http://yourdomain.com/controller/action/etc
</code>```

But

When I have a get parameters in url

```<code>http://yourdomain.com/controller/action/etc?id=1
</code>```

The .htaccess remove the parameter ?id=1 so

```<code>http://yourdomain.com/controller/action/etc?id=1
</code>```

become

```<code>http://yourdomain.com/controller/action/etc
</code>```

答:
Try this code in .htaccess:

```<code>DirectoryIndex index.php
# Turn on URL rewriting
RewriteEngine On

# If your website begins from a folder e.g localhost/my_project then
# you have to change it to: RewriteBase /my_project/
# If your site begins from the root e.g. example.local/ then
# let it as it is

RewriteBase /

# Protect application and system files from being viewed when the index.php is missing
RewriteCond $1 ^(application|system|private|logs)

# Rewrite to index.php/access_denied/URL
RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

# Allow these directories and files to be displayed directly:
RewriteCond $1 ^(index\.php|robots\.txt|opensearch\.xml|favicon\.ico|assets|forums)

# No rewriting
RewriteRule ^(.*)$ - [PT,L]

# Rewrite to index.php/URL
RewriteCond %{REQUEST_URI} !^(.+)\.(js|css|gif|png|jpg|jpeg|bmp|swf|txt|xml|htc|pdf|xls|doc|ico)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [PT,L]
</code>```

I used this in one of the project, and its working there...

Title: CodeIgniter project .htaccess issue

Body:
I want to install a codeigniter project on a GoDaddy hosting.

I've followed the Godaddy Installation Tips instructions from the CodeIgniter Wiki.

In config.php

$config['index_page'] = "index.php?";
$config['uri_protocol'] = "QUERY_STRING";

In .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?$1 [L]

I can access everything as such

http://yourdomain.com/controller/action/etc

But

When I have a get parameters in url

http://yourdomain.com/controller/action/etc?id=1

The .htaccess remove the parameter ?id=1 so

http://yourdomain.com/controller/action/etc?id=1

become

http://yourdomain.com/controller/action/etc

Body:
Try this code in .htaccess:

DirectoryIndex index.php
# Turn on URL rewriting
RewriteEngine On

# If your website begins from a folder e.g localhost/my_project then
# you have to change it to: RewriteBase /my_project/
# If your site begins from the root e.g. example.local/ then
# let it as it is

RewriteBase /

# Protect application and system files from being viewed when the index.php is missing
RewriteCond $1 ^(application|system|private|logs)

# Rewrite to index.php/access_denied/URL
RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

# Allow these directories and files to be displayed directly:
RewriteCond $1 ^(index\.php|robots\.txt|opensearch\.xml|favicon\.ico|assets|forums)

# No rewriting
RewriteRule ^(.*)$ - [PT,L]

# Rewrite to index.php/URL
RewriteCond %{REQUEST_URI} !^(.+)\.(js|css|gif|png|jpg|jpeg|bmp|swf|txt|xml|htc|pdf|xls|doc|ico)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [PT,L]

I used this in one of the project, and its working there...


问:
Linked List, read from text file, and sort by key
I'm trying to sort the Linked List by the key( priority number, the int number) from highest to lowest, with the data from text file. I'm stucking at insert the item and sort them.
Here is My text file.

Myjob 66

Junk   17

Fun    25

Important   96

Vital       99

MoreFun    28

Work      69

Assignment  44

Here is my Linked List class

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

@SuppressWarnings("unused")
public class LinkedList {
    Node head;
    Node prev;
    Node cur;
    Node node;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

//insert method
public void insert(Data dt){
    try {
        if(head==null){
            head = new Node(dt.getData(), null);
            System.out.println("Opps");
            }
        else if (dt.getData().num > head.dt.num){
            head = new Node(dt.getData(),head);
            System.out.println("Was Here");}
        else if (head.getNext()==null){
            head.setNext(new Node(dt.getData(),null));
            }
        else{
            cur = head.getNext();
            for(prev = head;cur!= null;cur=cur.getNext()){
                if(cur.dt.num>prev.dt.num){
                    Node temp = new Node(dt.getData(),cur);
                    prev.setNext(temp);
                    break;
                }
                else{
                    prev=cur;

                }
            }
        }
    }
        catch (NullPointerException e){
            System.out.println("Here is Error");
        }

}

//Running Linked list
public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        Data dt = new Data();

        l1.insert(dt);

}
</code>```

}

Here is My Node class:

```<code>public class Node {
Data dt;
Node next;

public Node(Data dt, Node next){
    this.dt=dt;
    this.next=next;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt.getData();
}

}
</code>```

Here is my Data class:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Data {

protected String name;
protected int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

//getter to get Data
@SuppressWarnings("unused")
public Data getData(){
        try{
            int count =0;
            File x = new File("Asg2Data.txt");
            Scanner sc = new Scanner(x);
            while (sc.hasNext()){
                String name = sc.next();
                int num = sc.nextInt();
                Data data= new Data(name,num);
                System.out.println("Name = "+ name+"          "+"Priority = "+num);
                System.out.println(" ");
                count++;
            }
            System.out.println("Total Objects: "+count);
            sc.close();
        }catch(FileNotFoundException e){
            System.out.println("Error");
        }
        return this;
}

//Compare Function
//  public int compare(Data dt){
//      if (this.getData().num > dt.getData().num)
//          return 1;
//      else if (this.getData().num < dt.getData().num)
//          return -1;
//      else
//          return 0;
//  }

// Testing: Worked !!!!!
    public static void main(String[] args){
        Data d1 = new Data();
        d1.getData();
    }

}
</code>```

My currently output, when I run from Linked List class:

```<code>Name = Myjob          Priority = 66

Name = Junk          Priority = 17

Name = Fun          Priority = 25

Name = Important          Priority = 96

Name = Vital          Priority = 99

Name = MoreFun          Priority = 28

Name = Work          Priority = 69

Name = Assignment          Priority = 44

Total Objects: 8
Opps
</code>```

My insert method always stop at the first if statement, and never keep going. I have no clue how to fix it. At the mean time, it can not perform the insert the data + sort them by the priority number from highest to lowest.  Can anyone help me ? I'm super new in Java. Thank you so much.

-Dustin

答:
First things first your LinkedList is not getting initialized is because in your Data->getData() method you are creating the data objects but never assigning them to the head and the next of the LinkedList head.

As you are new to Java just want to give you some tips on coding with Java.

Don’t use suppress warnings unless utmost important.  Most of the time you can handle them.

Try to segregate the code as much as possible. This will help you and everybody else to understand the code. Ex. why does your Data class have the initialization code, it should be in the LinkedList. Data is just a representation class which will act as a model for your data (This may be design consideration and you might have your reasons to do this..just saying)

You can also go through the identifiers once and how to use them.

I won't give you the complete the code (because then there will be nothing for you to do) but the below snippet should get you started. I have tried to use your code as much as possible so that it is easier for you to understand. Below code will initialize a LinkedList with the data required, maybe you can take care from there. You can continue to ask any questions if you face any issue going forward

`

```<code> import java.io.File;
 import java.util.Scanner;

 public class LinkedList
    {
        Node head;

        public static void main(String[] args)
        {
            LinkedList list = new LinkedList();
            list.initializeLL();
            list.printLinkedList();
        }

        private void printLinkedList(){
            System.out.println(head);
        }

        private void initializeLL()
        {
            Node currentNode = head;
            try
            {
                File file = new File("Asg2Data.txt");
                Scanner sc = new Scanner(file);
                while (sc.hasNext())
                {
                    Data d = new Data(sc.next(), sc.nextInt());
                    Node n = new Node(d);
                    if(currentNode == null){
                        currentNode = n;
                        head = n;
                    }else{
                        currentNode.setNextNode(n);
                        currentNode = n;
                    }
                }
                sc.close();
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }

    }

    class Node
    {

        private Data data;

        private Node nextNode;

        public Node(Data data)
        {
            this.data = data;
        }

        public Data getData()
        {
            return data;
        }

        public void setData(Data data)
        {
            this.data = data;
        }

        public Node getNextNode()
        {
            return nextNode;
        }

        public void setNextNode(Node nextNode)
        {
            this.nextNode = nextNode;
        }

        @Override
        public String toString()
        {
            return "Node [data=" + data + ", nextNode=" + nextNode + "]";
        }

    }

    class Data
    {

        private String name;

        private int data;

        public Data(String name, int data)
        {
            this.name = name;
            this.data = data;
        }

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        public int getData()
        {
            return data;
        }

        public void setData(int data)
        {
            this.data = data;
        }

        @Override
        public String toString()
        {
            return "Data [name=" + name + ", data=" + data + "]";
        }
    }
</code>```

`

Body:
I'm trying to sort the Linked List by the key( priority number, the int number) from highest to lowest, with the data from text file. I'm stucking at insert the item and sort them.
Here is My text file.

Myjob 66

Junk   17

Fun    25

Important   96

Vital       99

MoreFun    28

Work      69

Assignment  44

Here is my Linked List class

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

@SuppressWarnings("unused")
public class LinkedList {
    Node head;
    Node prev;
    Node cur;
    Node node;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

//insert method
public void insert(Data dt){
    try {
        if(head==null){
            head = new Node(dt.getData(), null);
            System.out.println("Opps");
            }
        else if (dt.getData().num > head.dt.num){
            head = new Node(dt.getData(),head);
            System.out.println("Was Here");}
        else if (head.getNext()==null){
            head.setNext(new Node(dt.getData(),null));
            }
        else{
            cur = head.getNext();
            for(prev = head;cur!= null;cur=cur.getNext()){
                if(cur.dt.num>prev.dt.num){
                    Node temp = new Node(dt.getData(),cur);
                    prev.setNext(temp);
                    break;
                }
                else{
                    prev=cur;

                }
            }
        }
    }
        catch (NullPointerException e){
            System.out.println("Here is Error");
        }

}

//Running Linked list
public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        Data dt = new Data();

        l1.insert(dt);

}

}

Here is My Node class:

public class Node {
Data dt;
Node next;

public Node(Data dt, Node next){
    this.dt=dt;
    this.next=next;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt.getData();
}

}

Here is my Data class:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Data {

protected String name;
protected int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

//getter to get Data
@SuppressWarnings("unused")
public Data getData(){
        try{
            int count =0;
            File x = new File("Asg2Data.txt");
            Scanner sc = new Scanner(x);
            while (sc.hasNext()){
                String name = sc.next();
                int num = sc.nextInt();
                Data data= new Data(name,num);
                System.out.println("Name = "+ name+"          "+"Priority = "+num);
                System.out.println(" ");
                count++;
            }
            System.out.println("Total Objects: "+count);
            sc.close();
        }catch(FileNotFoundException e){
            System.out.println("Error");
        }
        return this;
}

//Compare Function
//  public int compare(Data dt){
//      if (this.getData().num > dt.getData().num)
//          return 1;
//      else if (this.getData().num < dt.getData().num)
//          return -1;
//      else
//          return 0;
//  }

// Testing: Worked !!!!!
    public static void main(String[] args){
        Data d1 = new Data();
        d1.getData();
    }

}

My currently output, when I run from Linked List class:

Name = Myjob          Priority = 66

Name = Junk          Priority = 17

Name = Fun          Priority = 25

Name = Important          Priority = 96

Name = Vital          Priority = 99

Name = MoreFun          Priority = 28

Name = Work          Priority = 69

Name = Assignment          Priority = 44

Total Objects: 8
Opps

My insert method always stop at the first if statement, and never keep going. I have no clue how to fix it. At the mean time, it can not perform the insert the data + sort them by the priority number from highest to lowest.  Can anyone help me ? I'm super new in Java. Thank you so much.

-Dustin

Body:
First things first your LinkedList is not getting initialized is because in your Data->getData() method you are creating the data objects but never assigning them to the head and the next of the LinkedList head.

As you are new to Java just want to give you some tips on coding with Java.

Don’t use suppress warnings unless utmost important.  Most of the time you can handle them.

Try to segregate the code as much as possible. This will help you and everybody else to understand the code. Ex. why does your Data class have the initialization code, it should be in the LinkedList. Data is just a representation class which will act as a model for your data (This may be design consideration and you might have your reasons to do this..just saying)

You can also go through the identifiers once and how to use them.

I won't give you the complete the code (because then there will be nothing for you to do) but the below snippet should get you started. I have tried to use your code as much as possible so that it is easier for you to understand. Below code will initialize a LinkedList with the data required, maybe you can take care from there. You can continue to ask any questions if you face any issue going forward

`

 import java.io.File;
 import java.util.Scanner;

 public class LinkedList
    {
        Node head;

        public static void main(String[] args)
        {
            LinkedList list = new LinkedList();
            list.initializeLL();
            list.printLinkedList();
        }

        private void printLinkedList(){
            System.out.println(head);
        }

        private void initializeLL()
        {
            Node currentNode = head;
            try
            {
                File file = new File("Asg2Data.txt");
                Scanner sc = new Scanner(file);
                while (sc.hasNext())
                {
                    Data d = new Data(sc.next(), sc.nextInt());
                    Node n = new Node(d);
                    if(currentNode == null){
                        currentNode = n;
                        head = n;
                    }else{
                        currentNode.setNextNode(n);
                        currentNode = n;
                    }
                }
                sc.close();
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }

    }

    class Node
    {

        private Data data;

        private Node nextNode;

        public Node(Data data)
        {
            this.data = data;
        }

        public Data getData()
        {
            return data;
        }

        public void setData(Data data)
        {
            this.data = data;
        }

        public Node getNextNode()
        {
            return nextNode;
        }

        public void setNextNode(Node nextNode)
        {
            this.nextNode = nextNode;
        }

        @Override
        public String toString()
        {
            return "Node [data=" + data + ", nextNode=" + nextNode + "]";
        }

    }

    class Data
    {

        private String name;

        private int data;

        public Data(String name, int data)
        {
            this.name = name;
            this.data = data;
        }

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        public int getData()
        {
            return data;
        }

        public void setData(int data)
        {
            this.data = data;
        }

        @Override
        public String toString()
        {
            return "Data [name=" + name + ", data=" + data + "]";
        }
    }

`


问:
Most simple button doesn't work
I have a really easy submit button in HTML, but it doesn't work.

main_page.html

<form class="main_page" method="POST" action=".">

         <input type="submit" name="invoer" value="Invoeren"/>

</form>
```

<p><strong>flask_app.py</strong></p>

```from flask import Flask, render_template, request

app = Flask(__name__)
app.config["DEBUG"] = True

@app.route("/", methods=["GET", "POST"])

def main():
    if request.method == "GET":
        return render_template("main_page.html")

    if request.form["invoer"] == "POST":
        return render_template("main_page.html")
```

When I click on the button, it shows me this:

------------------------------------------------------------------------------------------------------------------------------------

I already made a button like this before but then it worked, maybe I did something different. What should I do?

答:
The error is showing that ValueError: View function did not return a response, it means your POST didn't return any response to template when you click submit button in HTML. Chagne your code flask_app.py to:

```<code>from flask import Flask, render_template, request

app = Flask(__name__)
app.config["DEBUG"] = True

@app.route("/", methods=["GET", "POST"])

def main():
    if request.method == "GET":
        return render_template("main_page.html")

    if request.method == "POST": # change code here
        return render_template("main_page.html")
</code>```

This will make it works, however, it will return just the same template.

Title: Most simple button doesn't work

Body:
I have a really easy submit button in HTML, but it doesn't work.

main_page.html

<form class="main_page" method="POST" action=".">

         <input type="submit" name="invoer" value="Invoeren"/>

</form>

flask_app.py

from flask import Flask, render_template, request

app = Flask(__name__)
app.config["DEBUG"] = True

@app.route("/", methods=["GET", "POST"])

def main():
    if request.method == "GET":
        return render_template("main_page.html")

    if request.form["invoer"] == "POST":
        return render_template("main_page.html")

When I click on the button, it shows me this:

------------------------------------------------------------------------------------------------------------------------------------

I already made a button like this before but then it worked, maybe I did something different. What should I do?

Body:
The error is showing that ValueError: View function did not return a response, it means your POST didn't return any response to template when you click submit button in HTML. Chagne your code flask_app.py to:

from flask import Flask, render_template, request

app = Flask(__name__)
app.config["DEBUG"] = True

@app.route("/", methods=["GET", "POST"])

def main():
    if request.method == "GET":
        return render_template("main_page.html")

    if request.method == "POST": # change code here
        return render_template("main_page.html")

This will make it works, however, it will return just the same template.


问:
How to compare elements of two arrays in assembly?
I need to solve the following problem:

I need to put 4 arrays in memory, each array has 10 numbers which are the size of one byte.

Now, I need to find the way to check if any of the numbers from one string have a pair in another string and if they do I need to put those answers on to stack.

This is what I did so far:

```<code>arr1 db 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
arr2 db 2, 11, 12, 13, 14, 15, 16, 17, 18, 19
arr3 db 1, 20, 21, 22, 23, 24, 25, 26, 27, 28
arr4 db 1, 29, 30, 31, 32, 33, 34, 35, 36, 37

lea si, arr1
lea di, arr2
mov al, 0
mov bl, 0

mov cx, 10
loopOne:
    loopTwo:
        cmp [si+al],[di+bl]
        je done
        inc al
        loop loopTwo
    inc bl
    mov al, 0
loop loopOne
done:
mov dl, si+al
inc 21h
ret
</code>```

I'm using emu8086.

EDIT:

This is how it'd look like in Java:

```<code>public class Main {

    public static void main(String[] args) {

        int[] arr1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] arr2 = { 1, 11, 12, 13, 14, 15, 16, 17, 18, 19};
        int[] arr3 = { 1, 20, 21, 22, 23, 24, 25, 26, 27, 28};
        int[] arr4 =  { 1, 29, 30, 31, 32, 33, 34, 35, 36, 37 };
        int a = 0; //counter of matches in every pair of arrays
        for (int i = 0; i < arr1.length ; i++) {
            for( int j = 0; j < arr2.length ; j++){
                if( arr1[i] == arr2[j]){
                    a++;
                }
            }
        }
        //instead of printing, the number of matches ( a ) should be pushed on to stack
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr1.length ; i++) {
            for( int j = 0; j < arr3.length ; j++){
                if( arr1[i] == arr3[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr1.length ; i++) {
            for( int j = 0; j < arr4.length ; j++){
                if( arr1[i] == arr4[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr2.length ; i++) {
            for( int j = 0; j < arr3.length ; j++){
                if( arr2[i] == arr3[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr2.length ; i++) {
            for( int j = 0; j < arr4.length ; j++){
                if( arr2[i] == arr4[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr3.length ; i++) {
            for( int j = 0; j < arr4.length ; j++){
                if( arr3[i] == arr4[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;

    }

}
</code>```

答:
LOOP is designed for small and simple loops. Things become complicated when it is used for longer calculations or for nested loops.  I suggest to avoid LOOP in those cases.

cmp [si+al],[di+bl] is wrong. You cannot compare two values in memory in this way. The so called string operations (scas, movs, cmps) are uncomfortable to handle in a 16-bit environment (MS-DOS) and especially for this task. Furthermore, you cannot add a WORD (si) and a BYTE (bl).

I figured out the first comparison (arr1/arr2) for you and hope you can add the remaining comparisons by yourself.

```<code>.MODEL small
.STACK

include "emu8086.inc"

.DATA
    arr1 db 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    arr2 db 2, 11, 12, 13, 14, 15, 16, 17, 18, 19
    arr3 db 1, 20, 21, 22, 23, 24, 25, 26, 27, 28
    arr4 db 1, 29, 30, 31, 32, 33, 34, 35, 36, 37

.CODE
define_print_num_uns            ; emu8086.inc

start:
    mov ax, @data               ; Initialize DS
    mov ds, ax

    ; Compare arr1 and arr2
    lea si, arr1                ; Reset pointer to arr1
    mov cl, 10                  ; Length of arr1 = loop counter for loopOne
    mov bx, 0                   ; Counter for matches
    loopOne:                    ; Loop through arr1
        mov al, [si]            ; Load one element of arr1
        lea di, arr2            ; Reset pointer to arr2
        mov ch, 10              ; Length of arr2 = loop counter for loopTwo
        loopTwo:                ; Loop through arr2
            mov ah, [di]        ; Load one element of arr2
            cmp al, ah          ; Compare it
            jne @1              ; Skip the next line if no match
            inc bx              ; Increment match counter
            @1:
            inc di              ; Next element in arr2
            dec ch              ; Decrement loop counter
            jne loopTwo         ; Loop - break if CH == 0
        inc si                  ; Next elemnt in arr1
        dec cl                  ; Decrement loop counter
        jne loopOne             ; Loop - break if CL == 0
    mov ax, bx                  ; match counter into AX for print_num_uns
    call print_num_uns          ; emu8086.inc

    mov ax, 4C00h               ; MS-DOS function 4C: Exit program
    int 21h                     ; Call MS-DOS

end start
</code>```

Body:
I need to solve the following problem:

I need to put 4 arrays in memory, each array has 10 numbers which are the size of one byte.

Now, I need to find the way to check if any of the numbers from one string have a pair in another string and if they do I need to put those answers on to stack.

This is what I did so far:

arr1 db 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
arr2 db 2, 11, 12, 13, 14, 15, 16, 17, 18, 19
arr3 db 1, 20, 21, 22, 23, 24, 25, 26, 27, 28
arr4 db 1, 29, 30, 31, 32, 33, 34, 35, 36, 37

lea si, arr1
lea di, arr2
mov al, 0
mov bl, 0

mov cx, 10
loopOne:
    loopTwo:
        cmp [si+al],[di+bl]
        je done
        inc al
        loop loopTwo
    inc bl
    mov al, 0
loop loopOne
done:
mov dl, si+al
inc 21h
ret

I'm using emu8086.

EDIT:

This is how it'd look like in Java:

public class Main {

    public static void main(String[] args) {

        int[] arr1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] arr2 = { 1, 11, 12, 13, 14, 15, 16, 17, 18, 19};
        int[] arr3 = { 1, 20, 21, 22, 23, 24, 25, 26, 27, 28};
        int[] arr4 =  { 1, 29, 30, 31, 32, 33, 34, 35, 36, 37 };
        int a = 0; //counter of matches in every pair of arrays
        for (int i = 0; i < arr1.length ; i++) {
            for( int j = 0; j < arr2.length ; j++){
                if( arr1[i] == arr2[j]){
                    a++;
                }
            }
        }
        //instead of printing, the number of matches ( a ) should be pushed on to stack
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr1.length ; i++) {
            for( int j = 0; j < arr3.length ; j++){
                if( arr1[i] == arr3[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr1.length ; i++) {
            for( int j = 0; j < arr4.length ; j++){
                if( arr1[i] == arr4[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr2.length ; i++) {
            for( int j = 0; j < arr3.length ; j++){
                if( arr2[i] == arr3[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr2.length ; i++) {
            for( int j = 0; j < arr4.length ; j++){
                if( arr2[i] == arr4[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;
        for (int i = 0; i < arr3.length ; i++) {
            for( int j = 0; j < arr4.length ; j++){
                if( arr3[i] == arr4[j]){
                    a++;
                }
            }
        }
        System.out.println("Number of matches: " + a);
        a = 0;

    }

}

Body:
LOOP is designed for small and simple loops. Things become complicated when it is used for longer calculations or for nested loops.  I suggest to avoid LOOP in those cases.

cmp [si+al],[di+bl] is wrong. You cannot compare two values in memory in this way. The so called string operations (scas, movs, cmps) are uncomfortable to handle in a 16-bit environment (MS-DOS) and especially for this task. Furthermore, you cannot add a WORD (si) and a BYTE (bl).

I figured out the first comparison (arr1/arr2) for you and hope you can add the remaining comparisons by yourself.

.MODEL small
.STACK

include "emu8086.inc"

.DATA
    arr1 db 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    arr2 db 2, 11, 12, 13, 14, 15, 16, 17, 18, 19
    arr3 db 1, 20, 21, 22, 23, 24, 25, 26, 27, 28
    arr4 db 1, 29, 30, 31, 32, 33, 34, 35, 36, 37

.CODE
define_print_num_uns            ; emu8086.inc

start:
    mov ax, @data               ; Initialize DS
    mov ds, ax

    ; Compare arr1 and arr2
    lea si, arr1                ; Reset pointer to arr1
    mov cl, 10                  ; Length of arr1 = loop counter for loopOne
    mov bx, 0                   ; Counter for matches
    loopOne:                    ; Loop through arr1
        mov al, [si]            ; Load one element of arr1
        lea di, arr2            ; Reset pointer to arr2
        mov ch, 10              ; Length of arr2 = loop counter for loopTwo
        loopTwo:                ; Loop through arr2
            mov ah, [di]        ; Load one element of arr2
            cmp al, ah          ; Compare it
            jne @1              ; Skip the next line if no match
            inc bx              ; Increment match counter
            @1:
            inc di              ; Next element in arr2
            dec ch              ; Decrement loop counter
            jne loopTwo         ; Loop - break if CH == 0
        inc si                  ; Next elemnt in arr1
        dec cl                  ; Decrement loop counter
        jne loopOne             ; Loop - break if CL == 0
    mov ax, bx                  ; match counter into AX for print_num_uns
    call print_num_uns          ; emu8086.inc

    mov ax, 4C00h               ; MS-DOS function 4C: Exit program
    int 21h                     ; Call MS-DOS

end start


问:
Android Studio 3 + Gradle 4.0 + shrinkResources + libraryProject = Unable to find a matching configuration in project
I've problems to migrate my project to the newest Gradle 4.0 + Android Studio 3 version, which gives me all kind of errors. Little by little I managed to sort them all out except this one.

```<code>    Could not resolve all dependencies for configuration ':app:forGoogleCoverageRuntimeClasspath'.
   > Unable to find a matching configuration in project :mylibrary:
       - Configuration 'debugApiElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=coverage}' and found incompatible value 'BuildTypeAttr{name=debug}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=debug}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found incompatible value 'for compile'.
           - Required store 'ProductFlavorAttr{name=forGoogle}' but no value provided.
       - Configuration 'debugRuntimeElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=coverage}' and found incompatible value 'BuildTypeAttr{name=debug}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=debug}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found compatible value 'for runtime'.
           - Required store 'ProductFlavorAttr{name=forGoogle}' but no value provided.
       - Configuration 'releaseApiElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=coverage}' and found incompatible value 'BuildTypeAttr{name=release}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=release}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found incompatible value 'for compile'.
           - Required store 'ProductFlavorAttr{name=forGoogle}' but no value provided.
       - Configuration 'releaseRuntimeElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=coverage}' and found incompatible value 'BuildTypeAttr{name=release}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=release}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found compatible value 'for runtime'.
           - Required store 'ProductFlavorAttr{name=forGoogle}' but no value provided.
</code>```

In order to nail down the problem:

I've created a minimum app project from Android Studios project assistant

added an empty library module which I then add to my app dependencies.

added one flavorDimensions and 2 productFlavors

added 3 build types and let one build type inherit from another

let the inherited build type enable shrinkResources

The last step produces the mentioned error, which is similar to this question:
Gradle 4.0 Unable to find a matching configuration

Has anybody an idea what's the matter here or an solution to this problem? I'll file a bug report too.

My complete gradle file:

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "gradletest.test"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    flavorDimensions "store"

    productFlavors {
        forAmazon {
            dimension "store"
        }

        forGoogle {
            dimension "store"
        }
    }

    buildTypes {

        debug {
            debuggable true
            minifyEnabled false
        }

        release {
            minifyEnabled true
            debuggable false
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        coverage.initWith(buildTypes.debug)
        coverage {
            testCoverageEnabled true
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation project(':mylibrary')
}
</code>```

答:
Possible workaround is create in all modules missing buildTypes, but it's crazy messing code when Google planed create a sollution for it. More info in: https://issuetracker.google.com/issues/62170415 as me (but deleted by moderator) and you mention.

But there is second (same but much cleaner) solution:
add this to your top project build.gradle

```<code>subprojects {
    afterEvaluate {project ->
        if (project.hasProperty("android")) {
            android {
                buildTypes {
                    YOUR_MISSING_BUILD_TYPES {
                       BUILD_TYPE_PARAMS_OR_EMPTY
                    }
                }
            }
        }
    }
}
</code>```

EDIT: 2017-07-12

It's finally fixed in classpath 'com.android.tools.build:gradle:3.0.0-alpha6'.
You can use new DSL: https://issuetracker.google.com/issues/62241369

```<code>android {
  buildTypeMatching 'staging', 'debug'
  productFlavorMatching 'color', 'blue', 'cyan'
}
</code>```

Don't forgot to remove above workaround before build project!

EDIT: 2017-07-18

There is official documentation: https://issuetracker.google.com/issues/62241369

To resolve this error, you need to specify which build type from
  "mylibrary" the Android plugin should match to the app's "staging"
  build type. You can do this with the buildTypeMatching property in the
  app's build.gradle file, as shown below:

```<code>// Add the following to the consumer's build.gradle file.
android {
    ...
    // Tells the Android plugin to use a library's 'debug' build type
    // when a 'staging' build type is not available. You can include
    // additional build types, and the plugin matches 'staging' to the
    // first build type it finds from the one's you specify. That is,
    // if 'mylibrary' doesn't include a 'debug' build type either, the
    // plugin matches 'staging' with the producer's 'release' build type.
    buildTypeMatching 'staging', 'debug', 'release'
}
</code>```

EDIT: 2017-09-06

buildTypeMatching has been removed from AS beta 4.

now use matchingFallbacks.

see: https://stackoverflow.com/a/46038946/4594990

Body:
I've problems to migrate my project to the newest Gradle 4.0 + Android Studio 3 version, which gives me all kind of errors. Little by little I managed to sort them all out except this one.

    Could not resolve all dependencies for configuration ':app:forGoogleCoverageRuntimeClasspath'.
   > Unable to find a matching configuration in project :mylibrary:
       - Configuration 'debugApiElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=coverage}' and found incompatible value 'BuildTypeAttr{name=debug}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=debug}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found incompatible value 'for compile'.
           - Required store 'ProductFlavorAttr{name=forGoogle}' but no value provided.
       - Configuration 'debugRuntimeElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=coverage}' and found incompatible value 'BuildTypeAttr{name=debug}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=debug}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found compatible value 'for runtime'.
           - Required store 'ProductFlavorAttr{name=forGoogle}' but no value provided.
       - Configuration 'releaseApiElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=coverage}' and found incompatible value 'BuildTypeAttr{name=release}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=release}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found incompatible value 'for compile'.
           - Required store 'ProductFlavorAttr{name=forGoogle}' but no value provided.
       - Configuration 'releaseRuntimeElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=coverage}' and found incompatible value 'BuildTypeAttr{name=release}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=release}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found compatible value 'for runtime'.
           - Required store 'ProductFlavorAttr{name=forGoogle}' but no value provided.

In order to nail down the problem:

I've created a minimum app project from Android Studios project assistant

added an empty library module which I then add to my app dependencies.

added one flavorDimensions and 2 productFlavors

added 3 build types and let one build type inherit from another

let the inherited build type enable shrinkResources

The last step produces the mentioned error, which is similar to this question:
Gradle 4.0 Unable to find a matching configuration

Has anybody an idea what's the matter here or an solution to this problem? I'll file a bug report too.

My complete gradle file:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "gradletest.test"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    flavorDimensions "store"

    productFlavors {
        forAmazon {
            dimension "store"
        }

        forGoogle {
            dimension "store"
        }
    }

    buildTypes {

        debug {
            debuggable true
            minifyEnabled false
        }

        release {
            minifyEnabled true
            debuggable false
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        coverage.initWith(buildTypes.debug)
        coverage {
            testCoverageEnabled true
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation project(':mylibrary')
}

Body:
Possible workaround is create in all modules missing buildTypes, but it's crazy messing code when Google planed create a sollution for it. More info in: https://issuetracker.google.com/issues/62170415 as me (but deleted by moderator) and you mention.

But there is second (same but much cleaner) solution:
add this to your top project build.gradle

subprojects {
    afterEvaluate {project ->
        if (project.hasProperty("android")) {
            android {
                buildTypes {
                    YOUR_MISSING_BUILD_TYPES {
                       BUILD_TYPE_PARAMS_OR_EMPTY
                    }
                }
            }
        }
    }
}

EDIT: 2017-07-12

It's finally fixed in classpath 'com.android.tools.build:gradle:3.0.0-alpha6'.
You can use new DSL: https://issuetracker.google.com/issues/62241369

android {
  buildTypeMatching 'staging', 'debug'
  productFlavorMatching 'color', 'blue', 'cyan'
}

Don't forgot to remove above workaround before build project!

EDIT: 2017-07-18

There is official documentation: https://issuetracker.google.com/issues/62241369

To resolve this error, you need to specify which build type from
  "mylibrary" the Android plugin should match to the app's "staging"
  build type. You can do this with the buildTypeMatching property in the
  app's build.gradle file, as shown below:

// Add the following to the consumer's build.gradle file.
android {
    ...
    // Tells the Android plugin to use a library's 'debug' build type
    // when a 'staging' build type is not available. You can include
    // additional build types, and the plugin matches 'staging' to the
    // first build type it finds from the one's you specify. That is,
    // if 'mylibrary' doesn't include a 'debug' build type either, the
    // plugin matches 'staging' with the producer's 'release' build type.
    buildTypeMatching 'staging', 'debug', 'release'
}

EDIT: 2017-09-06

buildTypeMatching has been removed from AS beta 4.

now use matchingFallbacks.

see: https://stackoverflow.com/a/46038946/4594990


问:
SQL Query to check if student1 has a course with student 2
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

```
Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)
```

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?

答:
```<code>SELECT COUNT(*) > 0 FROM jos_gj_users WHERE id_user=54321 AND id_group IN ( SELECT id_group FROM jos_gj_users WHERE id_user = 1345 )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?


问:
How to make module (such as bcrypt) available globally in Express?
I have several "routes" files where I import modules like this:

```<code>var bcrypt = require('bcryptjs');
</code>```

I have attempted to make bcrypt available globally by importing it into my main app js and then using an app.use() something like this:

```<code>var bcrypt = require('bcryptjs');
app.use(bcrypt); // clearly not right, app crashes
</code>```

I've tried a variety of things here. Should I just stick with importing this into every file separately or is there a good way to make this module available globally?

答:
app.use will only work with an Express middleware, which bcrypt is not, it's just a regular Node.js module.

As was pointed out in the comments, there is not really any reason why you shouldn't just use require to make bcrypt available in any module that needs it.

For what it's worth, you can use the globally available variable global to create a global variable in Node.js.

In your example, it would be used like this (but again, this is NOT RECOMMENDED):

```<code>var bcrypt = require('bcryptjs');
global.bcrypt = bcrypt;
</code>```

Body:
I have several "routes" files where I import modules like this:

var bcrypt = require('bcryptjs');

I have attempted to make bcrypt available globally by importing it into my main app js and then using an app.use() something like this:

var bcrypt = require('bcryptjs');
app.use(bcrypt); // clearly not right, app crashes

I've tried a variety of things here. Should I just stick with importing this into every file separately or is there a good way to make this module available globally?

Body:
app.use will only work with an Express middleware, which bcrypt is not, it's just a regular Node.js module.

As was pointed out in the comments, there is not really any reason why you shouldn't just use require to make bcrypt available in any module that needs it.

For what it's worth, you can use the globally available variable global to create a global variable in Node.js.

In your example, it would be used like this (but again, this is NOT RECOMMENDED):

var bcrypt = require('bcryptjs');
global.bcrypt = bcrypt;


问:
MVC Model Duplication in C#
I have a need for models that are mapped to their corresponding data tables, and every time the models/tables are updated, I need to mapped the changes to the archived tables for historical references. For example -

```<code>[Table("A")]
public class A
{
    [Key]
    public int A_Id { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

[Table("A_History")]
public class A_History
{
    [Key]
    public int A_History_Id { get; set; }

    public int A_Id { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}
</code>```

So every time Table A is modified, I need to add an entry to A_History with an exact copy of the new or original data. Is there a generic way to do this, such that I can pass in a string as the Model name to a method or class, and the method can automatically loop through all the properties of the Model class, and map them to another class to be added by matching the names?

答:
Below uses reflection, so be careful of performance. If performance is a very important aspect then it might be better to actually map properties one by one, but if you're looking at generic implementation you could try the below snippet.</p>

```<code>// object instances
A sourceInstance = new A();
A_History destInstance = new A_History();
MapSourceValuesToDestination(sourceInstance, destInstance);

private void MapSourceValuesToDestination(object sourceObject, object destinationObject)
{
    //get all properties
    PropertyInfo[] sourceProperties = typeof (sourceObject).GetProperties();
    PropertyInfo[] destinationProperties = typeof (destinationObject).GetProperties();

    // foreach in source
    foreach (PropertyInfo property in sourceProperties)
    {
        if (property != null)
        {
            string propertyName = property.Name;
            if (!string.IsNullOrEmpty(propertyName))
            {
                // get destination property matched by name
                PropertyInfo matchingProperty = destinationProperties.FirstOrDefault(x => x.Name.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase));
                if (matchingProperty != null)
                {
                    // get source value
                    object sourceValue = property.GetValue(sourceInstance);
                    if (sourceValue != null)
                    {
                        // set source value to destination
                        matchingProperty.SetValue(destInstance, sourceValue);
                    }
                }
            }
        }
    }
}
</code>```

Title: MVC Model Duplication in C#

Body:
I have a need for models that are mapped to their corresponding data tables, and every time the models/tables are updated, I need to mapped the changes to the archived tables for historical references. For example -

[Table("A")]
public class A
{
    [Key]
    public int A_Id { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

[Table("A_History")]
public class A_History
{
    [Key]
    public int A_History_Id { get; set; }

    public int A_Id { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

So every time Table A is modified, I need to add an entry to A_History with an exact copy of the new or original data. Is there a generic way to do this, such that I can pass in a string as the Model name to a method or class, and the method can automatically loop through all the properties of the Model class, and map them to another class to be added by matching the names?

Body:
Below uses reflection, so be careful of performance. If performance is a very important aspect then it might be better to actually map properties one by one, but if you're looking at generic implementation you could try the below snippet.

// object instances
A sourceInstance = new A();
A_History destInstance = new A_History();
MapSourceValuesToDestination(sourceInstance, destInstance);

private void MapSourceValuesToDestination(object sourceObject, object destinationObject)
{
    //get all properties
    PropertyInfo[] sourceProperties = typeof (sourceObject).GetProperties();
    PropertyInfo[] destinationProperties = typeof (destinationObject).GetProperties();

    // foreach in source
    foreach (PropertyInfo property in sourceProperties)
    {
        if (property != null)
        {
            string propertyName = property.Name;
            if (!string.IsNullOrEmpty(propertyName))
            {
                // get destination property matched by name
                PropertyInfo matchingProperty = destinationProperties.FirstOrDefault(x => x.Name.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase));
                if (matchingProperty != null)
                {
                    // get source value
                    object sourceValue = property.GetValue(sourceInstance);
                    if (sourceValue != null)
                    {
                        // set source value to destination
                        matchingProperty.SetValue(destInstance, sourceValue);
                    }
                }
            }
        }
    }
}


问:
In R: how to sum a variable by group between two dates
I have two data frames (DF1 and DF2):

(1) DF1 contains information on individual-level, i.e. on 10.000 individuals nested in 30 units across 11 years (2000-2011). It contains four variables:

"individual" (numeric id for each individual; ranging from 1-10.000)

"unit" (numeric id for each unit; ranging from 1-30)

"date1" (a date in date format, i.e. 2000-01-01, etc; ranging from 2000-01-01 to 2010-12-31)

"date2" ("Date1" + 1 year)

(2) DF2 contains information on unit-level, i.e. on the same 30 units as in DF1 across the same time period (2000-2011) and further contains a numeric variable ("x"):

"unit" (numeric id for each unit; ranging from 1-30)

"date" (a date in date format, i.e. 2000-01-01, etc; ranging from 2000-01-01 to 2011-12-31)

"x" (a numeric variable, ranging from 0 to 200)

I would like to create new variable ("newvar") that gives me for each "individual" per "unit" the sum of "x" (DF2) counting from "date1" (DF1) to "date2" (DF2). This means that I would like to add this new variable to DF1.

For instance, if "individual"=1 in "unit"=1 has "date1"=2000-01-01 and "date2"=2001-01-01, and in DF2 "unit"=1 has three observations in the time period "date1" to "date2" (i.e. 2000-01-01 to 2001-01-01) with "x"=1, "x"=2 and "x"=3, then I would like add a new variable that gives for "individual"=1 in "unit"=1 "newvar"=6.

I assume that I need to use a for loop in R and have been using the following code:

```<code>for(i in length(DF1)){

DF1$newvar[i] <-sum(DF2$x[which(DF1$date == DF1$date1[i] &
                     DF1$date == DF1P$date1[i] &
                     DF2$unit == DF1P$unit[i]),])
</code>```

}

but get the error message:

```<code>Error in DF2$x[which(DF2$date ==  : incorrect number of dimensions
</code>```

Any ideas of how to create this variable would be tremendously appreciated!

Here is a small example as well as the expected output, using one unit for the sake of simplicity:

Assume DF1 looks as follows:

```<code>individual  unit  date1        date2
1           1     2000-01-01   2001-01-01
2           1     2000-02-02   2001-02-02
3           1     2000-03-03   2000-03-03
4           1     2000-04-04   2000-04-04
5           1     2000-12-31   2001-12-31
(...)
996         1     2010-01-01   2011-01-01
997         1     2010-02-15   2011-02-15
998         1     2010-03-05   2011-03-05
999         1     2010-04-10   2011-04-10
1000        1     2010-12-27  2011-12-27
1001        2     2000-01-01   2001-01-01
1002        2     2000-02-02   2001-02-02
1003        2     2000-03-03   2000-03-03
1004        2     2000-04-04   2000-04-04
1005        2     2000-12-31   2001-12-31
(...)
1996        2     2010-01-01   2011-01-01
1997        2     2010-02-15   2011-02-15
1998        2     2010-03-05   2011-03-05
1999        2     2010-04-10   2011-04-10
2000        2     2010-12-027  2011-12-27
(...)
3000        34    2000-02-02   2002-02-02
3001        34    2000-05-05   2001-05-05
3002        34    2000-06-06   2001-06-06
3003        34    2000-07-07   2001-07-07
3004        34    2000-11-11   2001-11-11
(...)
9996        34    2010-02-06   2011-02-06
9997        34    2010-05-05   2011-05-05
9998        34    2010-09-09   2011-09-09
9999        34    2010-09-25   2011-09-25
10000       34    2010-10-15   2011-10-15
</code>```

Assume DF2 looks as follows:

```<code>unit      date         x
1         2000-01-01   1
1         2000-05-01   2
1         2000-12-01   3
1         2001-01-02   10
1         2001-07-05   20
1         2001-12-31   30
(...)
2         2010-05-05   1
2         2010-07-01   1
2         2010-08-09   1
3         (...)
</code>```

This is what I would like DF1 to look like after running the code:

```<code>individual  unit      date1        date2        newvar
    1           1     2000-01-01   2001-01-01   6
    2           1     2000-02-02   2001-02-02   16
    3           1     2000-03-03   2001-03-03   15
    4           1     2000-04-04   2001-04-04   15
    5           1     2000-12-31   2001-12-31   60
    (...)
    996         1     2010-01-01   2011-01-01    3
    997         1     2010-02-15   2011-02-15    2
    998         1     2010-03-05   2011-03-05    2
    999         1     2010-04-10   2011-04-10    2
    1000        1     2010-12-27  2011-12-27     0
    (...)
</code>```

However, I cannot simply aggregate: Imagine that in DF1 each "unit" has several hundreds of individuals for each year between 2000 and 2011. And DF2 has many observations for each unit across the years 2000-2011.

答:
You were almost there, I just modified slightly your for loop, and also made sure that the date variables are considered as such:

```<code>DF1$date1 = as.Date(DF1$date1,"%Y-%m-%d")
DF1$date2 = as.Date(DF1$date2,"%Y-%m-%d")
DF2$date = as.Date(DF2$date,"%Y-%m-%d")

for(i in 1:nrow(DF1)){
  DF1$newvar[i] <-sum(DF2$x[which(DF2$unit == DF1$unit[i] &
                                  DF2$date>= DF1$date1[i] &
                                  DF2$date<= DF1$date2[i])])
}
</code>```

The problem was, that you were asking DF2$date to be simultaneously == DF1$date1 & DF1$date2.
And also, length(DF1) gives you the number of columns. To have the number of rows you can either use nrow(DF1), or dim(DF1)[1].

Body:
I have two data frames (DF1 and DF2):

(1) DF1 contains information on individual-level, i.e. on 10.000 individuals nested in 30 units across 11 years (2000-2011). It contains four variables:

"individual" (numeric id for each individual; ranging from 1-10.000)

"unit" (numeric id for each unit; ranging from 1-30)

"date1" (a date in date format, i.e. 2000-01-01, etc; ranging from 2000-01-01 to 2010-12-31)

"date2" ("Date1" + 1 year)

(2) DF2 contains information on unit-level, i.e. on the same 30 units as in DF1 across the same time period (2000-2011) and further contains a numeric variable ("x"):

"unit" (numeric id for each unit; ranging from 1-30)

"date" (a date in date format, i.e. 2000-01-01, etc; ranging from 2000-01-01 to 2011-12-31)

"x" (a numeric variable, ranging from 0 to 200)

I would like to create new variable ("newvar") that gives me for each "individual" per "unit" the sum of "x" (DF2) counting from "date1" (DF1) to "date2" (DF2). This means that I would like to add this new variable to DF1.

For instance, if "individual"=1 in "unit"=1 has "date1"=2000-01-01 and "date2"=2001-01-01, and in DF2 "unit"=1 has three observations in the time period "date1" to "date2" (i.e. 2000-01-01 to 2001-01-01) with "x"=1, "x"=2 and "x"=3, then I would like add a new variable that gives for "individual"=1 in "unit"=1 "newvar"=6.

I assume that I need to use a for loop in R and have been using the following code:

for(i in length(DF1)){

DF1$newvar[i] <-sum(DF2$x[which(DF1$date == DF1$date1[i] &
                     DF1$date == DF1P$date1[i] &
                     DF2$unit == DF1P$unit[i]),])

}

but get the error message:

Error in DF2$x[which(DF2$date ==  : incorrect number of dimensions

Any ideas of how to create this variable would be tremendously appreciated!

Here is a small example as well as the expected output, using one unit for the sake of simplicity:

Assume DF1 looks as follows:

individual  unit  date1        date2
1           1     2000-01-01   2001-01-01
2           1     2000-02-02   2001-02-02
3           1     2000-03-03   2000-03-03
4           1     2000-04-04   2000-04-04
5           1     2000-12-31   2001-12-31
(...)
996         1     2010-01-01   2011-01-01
997         1     2010-02-15   2011-02-15
998         1     2010-03-05   2011-03-05
999         1     2010-04-10   2011-04-10
1000        1     2010-12-27  2011-12-27
1001        2     2000-01-01   2001-01-01
1002        2     2000-02-02   2001-02-02
1003        2     2000-03-03   2000-03-03
1004        2     2000-04-04   2000-04-04
1005        2     2000-12-31   2001-12-31
(...)
1996        2     2010-01-01   2011-01-01
1997        2     2010-02-15   2011-02-15
1998        2     2010-03-05   2011-03-05
1999        2     2010-04-10   2011-04-10
2000        2     2010-12-027  2011-12-27
(...)
3000        34    2000-02-02   2002-02-02
3001        34    2000-05-05   2001-05-05
3002        34    2000-06-06   2001-06-06
3003        34    2000-07-07   2001-07-07
3004        34    2000-11-11   2001-11-11
(...)
9996        34    2010-02-06   2011-02-06
9997        34    2010-05-05   2011-05-05
9998        34    2010-09-09   2011-09-09
9999        34    2010-09-25   2011-09-25
10000       34    2010-10-15   2011-10-15

Assume DF2 looks as follows:

unit      date         x
1         2000-01-01   1
1         2000-05-01   2
1         2000-12-01   3
1         2001-01-02   10
1         2001-07-05   20
1         2001-12-31   30
(...)
2         2010-05-05   1
2         2010-07-01   1
2         2010-08-09   1
3         (...)

This is what I would like DF1 to look like after running the code:

individual  unit      date1        date2        newvar
    1           1     2000-01-01   2001-01-01   6
    2           1     2000-02-02   2001-02-02   16
    3           1     2000-03-03   2001-03-03   15
    4           1     2000-04-04   2001-04-04   15
    5           1     2000-12-31   2001-12-31   60
    (...)
    996         1     2010-01-01   2011-01-01    3
    997         1     2010-02-15   2011-02-15    2
    998         1     2010-03-05   2011-03-05    2
    999         1     2010-04-10   2011-04-10    2
    1000        1     2010-12-27  2011-12-27     0
    (...)

However, I cannot simply aggregate: Imagine that in DF1 each "unit" has several hundreds of individuals for each year between 2000 and 2011. And DF2 has many observations for each unit across the years 2000-2011.

Body:
You were almost there, I just modified slightly your for loop, and also made sure that the date variables are considered as such:

DF1$date1 = as.Date(DF1$date1,"%Y-%m-%d")
DF1$date2 = as.Date(DF1$date2,"%Y-%m-%d")
DF2$date = as.Date(DF2$date,"%Y-%m-%d")

for(i in 1:nrow(DF1)){
  DF1$newvar[i] <-sum(DF2$x[which(DF2$unit == DF1$unit[i] &
                                  DF2$date>= DF1$date1[i] &
                                  DF2$date<= DF1$date2[i])])
}

The problem was, that you were asking DF2$date to be simultaneously == DF1$date1 & DF1$date2.
And also, length(DF1) gives you the number of columns. To have the number of rows you can either use nrow(DF1), or dim(DF1)[1].


答:
You are sending to many parameters.

```<code>$insert = $db->prepare("INSERT INTO klant(naam, adres, postcode, email, password) values(:name, :adres, :postcode, :woonplaats, :email, :pass) ");
</code>```

You have the insert into " naam, adres, postcode, email and password" (that's 5)
And you are trying to insert 6 values.
 "Name, adres, postcode, woonplaats, email and pass.

Sorry for the poor formating, I am on mobile.

Title: Getting error PDO/SQL

Body:
I'm getting the following error

Link to DBconfig.php ->

Link to code ->

Can you guys please help me ;)

thank you!

My code ->

<?php
    include '../header.php';
    include '../dbconfig.php';

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

        $naam = $_POST['naam'];
        $email = $_POST['email'];
        $wachtwoord = $_POST['wachtwoord'];

        $insert = $db->prepare("INSERT INTO klant(naam, adres, postcode, email, password)
        values(:name, :adres, :postcode, :woonplaats, :email, :pass) ");

        $insert->bindParam(':naam',$naam);
        $insert->bindParam(':adres',$adres);
        $insert->bindParam(':postcode',$postcode);
        $insert->bindParam(':woonplaats',$woonplaats);
        $insert->bindParam(':email',$email);
        $insert->bindParam(':wachtwoord',$wachtwoord);

        $insert->execute();
    }
?>

Body:
You are sending to many parameters.

$insert = $db->prepare("INSERT INTO klant(naam, adres, postcode, email, password) values(:name, :adres, :postcode, :woonplaats, :email, :pass) ");

You have the insert into " naam, adres, postcode, email and password" (that's 5)
And you are trying to insert 6 values.
 "Name, adres, postcode, woonplaats, email and pass.

Sorry for the poor formating, I am on mobile.


答:
This is query that shows users from same groups.</p>

```<code>SELECT
  *
FROM
  jos_gj_users T1
  INNER JOIN jos_gj_users T2 ON T1.id_group = T2.id_group
</code>```

Title: SQL Query to check if student1 has a course with student 2

Body:
This is query that shows users from same groups.

SELECT
  *
FROM
  jos_gj_users T1
  INNER JOIN jos_gj_users T2 ON T1.id_group = T2.id_group


问:
$scope.$watch is not triggered when ng-model is undefined?
Problem:

I am trying to use $scope.$watch method over a ng-model used in a number input with strict attributes like, max, min, maxlength and step.

When the value inserted in the input exceeds any of those attributes, the ng-model retrieves undefined.

So, eventually, what happens is: $scope.$watch is triggered every time we change value in the input. Once the value is undefined, it will only be triggered again when the inserted value is again valid, in other words, following attribute rules (max, min, maxlength and step).

E.g.

user input: -2,4
-> $scope.$watch is triggered, and outputs, newValue as undefined.

user adds a new digit: -2,44
-> $scope.$watch is not triggered anymore, this way.

main.js

```<code>$scope.$watch("user.input.base.sphere", function(newValue, oldValue) {
console.log(newValue);
}
</code>```

**index.html

```<code><input
ng-cloak
type="number"
ng-class="user.settings.input.sphere.class"
autocomplete="off"
required
name="sphere"
id="in-sphere"
title="Sphere"
step="{{user.filter.sphere.step}}"
min="{{user.filter.sphere.min}}"
max="{{user.filter.sphere.max}}"
maxlength="{{user.filter.sphere.maxlength}}"
placeholder="{{user.filter.sphere.placeholder}}"
ng-model="user.input.base.sphere"
select-on-click
sphere>
</code>```

Question: How can I still let $scope.$watch to be triggered even over a undefined ng-model

答:
You can attach the following function to the ng-keyup directive. This function will get a reference to your form control and read the value that the user has typed in even though the value in the model has not yet been updated.

```<code>$scope.changeHandler = function (a) {
  var element = angular.element(document.querySelector('#in-sphere'))[0];
  console.log(element.value);
}
</code>```

Attach it to your form control with this:
ng-keyup='changeHandler()'

Here is a working plunker

Body:
Problem:

I am trying to use $scope.$watch method over a ng-model used in a number input with strict attributes like, max, min, maxlength and step.

When the value inserted in the input exceeds any of those attributes, the ng-model retrieves undefined.

So, eventually, what happens is: $scope.$watch is triggered every time we change value in the input. Once the value is undefined, it will only be triggered again when the inserted value is again valid, in other words, following attribute rules (max, min, maxlength and step).

E.g.

user input: -2,4
-> $scope.$watch is triggered, and outputs, newValue as undefined.

user adds a new digit: -2,44
-> $scope.$watch is not triggered anymore, this way.

main.js

$scope.$watch("user.input.base.sphere", function(newValue, oldValue) {
console.log(newValue);
}

**index.html

<input
ng-cloak
type="number"
ng-class="user.settings.input.sphere.class"
autocomplete="off"
required
name="sphere"
id="in-sphere"
title="Sphere"
step="{{user.filter.sphere.step}}"
min="{{user.filter.sphere.min}}"
max="{{user.filter.sphere.max}}"
maxlength="{{user.filter.sphere.maxlength}}"
placeholder="{{user.filter.sphere.placeholder}}"
ng-model="user.input.base.sphere"
select-on-click
sphere>

Question: How can I still let $scope.$watch to be triggered even over a undefined ng-model

Body:
You can attach the following function to the ng-keyup directive. This function will get a reference to your form control and read the value that the user has typed in even though the value in the model has not yet been updated.

$scope.changeHandler = function (a) {
  var element = angular.element(document.querySelector('#in-sphere'))[0];
  console.log(element.value);
}

Attach it to your form control with this:
ng-keyup='changeHandler()'

Here is a working plunker


问:
QT client doesn't download file when action is placed on button
Code in main.cpp

```<code>Client c;
c.start("ip-address", port, "final folder/file");
</code>```

It works and client downloads file I need.

But if I place same code in mainwindow.cpp on button click action

```<code>void MainWindow::on_btn_connect_clicked()
{
    Client c;
    c.start("ip-address", port, "final folder/file");
}
</code>```

it doesn't work. Why is that? I'm newbie at Qt and network coding. Some source code

```<code>void Client::start(QString address, qint16 port, QString file)
{
    qDebug() << "client started";
    QHostAddress addr(address);
    filename = file;
    client->connectToHost(addr, port);
    qDebug() << client->socketDescriptor();
}
</code>```

I have readyRead() but programm doesn't get there.

```<code>Client::Client(QObject *parent) :
    QObject(parent)
{
    client = new QTcpSocket(this);
    client->abort();
    connect(client, SIGNAL(readyRead()), this, SLOT(ReadData()));
    connect(client, SIGNAL(disconnected()), this, SLOT(Completed()));
}
</code>```

答: Did you connect the buttons clicked signal to the on_btn_connect slot?</p>

Body:
Code in main.cpp

Client c;
c.start("ip-address", port, "final folder/file");

It works and client downloads file I need.

But if I place same code in mainwindow.cpp on button click action

void MainWindow::on_btn_connect_clicked()
{
    Client c;
    c.start("ip-address", port, "final folder/file");
}

it doesn't work. Why is that? I'm newbie at Qt and network coding. Some source code

void Client::start(QString address, qint16 port, QString file)
{
    qDebug() << "client started";
    QHostAddress addr(address);
    filename = file;
    client->connectToHost(addr, port);
    qDebug() << client->socketDescriptor();
}

I have readyRead() but programm doesn't get there.

Client::Client(QObject *parent) :
    QObject(parent)
{
    client = new QTcpSocket(this);
    client->abort();
    connect(client, SIGNAL(readyRead()), this, SLOT(ReadData()));
    connect(client, SIGNAL(disconnected()), this, SLOT(Completed()));
}


问:
How can I write out correctly the download status in C# console app?
I have the following code, and it is working correctly except writing out the status of the download.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {

        static void clear()
        {

            Thread.Sleep(1500);
            Console.SetCursorPosition(0, 0);

        }

        static void Main(string[] args)
        {
            var client = new WebClient();

            client.DownloadProgressChanged += (o, e) =>
            {

                Console.Write(e.ProgressPercentage + "% ");
                clear();

            };

            client.DownloadFileAsync(new Uri("http://XXX"), "file");

            Console.ReadKey();

        }
    }
}
</code>```

With the code many new lines will be inserted and the status of the download will not be updated and printed out.

答:
In my case it works if you will handle DownloadFileCompleted event too.

```<code>client.DownloadFileCompleted += (e, s) =>
{
     Console.WriteLine("Completed!");
};
</code>```

And you should also use client.Dispose() or write your code in using statement:

```<code>using (WebClient client = new WebClient())
{
     // Code which uses WebClient
}
</code>```

This will automaticly dispose resources.

Edit:

As rene correctly noticed, there is no need in that case to use Dispose but generally it's good to remember that using statement is commonly used with IDisposible or IO operations.

Body:
I have the following code, and it is working correctly except writing out the status of the download.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {

        static void clear()
        {

            Thread.Sleep(1500);
            Console.SetCursorPosition(0, 0);

        }

        static void Main(string[] args)
        {
            var client = new WebClient();

            client.DownloadProgressChanged += (o, e) =>
            {

                Console.Write(e.ProgressPercentage + "% ");
                clear();

            };

            client.DownloadFileAsync(new Uri("http://XXX"), "file");

            Console.ReadKey();

        }
    }
}

With the code many new lines will be inserted and the status of the download will not be updated and printed out.

Body:
In my case it works if you will handle DownloadFileCompleted event too.

client.DownloadFileCompleted += (e, s) =>
{
     Console.WriteLine("Completed!");
};

And you should also use client.Dispose() or write your code in using statement:

using (WebClient client = new WebClient())
{
     // Code which uses WebClient
}

This will automaticly dispose resources.

Edit:

As rene correctly noticed, there is no need in that case to use Dispose but generally it's good to remember that using statement is commonly used with IDisposible or IO operations.