问:
AJAX autofill Cakephp 3 form
I am trying to auto fill defaults on my invoices form with customer data based off the customer selected in the drop down. Once the customer is selected in this drop down in the photo below I want it to auto fill the addresses from the data found in the customer table in the next photo below also.

So far this is my invoices add.ctp script to try fetch the data. Currently with this script I can fetch  the customer id that was selected to use in a sql query and also set data in the forms inputs

```<code><script>

            document.getElementById('customers').addEventListener('change',function(){
               alert(this.value);
            $('#customers').click(function(){
                $.ajax({
                    type: "POST",
                    url: '<?php echo Router::url(array('controller' => 'Customers', 'action' => 'fill')); ?>',
                    success: function(data){
                        alert(data);
                    }
                });
            });

            document.getElementById('name').value = "test"
            document.getElementById('invoice_to_address').value = "test"

            });

        </script>
</code>```

This is my fill function in my CustomersController. This is where I am going wrong I think my query is probably completely wrong and it's not searching for the right thing and returning it incorrectly and probably not even using the customer ID from the form. Currently it just returns no data but also has no errors and an empty alert box comes up due to the script in the view.

```<code> public function fill()
{
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    $data = array();

    $id = $this->request->data();
    $query = $this->Customers->find()
    ->where([
    'id' => $id]);

$this->set(array(
    'id' => $query,
    '_serialize' => 'id'
    ));

}
</code>```

UPDATE

My full Invoices add.ctp

```<code>    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<?php echo $this->Html->script('jquery.chained'); ?>
<script type="text/javascript">
    $(document).ready(function () {
        $("#contacts").chained("#customers");
    });
</script>
<?php use Cake\Routing\Router; ?>
<?php
/**
  * @var \App\View\AppView $this
  */
?>
<nav class="large-3 medium-4 columns" id="actions-sidebar">
    <ul class="side-nav">
        <li class="heading"><?= __('Actions') ?></li>
        <li><?= $this->Html->link(__('List Invoices'), ['action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('List Customers'), ['controller' => 'Customers', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Customer'), ['controller' => 'Customers', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Customer Contacts'), ['controller' => 'CustomerContacts', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Customer Contact'), ['controller' => 'CustomerContacts', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Aircraft Registrations'), ['controller' => 'AircraftRegistrations', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Aircraft Registration'), ['controller' => 'AircraftRegistrations', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Shipping Companies'), ['controller' => 'ShippingCompanies', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Shipping Company'), ['controller' => 'ShippingCompanies', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Job Types'), ['controller' => 'JobTypes', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Job Type'), ['controller' => 'JobTypes', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Currencies'), ['controller' => 'Currencies', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Currency'), ['controller' => 'Currencies', 'action' => 'add']) ?></li>
    </ul>
</nav>
<div class="invoices form large-9 medium-8 columns content">
    <?= $this->Form->create($invoice) ?>
    <fieldset>
        <legend><?= __('Add Invoice') ?></legend>
        <?php
            echo $this->Form->input('start_date', ['empty' => false]);
            echo $this->Form->input('close_date', ['empty' => true]);
            echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);
            echo $this->Form->input('name', ['type' => 'text', 'id'=>'name']);
            echo $this->Form->input('invoice_to_address', ['type' => 'text', 'id'=>'invoice_to_address']);
            echo $this->Form->input('ship_to_address');
            echo $this->Form->input('customer_contact_id', ['options' => $customerContacts, 'empty' => true,'id'=>'contacts']);
            echo $this->Form->input('currency_id', ['options' => $currencies, 'default'=> 1, 'id'=>'currencies']);
        ?>

    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
    <?= $this->Form->create(Null, ['type' => 'POST']) ?>
    <?= $this->Form->end() ?>
</div>

<script>
        jQuery('#name').autocomplete({source:'<?php echo Router::url(array('controller' => 'Customers', 'action' => 'search')); ?>'
        });
</script>

<script>
    document.getElementById('customers').addEventListener('change',function(){
       var id = this.value;
       alert(id);
        var csrfToken = $('[name=_csrfToken]').val();
        $.ajax({
            type: "POST",
            url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
            data: {'id' : id},
            beforeSend: function(xhr){
               xhr.setRequestHeader('X-CSRF-Token', csrfToken);
            },
            success: function(data){
                alert(data);
                data = JSON.parse(data);
                alert("id: " + data.id);
            }
        });
    document.getElementById('name').value = "test"
    document.getElementById('invoice_to_address').value = "test"
    document.getElementById('currencies').value = 3;
    });

</script>
</code>```

and the controller fill function

```<code>public function fill(){
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    if ($this->request->is('ajax')) {
        $id = $this->request->data['id'];
        $query = $this->Customers->find()
        ->where([
           'id' => $id
        ])->first();
        echo json_encode($query);
    }
}
</code>```

What happens when ($this->request->is('ajax')) is there. There's no response or preview.

When if ($this->request->is('ajax')) is removed.

Here is the full error message

```<code>{"id":0,"name":"Sky Works","country_id":1,"city_id":6,"address":"Sky works address in the customers table","postal_address":"Sky works shippng address in the customers table","phone":"","email":"","payment_terms_id":1,"stop_credit":false,"gst_percentage":null,"currency_id":"2","account_closed":false,"invoice_email":"","customer_notes":""}<pre class="cake-error"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8332d-trace').style.display = (document.getElementById('cakeErr5a1140bb8332d-trace').style.display == 'none' ? '' : 'none');"><b>Warning</b> (512)</a>: Unable to emit headers. Headers sent in file=/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php line=179 [<b>CORE/src/Http/ResponseEmitter.php</b>, line <b>48</b>]<div id="cakeErr5a1140bb8332d-trace" class="cake-stack-trace" style="display: none;"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8332d-code').style.display = (document.getElementById('cakeErr5a1140bb8332d-code').style.display == 'none' ? '' : 'none')">Code</a> <a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8332d-context').style.display = (document.getElementById('cakeErr5a1140bb8332d-context').style.display == 'none' ? '' : 'none')">Context</a><pre id="cakeErr5a1140bb8332d-code" class="cake-code-dump" style="display: none;"><code><span style="color: #000000"><span style="color: #0000BB">            $message </span><span style="color: #007700">= </span><span style="color: #DD0000">"Unable to emit headers. Headers sent in file=</span><span style="color: #0000BB">$file</span><span style="color: #DD0000"> line=</span><span style="color: #0000BB">$line</span><span style="color: #DD0000">"</span><span style="color: #007700">;</span></span></code>
<span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">            </span><span style="color: #007700">if (</span><span style="color: #0000BB">Configure</span><span style="color: #007700">::</span><span style="color: #0000BB">read</span><span style="color: #007700">(</span><span style="color: #DD0000">'debug'</span><span style="color: #007700">)) {</span></span></code></span>
<code><span style="color: #000000"><span style="color: #0000BB">                trigger_error</span><span style="color: #007700">(</span><span style="color: #0000BB">$message</span><span style="color: #007700">, </span><span style="color: #0000BB">E_USER_WARNING</span><span style="color: #007700">);</span></span></code>```
$response = object(Zend\Diactoros\Response) {
    [protected] headers => [
        'Content-Type' => [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames => [
        'content-type' => 'Content-Type'
    ]
    [private] phrases => [
        (int) 100 => 'Continue',
        (int) 101 => 'Switching Protocols',
        (int) 102 => 'Processing',
        (int) 200 => 'OK',
        (int) 201 => 'Created',
        (int) 202 => 'Accepted',
        (int) 203 => 'Non-Authoritative Information',
        (int) 204 => 'No Content',
        (int) 205 => 'Reset Content',
        (int) 206 => 'Partial Content',
        (int) 207 => 'Multi-status',
        (int) 208 => 'Already Reported',
        (int) 226 => 'IM used',
        (int) 300 => 'Multiple Choices',
        (int) 301 => 'Moved Permanently',
        (int) 302 => 'Found',
        (int) 303 => 'See Other',
        (int) 304 => 'Not Modified',
        (int) 305 => 'Use Proxy',
        (int) 306 => 'Switch Proxy',
        (int) 307 => 'Temporary Redirect',
        (int) 308 => 'Permanent Redirect',
        (int) 400 => 'Bad Request',
        (int) 401 => 'Unauthorized',
        (int) 402 => 'Payment Required',
        (int) 403 => 'Forbidden',
        (int) 404 => 'Not Found',
        (int) 405 => 'Method Not Allowed',
        (int) 406 => 'Not Acceptable',
        (int) 407 => 'Proxy Authentication Required',
        (int) 408 => 'Request Time-out',
        (int) 409 => 'Conflict',
        (int) 410 => 'Gone',
        (int) 411 => 'Length Required',
        (int) 412 => 'Precondition Failed',
        (int) 413 => 'Request Entity Too Large',
        (int) 414 => 'Request-URI Too Large',
        (int) 415 => 'Unsupported Media Type',
        (int) 416 => 'Requested range not satisfiable',
        (int) 417 => 'Expectation Failed',
        (int) 418 => 'I'm a teapot',
        (int) 421 => 'Misdirected Request',
        (int) 422 => 'Unprocessable Entity',
        (int) 423 => 'Locked',
        (int) 424 => 'Failed Dependency',
        (int) 425 => 'Unordered Collection',
        (int) 426 => 'Upgrade Required',
        (int) 428 => 'Precondition Required',
        (int) 429 => 'Too Many Requests',
        (int) 431 => 'Request Header Fields Too Large',
        (int) 444 => 'Connection Closed Without Response',
        (int) 451 => 'Unavailable For Legal Reasons',
        (int) 499 => 'Client Closed Request',
        (int) 500 => 'Internal Server Error',
        (int) 501 => 'Not Implemented',
        (int) 502 => 'Bad Gateway',
        (int) 503 => 'Service Unavailable',
        (int) 504 => 'Gateway Time-out',
        (int) 505 => 'HTTP Version not supported',
        (int) 506 => 'Variant Also Negotiates',
        (int) 507 => 'Insufficient Storage',
        (int) 508 => 'Loop Detected',
        (int) 510 => 'Not Extended',
        (int) 511 => 'Network Authentication Required',
        (int) 599 => 'Network Connect Timeout Error'
    ]
    [private] reasonPhrase => ''
    [private] statusCode => (int) 200
    [private] protocol => '1.1'
    [private] stream => object(Zend\Diactoros\Stream) {}
}
$maxBufferLength = (int) 8192
$file = '/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php'
$line = (int) 179
$message = 'Unable to emit headers. Headers sent in file=/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php line=179'```<pre class="stack-trace">Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 48
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37```
```<pre class="cake-error"><b>Warning</b> (2): Cannot modify header information - headers already sent by (output started at /home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php:179) [<b>CORE/src/Http/ResponseEmitter.php</b>, line <b>146</b>]<div id="cakeErr5a1140bb8392c-trace" class="cake-stack-trace" style="display: none;">Code Context<pre id="cakeErr5a1140bb8392c-code" class="cake-code-dump" style="display: none;"><code><span style="color: #000000"><span style="color: #0000BB">            $response</span><span style="color: #007700">-></span><span style="color: #0000BB">getStatusCode</span><span style="color: #007700">(),</span></span></code>
<span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">            </span><span style="color: #007700">(</span><span style="color: #0000BB">$reasonPhrase </span><span style="color: #007700">? </span><span style="color: #DD0000">' ' </span><span style="color: #007700">. </span><span style="color: #0000BB">$reasonPhrase </span><span style="color: #007700">: </span><span style="color: #DD0000">''</span><span style="color: #007700">)</span></span></code></span>
<code><span style="color: #000000"><span style="color: #0000BB">        </span><span style="color: #007700">));</span></span></code>```
$response = object(Zend\Diactoros\Response) {
    [protected] headers => [
        'Content-Type' => [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames => [
        'content-type' => 'Content-Type'
    ]
    [private] phrases => [
        (int) 100 => 'Continue',
        (int) 101 => 'Switching Protocols',
        (int) 102 => 'Processing',
        (int) 200 => 'OK',
        (int) 201 => 'Created',
        (int) 202 => 'Accepted',
        (int) 203 => 'Non-Authoritative Information',
        (int) 204 => 'No Content',
        (int) 205 => 'Reset Content',
        (int) 206 => 'Partial Content',
        (int) 207 => 'Multi-status',
        (int) 208 => 'Already Reported',
        (int) 226 => 'IM used',
        (int) 300 => 'Multiple Choices',
        (int) 301 => 'Moved Permanently',
        (int) 302 => 'Found',
        (int) 303 => 'See Other',
        (int) 304 => 'Not Modified',
        (int) 305 => 'Use Proxy',
        (int) 306 => 'Switch Proxy',
        (int) 307 => 'Temporary Redirect',
        (int) 308 => 'Permanent Redirect',
        (int) 400 => 'Bad Request',
        (int) 401 => 'Unauthorized',
        (int) 402 => 'Payment Required',
        (int) 403 => 'Forbidden',
        (int) 404 => 'Not Found',
        (int) 405 => 'Method Not Allowed',
        (int) 406 => 'Not Acceptable',
        (int) 407 => 'Proxy Authentication Required',
        (int) 408 => 'Request Time-out',
        (int) 409 => 'Conflict',
        (int) 410 => 'Gone',
        (int) 411 => 'Length Required',
        (int) 412 => 'Precondition Failed',
        (int) 413 => 'Request Entity Too Large',
        (int) 414 => 'Request-URI Too Large',
        (int) 415 => 'Unsupported Media Type',
        (int) 416 => 'Requested range not satisfiable',
        (int) 417 => 'Expectation Failed',
        (int) 418 => 'I'm a teapot',
        (int) 421 => 'Misdirected Request',
        (int) 422 => 'Unprocessable Entity',
        (int) 423 => 'Locked',
        (int) 424 => 'Failed Dependency',
        (int) 425 => 'Unordered Collection',
        (int) 426 => 'Upgrade Required',
        (int) 428 => 'Precondition Required',
        (int) 429 => 'Too Many Requests',
        (int) 431 => 'Request Header Fields Too Large',
        (int) 444 => 'Connection Closed Without Response',
        (int) 451 => 'Unavailable For Legal Reasons',
        (int) 499 => 'Client Closed Request',
        (int) 500 => 'Internal Server Error',
        (int) 501 => 'Not Implemented',
        (int) 502 => 'Bad Gateway',
        (int) 503 => 'Service Unavailable',
        (int) 504 => 'Gateway Time-out',
        (int) 505 => 'HTTP Version not supported',
        (int) 506 => 'Variant Also Negotiates',
        (int) 507 => 'Insufficient Storage',
        (int) 508 => 'Loop Detected',
        (int) 510 => 'Not Extended',
        (int) 511 => 'Network Authentication Required',
        (int) 599 => 'Network Connect Timeout Error'
    ]
    [private] reasonPhrase => 'OK'
    [private] statusCode => (int) 200
    [private] protocol => '1.1'
    [private] stream => object(Zend\Diactoros\Stream) {}
}
$reasonPhrase = 'OK'```<pre class="stack-trace">header - [internal], line ??
Cake\Http\ResponseEmitter::emitStatusLine() - CORE/src/Http/ResponseEmitter.php, line 146
Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 54
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37```
```<pre class="cake-error"><b>Warning</b> (2): Cannot modify header information - headers already sent by (output started at /home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php:179) [<b>CORE/src/Http/ResponseEmitter.php</b>, line <b>173</b>]<div id="cakeErr5a1140bb83ee9-trace" class="cake-stack-trace" style="display: none;">Code Context<pre id="cakeErr5a1140bb83ee9-code" class="cake-code-dump" style="display: none;"><code><span style="color: #000000"><span style="color: #0000BB">                    $name</span><span style="color: #007700">,</span></span></code>
<span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">                    $value</span></span></code></span>
<code><span style="color: #000000"><span style="color: #0000BB">                </span><span style="color: #007700">), </span><span style="color: #0000BB">$first</span><span style="color: #007700">);</span></span></code>```
$response = object(Zend\Diactoros\Response) {
    [protected] headers => [
        'Content-Type' => [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames => [
        'content-type' => 'Content-Type'
    ]
    [private] phrases => [
        (int) 100 => 'Continue',
        (int) 101 => 'Switching Protocols',
        (int) 102 => 'Processing',
        (int) 200 => 'OK',
        (int) 201 => 'Created',
        (int) 202 => 'Accepted',
        (int) 203 => 'Non-Authoritative Information',
        (int) 204 => 'No Content',
        (int) 205 => 'Reset Content',
        (int) 206 => 'Partial Content',
        (int) 207 => 'Multi-status',
        (int) 208 => 'Already Reported',
        (int) 226 => 'IM used',
        (int) 300 => 'Multiple Choices',
        (int) 301 => 'Moved Permanently',
        (int) 302 => 'Found',
        (int) 303 => 'See Other',
        (int) 304 => 'Not Modified',
        (int) 305 => 'Use Proxy',
        (int) 306 => 'Switch Proxy',
        (int) 307 => 'Temporary Redirect',
        (int) 308 => 'Permanent Redirect',
        (int) 400 => 'Bad Request',
        (int) 401 => 'Unauthorized',
        (int) 402 => 'Payment Required',
        (int) 403 => 'Forbidden',
        (int) 404 => 'Not Found',
        (int) 405 => 'Method Not Allowed',
        (int) 406 => 'Not Acceptable',
        (int) 407 => 'Proxy Authentication Required',
        (int) 408 => 'Request Time-out',
        (int) 409 => 'Conflict',
        (int) 410 => 'Gone',
        (int) 411 => 'Length Required',
        (int) 412 => 'Precondition Failed',
        (int) 413 => 'Request Entity Too Large',
        (int) 414 => 'Request-URI Too Large',
        (int) 415 => 'Unsupported Media Type',
        (int) 416 => 'Requested range not satisfiable',
        (int) 417 => 'Expectation Failed',
        (int) 418 => 'I'm a teapot',
        (int) 421 => 'Misdirected Request',
        (int) 422 => 'Unprocessable Entity',
        (int) 423 => 'Locked',
        (int) 424 => 'Failed Dependency',
        (int) 425 => 'Unordered Collection',
        (int) 426 => 'Upgrade Required',
        (int) 428 => 'Precondition Required',
        (int) 429 => 'Too Many Requests',
        (int) 431 => 'Request Header Fields Too Large',
        (int) 444 => 'Connection Closed Without Response',
        (int) 451 => 'Unavailable For Legal Reasons',
        (int) 499 => 'Client Closed Request',
        (int) 500 => 'Internal Server Error',
        (int) 501 => 'Not Implemented',
        (int) 502 => 'Bad Gateway',
        (int) 503 => 'Service Unavailable',
        (int) 504 => 'Gateway Time-out',
        (int) 505 => 'HTTP Version not supported',
        (int) 506 => 'Variant Also Negotiates',
        (int) 507 => 'Insufficient Storage',
        (int) 508 => 'Loop Detected',
        (int) 510 => 'Not Extended',
        (int) 511 => 'Network Authentication Required',
        (int) 599 => 'Network Connect Timeout Error'
    ]
    [private] reasonPhrase => 'OK'
    [private] statusCode => (int) 200
    [private] protocol => '1.1'
    [private] stream => object(Zend\Diactoros\Stream) {}
}
$name = 'Content-Type'
$values = [
    (int) 0 => 'text/html; charset=UTF-8'
]
$first = true
$value = 'text/html; charset=UTF-8'```<pre class="stack-trace">header - [internal], line ??
Cake\Http\ResponseEmitter::emitHeaders() - CORE/src/Http/ResponseEmitter.php, line 173
Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 55
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37```
```
</code>```

答:
Change:

```<code>$query = $this->Customers->find()->where(['id' => $id]);
</code>```

To:

```<code>$query = $this->Customers->find()->where(['id' => $id])->first();
</code>```

Also use "echo" in the controller to return the  data to ajax.

```<code>echo json_encode($query);
</code>```

Then json encoded data should be returned.

Edit:

Make sure you have created a form (to get csrf token) like this in the ctp file:

```<code><?= $this->Form->create(Null, ['type' => 'POST']) ?>
<?= $this->Form->end() ?>
</code>```

And add these lines to the javascript code:

```<code>beforeSend: function(xhr){
    xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
</code>```

And add "data" to javascript, like:

```<code>var id = 1; //Your ID. I don't know what ID it is, so I just use 1.
var csrfToken = $('[name=_csrfToken]').val(); //Sorry, I forgot this.
$.ajax({
    type: "POST",
    url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
    data: {'id' : id},
    beforeSend: function(xhr){
       xhr.setRequestHeader('X-CSRF-Token', csrfToken);
    },
    success: function(data){
        alert(data);
        data = JSON.parse(data);
        alert("id: " + data.id);
    }
});
</code>```

And change the controller:

```<code>public function fill(){
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    if ($this->request->is('ajax')) {
        $id = $this->request->data['id'];
        $query = $this->Customers->find()
        ->where([
           'id' => $id
        ])->first();
        echo json_encode($query);
    }
}
</code>```

Edit:

Maybe you are not using CsrfToken. In that case, you don't need to load CsrfToken.
Change the javascript code like this:

```<code><script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous">
  //jQuery CDN. If you have loaded jQuery somewhere else, you don't need this.
</script>
<script>
var id = 1; //Your ID. I don't know what ID it is, so I just use 1.
$.ajax({
    type: "POST",
    url: '<?= $this->Url->build(array("controller" => "Customers", "action" => "fill")); ?>',
    data: {'id' : id},
    success: function(data){
        alert(data);
        data = JSON.parse(data);
        alert("id: " + data.id);
    }
});
</script>
</code>```

With this javascript, I think you don't have to change the controller (you don't need to remove is('ajax').)

Edit

Maybe as you say, null is returned from the controller. But I want to check what the error message is. Please check it by the following way.

If succeeded, you get json string. You can change it to javascript's object after receiving it.

If failed, you can check it from the google chrome browser. It should show what error you get:

Or, maybe cakephp might return error message in html. In that case, you would receive this:

This is raw html code, so it might be hard to read.

Please let me know what error message you get..

Title: AJAX autofill Cakephp 3 form

Body:
I am trying to auto fill defaults on my invoices form with customer data based off the customer selected in the drop down. Once the customer is selected in this drop down in the photo below I want it to auto fill the addresses from the data found in the customer table in the next photo below also.

So far this is my invoices add.ctp script to try fetch the data. Currently with this script I can fetch  the customer id that was selected to use in a sql query and also set data in the forms inputs

This is my fill function in my CustomersController. This is where I am going wrong I think my query is probably completely wrong and it's not searching for the right thing and returning it incorrectly and probably not even using the customer ID from the form. Currently it just returns no data but also has no errors and an empty alert box comes up due to the script in the view.

 public function fill()
{
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    $data = array();

    $id = $this->request->data();
    $query = $this->Customers->find()
    ->where([
    'id' => $id]);

$this->set(array(
    'id' => $query,
    '_serialize' => 'id'
    ));

}

UPDATE

My full Invoices add.ctp

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

<?php echo $this->Html->script('jquery.chained'); ?>

<?php use Cake\Routing\Router; ?>
<?php
/**
  * @var \App\View\AppView $this
  */
?>

<?= __('Actions') ?>

<?= $this->Html->link(__('List Invoices'), ['action' => 'index']) ?>

<?= $this->Html->link(__('List Customers'), ['controller' => 'Customers', 'action' => 'index']) ?>

<?= $this->Html->link(__('New Customer'), ['controller' => 'Customers', 'action' => 'add']) ?>

<?= $this->Html->link(__('List Customer Contacts'), ['controller' => 'CustomerContacts', 'action' => 'index']) ?>

<?= $this->Html->link(__('New Customer Contact'), ['controller' => 'CustomerContacts', 'action' => 'add']) ?>

<?= $this->Html->link(__('List Aircraft Registrations'), ['controller' => 'AircraftRegistrations', 'action' => 'index']) ?>

<?= $this->Html->link(__('New Aircraft Registration'), ['controller' => 'AircraftRegistrations', 'action' => 'add']) ?>

<?= $this->Html->link(__('List Shipping Companies'), ['controller' => 'ShippingCompanies', 'action' => 'index']) ?>

<?= $this->Html->link(__('New Shipping Company'), ['controller' => 'ShippingCompanies', 'action' => 'add']) ?>

<?= $this->Html->link(__('List Job Types'), ['controller' => 'JobTypes', 'action' => 'index']) ?>

<?= $this->Html->link(__('New Job Type'), ['controller' => 'JobTypes', 'action' => 'add']) ?>

<?= $this->Html->link(__('List Currencies'), ['controller' => 'Currencies', 'action' => 'index']) ?>

<?= $this->Html->link(__('New Currency'), ['controller' => 'Currencies', 'action' => 'add']) ?>

    <?= $this->Form->create($invoice) ?>
    <fieldset>
        <legend><?= __('Add Invoice') ?></legend>
        <?php
            echo $this->Form->input('start_date', ['empty' => false]);
            echo $this->Form->input('close_date', ['empty' => true]);
            echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);
            echo $this->Form->input('name', ['type' => 'text', 'id'=>'name']);
            echo $this->Form->input('invoice_to_address', ['type' => 'text', 'id'=>'invoice_to_address']);
            echo $this->Form->input('ship_to_address');
            echo $this->Form->input('customer_contact_id', ['options' => $customerContacts, 'empty' => true,'id'=>'contacts']);
            echo $this->Form->input('currency_id', ['options' => $currencies, 'default'=> 1, 'id'=>'currencies']);
        ?>

    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
    <?= $this->Form->create(Null, ['type' => 'POST']) ?>
    <?= $this->Form->end() ?>

and the controller fill function

public function fill(){
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    if ($this->request->is('ajax')) {
        $id = $this->request->data['id'];
        $query = $this->Customers->find()
        ->where([
           'id' => $id
        ])->first();
        echo json_encode($query);
    }
}

What happens when ($this->request->is('ajax')) is there. There's no response or preview.

When if ($this->request->is('ajax')) is removed.

Here is the full error message

{"id":0,"name":"Sky Works","country_id":1,"city_id":6,"address":"Sky works address in the customers table","postal_address":"Sky works shippng address in the customers table","phone":"","email":"","payment_terms_id":1,"stop_credit":false,"gst_percentage":null,"currency_id":"2","account_closed":false,"invoice_email":"","customer_notes":""}
Warning (512): Unable to emit headers. Headers sent in file=/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php line=179 [CORE/src/Http/ResponseEmitter.php, line 48]
Code Context
            $message = "Unable to emit headers. Headers sent in file=$file line=$line";
            if (Configure::read('debug')) {
                trigger_error($message, E_USER_WARNING);

$response = object(Zend\Diactoros\Response) {
    [protected] headers => [
        'Content-Type' => [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames => [
        'content-type' => 'Content-Type'
    ]
    [private] phrases => [
        (int) 100 => 'Continue',
        (int) 101 => 'Switching Protocols',
        (int) 102 => 'Processing',
        (int) 200 => 'OK',
        (int) 201 => 'Created',
        (int) 202 => 'Accepted',
        (int) 203 => 'Non-Authoritative Information',
        (int) 204 => 'No Content',
        (int) 205 => 'Reset Content',
        (int) 206 => 'Partial Content',
        (int) 207 => 'Multi-status',
        (int) 208 => 'Already Reported',
        (int) 226 => 'IM used',
        (int) 300 => 'Multiple Choices',
        (int) 301 => 'Moved Permanently',
        (int) 302 => 'Found',
        (int) 303 => 'See Other',
        (int) 304 => 'Not Modified',
        (int) 305 => 'Use Proxy',
        (int) 306 => 'Switch Proxy',
        (int) 307 => 'Temporary Redirect',
        (int) 308 => 'Permanent Redirect',
        (int) 400 => 'Bad Request',
        (int) 401 => 'Unauthorized',
        (int) 402 => 'Payment Required',
        (int) 403 => 'Forbidden',
        (int) 404 => 'Not Found',
        (int) 405 => 'Method Not Allowed',
        (int) 406 => 'Not Acceptable',
        (int) 407 => 'Proxy Authentication Required',
        (int) 408 => 'Request Time-out',
        (int) 409 => 'Conflict',
        (int) 410 => 'Gone',
        (int) 411 => 'Length Required',
        (int) 412 => 'Precondition Failed',
        (int) 413 => 'Request Entity Too Large',
        (int) 414 => 'Request-URI Too Large',
        (int) 415 => 'Unsupported Media Type',
        (int) 416 => 'Requested range not satisfiable',
        (int) 417 => 'Expectation Failed',
        (int) 418 => 'I'm a teapot',
        (int) 421 => 'Misdirected Request',
        (int) 422 => 'Unprocessable Entity',
        (int) 423 => 'Locked',
        (int) 424 => 'Failed Dependency',
        (int) 425 => 'Unordered Collection',
        (int) 426 => 'Upgrade Required',
        (int) 428 => 'Precondition Required',
        (int) 429 => 'Too Many Requests',
        (int) 431 => 'Request Header Fields Too Large',
        (int) 444 => 'Connection Closed Without Response',
        (int) 451 => 'Unavailable For Legal Reasons',
        (int) 499 => 'Client Closed Request',
        (int) 500 => 'Internal Server Error',
        (int) 501 => 'Not Implemented',
        (int) 502 => 'Bad Gateway',
        (int) 503 => 'Service Unavailable',
        (int) 504 => 'Gateway Time-out',
        (int) 505 => 'HTTP Version not supported',
        (int) 506 => 'Variant Also Negotiates',
        (int) 507 => 'Insufficient Storage',
        (int) 508 => 'Loop Detected',
        (int) 510 => 'Not Extended',
        (int) 511 => 'Network Authentication Required',
        (int) 599 => 'Network Connect Timeout Error'
    ]
    [private] reasonPhrase => ''
    [private] statusCode => (int) 200
    [private] protocol => '1.1'
    [private] stream => object(Zend\Diactoros\Stream) {}
}
$maxBufferLength = (int) 8192
$file = '/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php'
$line = (int) 179
$message = 'Unable to emit headers. Headers sent in file=/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php line=179'

Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 48
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37

Warning (2): Cannot modify header information - headers already sent by (output started at /home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php:179) [CORE/src/Http/ResponseEmitter.php, line 146]
Code Context
            $response->getStatusCode(),
            ($reasonPhrase ? ' ' . $reasonPhrase : '')
        ));

$response = object(Zend\Diactoros\Response) {
    [protected] headers => [
        'Content-Type' => [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames => [
        'content-type' => 'Content-Type'
    ]
    [private] phrases => [
        (int) 100 => 'Continue',
        (int) 101 => 'Switching Protocols',
        (int) 102 => 'Processing',
        (int) 200 => 'OK',
        (int) 201 => 'Created',
        (int) 202 => 'Accepted',
        (int) 203 => 'Non-Authoritative Information',
        (int) 204 => 'No Content',
        (int) 205 => 'Reset Content',
        (int) 206 => 'Partial Content',
        (int) 207 => 'Multi-status',
        (int) 208 => 'Already Reported',
        (int) 226 => 'IM used',
        (int) 300 => 'Multiple Choices',
        (int) 301 => 'Moved Permanently',
        (int) 302 => 'Found',
        (int) 303 => 'See Other',
        (int) 304 => 'Not Modified',
        (int) 305 => 'Use Proxy',
        (int) 306 => 'Switch Proxy',
        (int) 307 => 'Temporary Redirect',
        (int) 308 => 'Permanent Redirect',
        (int) 400 => 'Bad Request',
        (int) 401 => 'Unauthorized',
        (int) 402 => 'Payment Required',
        (int) 403 => 'Forbidden',
        (int) 404 => 'Not Found',
        (int) 405 => 'Method Not Allowed',
        (int) 406 => 'Not Acceptable',
        (int) 407 => 'Proxy Authentication Required',
        (int) 408 => 'Request Time-out',
        (int) 409 => 'Conflict',
        (int) 410 => 'Gone',
        (int) 411 => 'Length Required',
        (int) 412 => 'Precondition Failed',
        (int) 413 => 'Request Entity Too Large',
        (int) 414 => 'Request-URI Too Large',
        (int) 415 => 'Unsupported Media Type',
        (int) 416 => 'Requested range not satisfiable',
        (int) 417 => 'Expectation Failed',
        (int) 418 => 'I'm a teapot',
        (int) 421 => 'Misdirected Request',
        (int) 422 => 'Unprocessable Entity',
        (int) 423 => 'Locked',
        (int) 424 => 'Failed Dependency',
        (int) 425 => 'Unordered Collection',
        (int) 426 => 'Upgrade Required',
        (int) 428 => 'Precondition Required',
        (int) 429 => 'Too Many Requests',
        (int) 431 => 'Request Header Fields Too Large',
        (int) 444 => 'Connection Closed Without Response',
        (int) 451 => 'Unavailable For Legal Reasons',
        (int) 499 => 'Client Closed Request',
        (int) 500 => 'Internal Server Error',
        (int) 501 => 'Not Implemented',
        (int) 502 => 'Bad Gateway',
        (int) 503 => 'Service Unavailable',
        (int) 504 => 'Gateway Time-out',
        (int) 505 => 'HTTP Version not supported',
        (int) 506 => 'Variant Also Negotiates',
        (int) 507 => 'Insufficient Storage',
        (int) 508 => 'Loop Detected',
        (int) 510 => 'Not Extended',
        (int) 511 => 'Network Authentication Required',
        (int) 599 => 'Network Connect Timeout Error'
    ]
    [private] reasonPhrase => 'OK'
    [private] statusCode => (int) 200
    [private] protocol => '1.1'
    [private] stream => object(Zend\Diactoros\Stream) {}
}
$reasonPhrase = 'OK'

header - [internal], line ??
Cake\Http\ResponseEmitter::emitStatusLine() - CORE/src/Http/ResponseEmitter.php, line 146
Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 54
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37

Warning (2): Cannot modify header information - headers already sent by (output started at /home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php:179) [CORE/src/Http/ResponseEmitter.php, line 173]
Code Context
                    $name,
                    $value
                ), $first);

$response = object(Zend\Diactoros\Response) {
    [protected] headers => [
        'Content-Type' => [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames => [
        'content-type' => 'Content-Type'
    ]
    [private] phrases => [
        (int) 100 => 'Continue',
        (int) 101 => 'Switching Protocols',
        (int) 102 => 'Processing',
        (int) 200 => 'OK',
        (int) 201 => 'Created',
        (int) 202 => 'Accepted',
        (int) 203 => 'Non-Authoritative Information',
        (int) 204 => 'No Content',
        (int) 205 => 'Reset Content',
        (int) 206 => 'Partial Content',
        (int) 207 => 'Multi-status',
        (int) 208 => 'Already Reported',
        (int) 226 => 'IM used',
        (int) 300 => 'Multiple Choices',
        (int) 301 => 'Moved Permanently',
        (int) 302 => 'Found',
        (int) 303 => 'See Other',
        (int) 304 => 'Not Modified',
        (int) 305 => 'Use Proxy',
        (int) 306 => 'Switch Proxy',
        (int) 307 => 'Temporary Redirect',
        (int) 308 => 'Permanent Redirect',
        (int) 400 => 'Bad Request',
        (int) 401 => 'Unauthorized',
        (int) 402 => 'Payment Required',
        (int) 403 => 'Forbidden',
        (int) 404 => 'Not Found',
        (int) 405 => 'Method Not Allowed',
        (int) 406 => 'Not Acceptable',
        (int) 407 => 'Proxy Authentication Required',
        (int) 408 => 'Request Time-out',
        (int) 409 => 'Conflict',
        (int) 410 => 'Gone',
        (int) 411 => 'Length Required',
        (int) 412 => 'Precondition Failed',
        (int) 413 => 'Request Entity Too Large',
        (int) 414 => 'Request-URI Too Large',
        (int) 415 => 'Unsupported Media Type',
        (int) 416 => 'Requested range not satisfiable',
        (int) 417 => 'Expectation Failed',
        (int) 418 => 'I'm a teapot',
        (int) 421 => 'Misdirected Request',
        (int) 422 => 'Unprocessable Entity',
        (int) 423 => 'Locked',
        (int) 424 => 'Failed Dependency',
        (int) 425 => 'Unordered Collection',
        (int) 426 => 'Upgrade Required',
        (int) 428 => 'Precondition Required',
        (int) 429 => 'Too Many Requests',
        (int) 431 => 'Request Header Fields Too Large',
        (int) 444 => 'Connection Closed Without Response',
        (int) 451 => 'Unavailable For Legal Reasons',
        (int) 499 => 'Client Closed Request',
        (int) 500 => 'Internal Server Error',
        (int) 501 => 'Not Implemented',
        (int) 502 => 'Bad Gateway',
        (int) 503 => 'Service Unavailable',
        (int) 504 => 'Gateway Time-out',
        (int) 505 => 'HTTP Version not supported',
        (int) 506 => 'Variant Also Negotiates',
        (int) 507 => 'Insufficient Storage',
        (int) 508 => 'Loop Detected',
        (int) 510 => 'Not Extended',
        (int) 511 => 'Network Authentication Required',
        (int) 599 => 'Network Connect Timeout Error'
    ]
    [private] reasonPhrase => 'OK'
    [private] statusCode => (int) 200
    [private] protocol => '1.1'
    [private] stream => object(Zend\Diactoros\Stream) {}
}
$name = 'Content-Type'
$values = [
    (int) 0 => 'text/html; charset=UTF-8'
]
$first = true
$value = 'text/html; charset=UTF-8'

header - [internal], line ??
Cake\Http\ResponseEmitter::emitHeaders() - CORE/src/Http/ResponseEmitter.php, line 173
Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 55
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37

Body:
Change:

$query = $this->Customers->find()->where(['id' => $id]);

To:

$query = $this->Customers->find()->where(['id' => $id])->first();

Also use "echo" in the controller to return the  data to ajax.

echo json_encode($query);

Then json encoded data should be returned.

Edit:

Make sure you have created a form (to get csrf token) like this in the ctp file:

<?= $this->Form->create(Null, ['type' => 'POST']) ?>
<?= $this->Form->end() ?>

And add these lines to the javascript code:

beforeSend: function(xhr){
    xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},

And add "data" to javascript, like:

var id = 1; //Your ID. I don't know what ID it is, so I just use 1.
var csrfToken = $('[name=_csrfToken]').val(); //Sorry, I forgot this.
$.ajax({
    type: "POST",
    url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
    data: {'id' : id},
    beforeSend: function(xhr){
       xhr.setRequestHeader('X-CSRF-Token', csrfToken);
    },
    success: function(data){
        alert(data);
        data = JSON.parse(data);
        alert("id: " + data.id);
    }
});

And change the controller:

public function fill(){
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    if ($this->request->is('ajax')) {
        $id = $this->request->data['id'];
        $query = $this->Customers->find()
        ->where([
           'id' => $id
        ])->first();
        echo json_encode($query);
    }
}

Edit:

Maybe you are not using CsrfToken. In that case, you don't need to load CsrfToken.
Change the javascript code like this:

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous">
  //jQuery CDN. If you have loaded jQuery somewhere else, you don't need this.
</script>
<script>
var id = 1; //Your ID. I don't know what ID it is, so I just use 1.
$.ajax({
    type: "POST",
    url: '<?= $this->Url->build(array("controller" => "Customers", "action" => "fill")); ?>',
    data: {'id' : id},
    success: function(data){
        alert(data);
        data = JSON.parse(data);
        alert("id: " + data.id);
    }
});
</script>

With this javascript, I think you don't have to change the controller (you don't need to remove is('ajax').)

Edit

Maybe as you say, null is returned from the controller. But I want to check what the error message is. Please check it by the following way.

If succeeded, you get json string. You can change it to javascript's object after receiving it.

If failed, you can check it from the google chrome browser. It should show what error you get:

Or, maybe cakephp might return error message in html. In that case, you would receive this:

This is raw html code, so it might be hard to read.

Please let me know what error message you get..


来源: stackexchange

问:
How to open multiple consoles in multiple tabs in Eclipse?
I am using Eclipse Version: Helios Release for a Java application. I need to run multiple instances of same application and want easy visibility of multiple consoles.

Can it be done? If yes, how?

答:
Located near your console tab should be a button "Open Console".
If you click this button one of your options should be "New Console View".

You'll now have 2 console views.

One of your other buttons near your console tab is "Display Selected Console". When you choose this option you can select from any of your running applications.
Just select the tab, select which application you want it to watch, and repeat for the other tab.
You can then move your 2 console views to wherever you want independently of each other.

ContentLicense: CC BY-SA 3.0


问:
How to run examples of an API (which is already having workspace) using eclipse IDE
I am new to Java and I am not sure how apt is my question title. Please suggest any better title.

I have got a Java API which has many executable modules which do various things related to parsing MS Outlook's .pst files. And my problem is that I am getting this exception when I run the execute command to execute a .class file of one module of the API(java -classpath /opt/Java/libs/JPST/lib/jpst.jar /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example)-

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example
Caused by: java.lang.ClassNotFoundException: .opt.Java.libs.JPST.examples.GetInboxMessages.bin.Example

        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example.  Program will exit.
</code>```

So far ...

You can check my previous question where I concluded that I was correctly running the compile and execute commands. But I am still getting the above mentioned `exception.

I asked the API's developer who says that I should get Eclipse or Netbeans IDE. He said that the

examples folder inside the API's
  folder structure is entire Eclipse
  workspace.

and also said that

It is easier to compile and run all
  examples.

And now ...

So, I have setup Eclipse Helios for Java. Can anyone tell me how is it easy to compile and run all the examples (I think the modules inside the examples folder) using the IDE. I have earlier worked with Eclipse for PHP but never for Java.

Folder structure of the API

 I need to execute a .class file of one of those modules (many module folders are present inside examples directory). There are many such modules present inside the examples folder of the API. Each of these modules folders contain a bin folder (containing .class file) and src folder (containing .java file) . I need to execute one such .class file.

There is a lib directory containing a .jar file (which is needed to be referenced by my target .class file). The lib directory is at the same level as the examples directory.

Solution

I have verified that the solution given by Jonathan works (verified only without-using-elipse case). To make it more clear the classpath needs to include all the class locations in both compile and execute commands. So, if you need to compile and execute an Example.java file with a dependency Parent.jar do this:-

Compile

```<code>javac -classpath /path/to/Parent.jar/file/Parent.jar:/path/to/Example.java/file/ Example.java
</code>```

Execute

```<code>java -classpath /path/to/Parent.jar/file/Parent.jar:/path/to/Example.class/file Example
</code>```

And note the  separator - should be : for linux and ; for windows.

Thanks,

Sandeepan

答:
When Eclipse starts it should ask you which workspace to use. Select the examples folder and, if it really is an eclipse workspace, you should see all the projects already set up (it may take some time to build everything depending on the size of the projects and the speed of your machine). Then simply find the class you want and run it. If everything is set up correctly it should just work. If not you may have to go back to the developer for more details.

But I don't think you need Eclipse to run that one class. Looking at the stacktrace you provided at the beginning of your question it looks like it failed to run because you haven't set your classpath properly. Try:

```<code>java -classpath /opt/Java/libs/JPST/lib/jpst.jar:/opt/Java/libs/JPST/examples/GetInboxMessages/bin Example
</code>```

To very briefly explain: The classpath lists the places where Java looks for the classes it needs. You specify the class to run relative to the classpath, not as a file path. Since the class you are trying to run in in the folder "/opt/Java/libs/JPST/examples/GetInboxMessages/bin" this folder must be on the classpath (note, I am assuming a unix based system, if you are using windows use ';' to separate entries not ':'). Then simply specify the class to run by itself relative to the classpath (which in this case is just the class name by itself).

Please be aware this is a very basic overview, things get a more complex if you start using packages (folders that would appear below the bin folder). This is one advantage of using a program like Eclipse since it will handle a lot of this for you.

ContentLicense: CC BY-SA 2.5

Body:
I am new to Java and I am not sure how apt is my question title. Please suggest any better title.

I have got a Java API which has many executable modules which do various things related to parsing MS Outlook's .pst files. And my problem is that I am getting this exception when I run the execute command to execute a .class file of one module of the API(java -classpath /opt/Java/libs/JPST/lib/jpst.jar /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example)-

Exception in thread "main" java.lang.NoClassDefFoundError: /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example
Caused by: java.lang.ClassNotFoundException: .opt.Java.libs.JPST.examples.GetInboxMessages.bin.Example

        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example.  Program will exit.

So far ...

You can check my previous question where I concluded that I was correctly running the compile and execute commands. But I am still getting the above mentioned `exception.

I asked the API's developer who says that I should get Eclipse or Netbeans IDE. He said that the

examples folder inside the API's
  folder structure is entire Eclipse
  workspace.

and also said that

It is easier to compile and run all
  examples.

And now ...

So, I have setup Eclipse Helios for Java. Can anyone tell me how is it easy to compile and run all the examples (I think the modules inside the examples folder) using the IDE. I have earlier worked with Eclipse for PHP but never for Java.

Folder structure of the API

 I need to execute a .class file of one of those modules (many module folders are present inside examples directory). There are many such modules present inside the examples folder of the API. Each of these modules folders contain a bin folder (containing .class file) and src folder (containing .java file) . I need to execute one such .class file.

There is a lib directory containing a .jar file (which is needed to be referenced by my target .class file). The lib directory is at the same level as the examples directory.

Solution

I have verified that the solution given by Jonathan works (verified only without-using-elipse case). To make it more clear the classpath needs to include all the class locations in both compile and execute commands. So, if you need to compile and execute an Example.java file with a dependency Parent.jar do this:-

Compile

javac -classpath /path/to/Parent.jar/file/Parent.jar:/path/to/Example.java/file/ Example.java

Execute

java -classpath /path/to/Parent.jar/file/Parent.jar:/path/to/Example.class/file Example

And note the  separator - should be : for linux and ; for windows.

Thanks,

Sandeepan

Body:
When Eclipse starts it should ask you which workspace to use. Select the examples folder and, if it really is an eclipse workspace, you should see all the projects already set up (it may take some time to build everything depending on the size of the projects and the speed of your machine). Then simply find the class you want and run it. If everything is set up correctly it should just work. If not you may have to go back to the developer for more details.

But I don't think you need Eclipse to run that one class. Looking at the stacktrace you provided at the beginning of your question it looks like it failed to run because you haven't set your classpath properly. Try:

java -classpath /opt/Java/libs/JPST/lib/jpst.jar:/opt/Java/libs/JPST/examples/GetInboxMessages/bin Example

To very briefly explain: The classpath lists the places where Java looks for the classes it needs. You specify the class to run relative to the classpath, not as a file path. Since the class you are trying to run in in the folder "/opt/Java/libs/JPST/examples/GetInboxMessages/bin" this folder must be on the classpath (note, I am assuming a unix based system, if you are using windows use ';' to separate entries not ':'). Then simply specify the class to run by itself relative to the classpath (which in this case is just the class name by itself).

Please be aware this is a very basic overview, things get a more complex if you start using packages (folders that would appear below the bin folder). This is one advantage of using a program like Eclipse since it will handle a lot of this for you.


问:
Guessing Number within Time Limit [Threads]
I've been practicing with threads, so I wrote up this timed game where the user needs to guess the correct number (ranges from 1-10). If the user guesses the correct answer in the time limit, the thread stops and the program terminates. It fails to work when the user fails to guess within the time limit. Even though it enters the if-statement after the time limit, it still fails to interrupt the thread completely unless I guess the correct number. I have read other threads but they seem to use ask about the "traditional" guessing game or utilizing Timer. Explanation and/or tips for a suggested solution is also appreciated.

```<code>    import java.util.*;
    import static java.lang.System.out;
    import java.io.*;

    public class Threading implements Runnable {
        private static int num;
        private static int k;

    public void run() {
        try {
            Scanner line = new Scanner(System.in);
            k = -1;
            out.println("Guess!");
            while (k != num) {
                k = line.nextInt();
                if (k != num) {
                    out.println("Nope");
                }
            }

        }
        catch (Exception e) {
            out.println("I'm not done!");
        }
    }

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

        num = (int) (Math.random() * 9 + 1);
        out.println(num);
        Thread t = new Thread(new Threading());
        t.start();

        long patience = 1000 * 5;
        long startTime = System.currentTimeMillis();
        while (t.isAlive()) {
            t.join(1000);
            if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) {
                out.println("I'm in here!");
                t.interrupt();
                t.join();
                out.println("Times up!");
            }
        }
    }
}
</code>```

答:
Since one of the comments already points out that the call to nextInt will block I don't think there is a need to go into the details of that.

So for now I'm going to assume you're fine with allowing the user 1 final guess after the timer expires.

The following is the modified code including my comments. I refer to the thread you named t as the "guessing thread".

```<code>private static int num;
private static int k;
//Changed variable "line" to "scanner" and made it static so that the
//  main method can close it once everything is done.
private static Scanner scanner = new Scanner(System.in);

public void run() {
    try {
        k = -1;
        System.out.println("Guess!");
        while (k!=num) {
            //Added a check for interrupt, otherwise this thread will never
            // end unless the user enters the correct answer.
            if(Thread.currentThread().isInterrupted())
                return;
            k = scanner.nextInt();
            if(k != num){
                System.out.println("Nope");
            }
        }
        System.out.println("Correct!");

    } catch (Exception e) {
        System.out.println("I'm not done!");
    }
}

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

    num = (int) (Math.random() * 9 + 1);
    System.out.println(num);
    //Declared the guessing thread as final so it can be used inside of
    // the TimerTask that is created later.
    final Thread t = new Thread(new GuessUntilTimeLimit());
    t.start();

    long patience = 1000 * 5;

    //Use a Timer to enforce your time limit, the TimerTask will execute
    // an interrupt of your guessing thread if the thread is still alive
    // (it may have died already if user got right answer)
    Timer timer = new Timer();
    TimerTask task = new TimerTask(){

        @Override
        public void run() {
            if(t.isAlive()){
                t.interrupt();
                System.out.println("Times up! Enter your final guess now.");
            }
        }
    };
    timer.schedule(task, patience);
    //Wait for the guessing thread to finish before canceling the timer
    t.join();
    //By now either the user got the answer or time has run out. Either way
    //  we need to clean up by canceling the timer.
    timer.cancel();
    //Added a call to close the scanner, it's always important to release
    // resources
    scanner.close();
}
</code>```

Now your main thread schedules a task to execute after patience milliseconds. This task is then responsible for interrupting the "guessing thread". The "guessing thread" will check for interrupt and stop itself when appropriate.

Again, depending on your requirements, you may need to alter the way you accept user input since nextInt will block the thread. For completeness I'm including a link to the question regarding interrupting Scanner.nextLine mentioned in the comments.

Body:
I've been practicing with threads, so I wrote up this timed game where the user needs to guess the correct number (ranges from 1-10). If the user guesses the correct answer in the time limit, the thread stops and the program terminates. It fails to work when the user fails to guess within the time limit. Even though it enters the if-statement after the time limit, it still fails to interrupt the thread completely unless I guess the correct number. I have read other threads but they seem to use ask about the "traditional" guessing game or utilizing Timer. Explanation and/or tips for a suggested solution is also appreciated.

    import java.util.*;
    import static java.lang.System.out;
    import java.io.*;

    public class Threading implements Runnable {
        private static int num;
        private static int k;

    public void run() {
        try {
            Scanner line = new Scanner(System.in);
            k = -1;
            out.println("Guess!");
            while (k != num) {
                k = line.nextInt();
                if (k != num) {
                    out.println("Nope");
                }
            }

        }
        catch (Exception e) {
            out.println("I'm not done!");
        }
    }

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

        num = (int) (Math.random() * 9 + 1);
        out.println(num);
        Thread t = new Thread(new Threading());
        t.start();

        long patience = 1000 * 5;
        long startTime = System.currentTimeMillis();
        while (t.isAlive()) {
            t.join(1000);
            if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) {
                out.println("I'm in here!");
                t.interrupt();
                t.join();
                out.println("Times up!");
            }
        }
    }
}

Body:
Since one of the comments already points out that the call to nextInt will block I don't think there is a need to go into the details of that.

So for now I'm going to assume you're fine with allowing the user 1 final guess after the timer expires.

The following is the modified code including my comments. I refer to the thread you named t as the "guessing thread".

private static int num;
private static int k;
//Changed variable "line" to "scanner" and made it static so that the
//  main method can close it once everything is done.
private static Scanner scanner = new Scanner(System.in);

public void run() {
    try {
        k = -1;
        System.out.println("Guess!");
        while (k!=num) {
            //Added a check for interrupt, otherwise this thread will never
            // end unless the user enters the correct answer.
            if(Thread.currentThread().isInterrupted())
                return;
            k = scanner.nextInt();
            if(k != num){
                System.out.println("Nope");
            }
        }
        System.out.println("Correct!");

    } catch (Exception e) {
        System.out.println("I'm not done!");
    }
}

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

    num = (int) (Math.random() * 9 + 1);
    System.out.println(num);
    //Declared the guessing thread as final so it can be used inside of
    // the TimerTask that is created later.
    final Thread t = new Thread(new GuessUntilTimeLimit());
    t.start();

    long patience = 1000 * 5;

    //Use a Timer to enforce your time limit, the TimerTask will execute
    // an interrupt of your guessing thread if the thread is still alive
    // (it may have died already if user got right answer)
    Timer timer = new Timer();
    TimerTask task = new TimerTask(){

        @Override
        public void run() {
            if(t.isAlive()){
                t.interrupt();
                System.out.println("Times up! Enter your final guess now.");
            }
        }
    };
    timer.schedule(task, patience);
    //Wait for the guessing thread to finish before canceling the timer
    t.join();
    //By now either the user got the answer or time has run out. Either way
    //  we need to clean up by canceling the timer.
    timer.cancel();
    //Added a call to close the scanner, it's always important to release
    // resources
    scanner.close();
}

Now your main thread schedules a task to execute after patience milliseconds. This task is then responsible for interrupting the "guessing thread". The "guessing thread" will check for interrupt and stop itself when appropriate.

Again, depending on your requirements, you may need to alter the way you accept user input since nextInt will block the thread. For completeness I'm including a link to the question regarding interrupting Scanner.nextLine mentioned in the comments.


问:
how to `bindActionCreators` with redux-thunk
I am quite new to JavaScript and react-native and I have existing project that I need to add functionality to. It is using redux and redux-thunk with redux-saga to send API requests. Currently it supports only 1 dispatch function per component and I need to dispatch several types of requests to the saga. I am trying to bindActionCreators to add the dispatch to the stores but to no avail.. I am totally lost on the mapDispatchToProps part and how do I "fire the action" afterwards..

in single dispatch to props, I did this:

```<code>let sdtp = (arg) => {
   return (dispatch) => {
     dispatch({
       type: 'GET_TEST_HASHMAP_SAGA',
       hashmap: arg
     })
   }
 }

export default MainPage = connect(
   mapStateToProps,
   { sdtp }
)(MainPage);
</code>```

and I can "access the function" (is this the right term? at least my saga gets called) inside the MainPage.render() component :

```<code>`this.props.sdtp({'hello':'world'});`
</code>```

but when I change to use bindActionCreators, I cannot access it in the props anymore (I have tried so many different experiments I almost give up)

Here is how I construct my multiple dispatches:

```<code>let action1 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA',
         hashmap: arg
      });
   }
}

let action2 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA2',
         params: arg
      });
   }
}

let action3 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA3',
         args: arg
      });
   }
}

let mdtp = (dispatch) => {
  return {
    actions: bindActionCreators(action1, action2, action3, dispatch)
  }
}

export default MainPage = connect(
   mapStateToProps,
       { mdtp }
)(MainPage);
</code>```

I am trying to access the actions like this:

this.props.mdtp.action1({arg: 'hello'});

Thanks in advance!

答:
In your mpdt function, you need to return result of bindActionCreators call, not object with action key.

So, it should be

```<code>const mdtp = (dispatch) => {
  return bindActionCreators({
    action1, action2, action3
  }, dispatch);
};
</code>```

and you can call them as this.props.action1(...)

From your code it also seems, that you have confused two ways of passing action creators to the component. One way is described above. And another way, you can pass your action creators directly to connect() using object notations, like so

```<code>export default MainPage = connect(
   mapStateToProps,
   { action1, action2, action3 }
)(MainPage);
</code>```

which will have same result. And your first approach, with sdtp action creator uses this approach.

Body:
I am quite new to JavaScript and react-native and I have existing project that I need to add functionality to. It is using redux and redux-thunk with redux-saga to send API requests. Currently it supports only 1 dispatch function per component and I need to dispatch several types of requests to the saga. I am trying to bindActionCreators to add the dispatch to the stores but to no avail.. I am totally lost on the mapDispatchToProps part and how do I "fire the action" afterwards..

in single dispatch to props, I did this:

let sdtp = (arg) => {
   return (dispatch) => {
     dispatch({
       type: 'GET_TEST_HASHMAP_SAGA',
       hashmap: arg
     })
   }
 }

export default MainPage = connect(
   mapStateToProps,
   { sdtp }
)(MainPage);

and I can "access the function" (is this the right term? at least my saga gets called) inside the MainPage.render() component :

`this.props.sdtp({'hello':'world'});`

but when I change to use bindActionCreators, I cannot access it in the props anymore (I have tried so many different experiments I almost give up)

Here is how I construct my multiple dispatches:

let action1 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA',
         hashmap: arg
      });
   }
}

let action2 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA2',
         params: arg
      });
   }
}

let action3 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA3',
         args: arg
      });
   }
}

let mdtp = (dispatch) => {
  return {
    actions: bindActionCreators(action1, action2, action3, dispatch)
  }
}

export default MainPage = connect(
   mapStateToProps,
       { mdtp }
)(MainPage);

I am trying to access the actions like this:

this.props.mdtp.action1({arg: 'hello'});

Thanks in advance!

Body:
In your mpdt function, you need to return result of bindActionCreators call, not object with action key.

So, it should be

const mdtp = (dispatch) => {
  return bindActionCreators({
    action1, action2, action3
  }, dispatch);
};

and you can call them as this.props.action1(...)

From your code it also seems, that you have confused two ways of passing action creators to the component. One way is described above. And another way, you can pass your action creators directly to connect() using object notations, like so

export default MainPage = connect(
   mapStateToProps,
   { action1, action2, action3 }
)(MainPage);

which will have same result. And your first approach, with sdtp action creator uses this approach.


问:
Can't bind to 'totalItems' since it isn't a known property of 'pagination'
this is my HTML pagination tag

```<code><pagination class="pagination-sm" [(ngModel)]="page" [totalItems]="length" [itemsPerPage]="itemsPerPage" [maxSize]="maxSize" [boundaryLinks]="true" [rotate]="false" (pageChanged)="changePage($event)" (numPages)="numPages = $event"></pagination>
</code>```

and my model file

```<code>import { Injectable } from '@angular/core';
import { NgbPaginationConfig} from '@ng-bootstrap/ng-bootstrap';

@Injectable()
export class PaginationConfig {
    constructor(private config: NgbPaginationConfig) {
        config.boundaryLinks = true;
        config.maxSize = 5;
        config.pageSize = 20;
        config.size = 'sm';
    }
}
</code>```

GitHub package I am using @ng-bootstrap/ng-bootstrap that time I got following error

```<code>Unhandled Promise rejection: Template parse errors:
Can't bind to 'itemsPerPage' since it isn't a known property of 'pagination'. ("
</tbody>
</table>
<pagination class="pagination-sm" [(ngModel)]="page"  [ERROR ->][itemsPerPage]="itemsPerPage" [maxSize]="maxSize" [boundaryLinks]="true" [rotate]="false" (pageChange"): ng:///TeamModule/TeamComponent.html@83:54
Can't bind to 'maxSize' since it isn't a known property of 'pagination'. ("tbody>
</table>
<pagination class="pagination-sm" [(ngModel)]="page"  [itemsPerPage]="itemsPerPage" [ERROR ->][maxSize]="maxSize" [boundaryLinks]="true" [rotate]="false" (pageChanged)="changePage($event)" (numPa"): ng:///TeamModule/TeamComponent.html@83:84
Can't bind to 'boundaryLinks' since it isn't a known property of 'pagination'. ("ination class="pagination-sm" [(ngModel)]="page"  [itemsPerPage]="itemsPerPage" [maxSize]="maxSize" [ERROR ->][boundaryLinks]="true" [rotate]="false" (pageChanged)="changePage($event)" (numPages)="numPages = $ev"): ng:///TeamModule/TeamComponent.html@83:104
Can't bind to 'rotate' since it isn't a known property of 'pagination'. ("on-sm" [(ngModel)]="page"  [itemsPerPage]="itemsPerPage" [maxSize]="maxSize" [boundaryLinks]="true" [ERROR ->][rotate]="false" (pageChanged)="changePage($event)" (numPages)="numPages = $event"></pagination>
</di"): ng:///TeamModule/TeamComponent.html@83:127
'pagination' is not a known element:
1. If 'pagination' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
</tbody>
</table>
[ERROR ->]<pagination class="pagination-sm" [(ngModel)]="page"  [itemsPerPage]="itemsPerPage" [maxSize]="maxSiz"): ng:///TeamModule/TeamComponent.html@83:0 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:
Can't bind to 'itemsPerPage' since it isn't a known property of 'pagination'. ("
</tbody>
</table>
</code>```

When loading time only i got that above error

答:
I miss that model file import ng-bootstrap

```<code>import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
</code>```

and inside @NgModel import for root

```<code>NgbModule.forRoot()
</code>```

Edit: Please note that forRoot() of NgbModule is deprecated since 3.0.0 and will be removed from 4.0.0. Instead, it is suggested to just import

```<code>NgbModule
</code>```

Body:
this is my HTML pagination tag

<pagination class="pagination-sm" [(ngModel)]="page" [totalItems]="length" [itemsPerPage]="itemsPerPage" [maxSize]="maxSize" [boundaryLinks]="true" [rotate]="false" (pageChanged)="changePage($event)" (numPages)="numPages = $event"></pagination>

and my model file

import { Injectable } from '@angular/core';
import { NgbPaginationConfig} from '@ng-bootstrap/ng-bootstrap';

@Injectable()
export class PaginationConfig {
    constructor(private config: NgbPaginationConfig) {
        config.boundaryLinks = true;
        config.maxSize = 5;
        config.pageSize = 20;
        config.size = 'sm';
    }
}

GitHub package I am using @ng-bootstrap/ng-bootstrap that time I got following error

Unhandled Promise rejection: Template parse errors:
Can't bind to 'itemsPerPage' since it isn't a known property of 'pagination'. ("

<pagination class="pagination-sm" [(ngModel)]="page"  [ERROR ->][itemsPerPage]="itemsPerPage" [maxSize]="maxSize" [boundaryLinks]="true" [rotate]="false" (pageChange"): ng:///TeamModule/TeamComponent.html@83:54
Can't bind to 'maxSize' since it isn't a known property of 'pagination'. ("tbody>

<pagination class="pagination-sm" [(ngModel)]="page"  [itemsPerPage]="itemsPerPage" [ERROR ->][maxSize]="maxSize" [boundaryLinks]="true" [rotate]="false" (pageChanged)="changePage($event)" (numPa"): ng:///TeamModule/TeamComponent.html@83:84
Can't bind to 'boundaryLinks' since it isn't a known property of 'pagination'. ("ination class="pagination-sm" [(ngModel)]="page"  [itemsPerPage]="itemsPerPage" [maxSize]="maxSize" [ERROR ->][boundaryLinks]="true" [rotate]="false" (pageChanged)="changePage($event)" (numPages)="numPages = $ev"): ng:///TeamModule/TeamComponent.html@83:104
Can't bind to 'rotate' since it isn't a known property of 'pagination'. ("on-sm" [(ngModel)]="page"  [itemsPerPage]="itemsPerPage" [maxSize]="maxSize" [boundaryLinks]="true" [ERROR ->][rotate]="false" (pageChanged)="changePage($event)" (numPages)="numPages = $event"></pagination>
</di"): ng:///TeamModule/TeamComponent.html@83:127
'pagination' is not a known element:
1. If 'pagination' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

[ERROR ->]<pagination class="pagination-sm" [(ngModel)]="page"  [itemsPerPage]="itemsPerPage" [maxSize]="maxSiz"): ng:///TeamModule/TeamComponent.html@83:0 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:
Can't bind to 'itemsPerPage' since it isn't a known property of 'pagination'. ("

When loading time only i got that above error

Body:
I miss that model file import ng-bootstrap

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

and inside @NgModel import for root

NgbModule.forRoot()

Edit: Please note that forRoot() of NgbModule is deprecated since 3.0.0 and will be removed from 4.0.0. Instead, it is suggested to just import

NgbModule

ContentLicense: CC BY-SA 4.0


问:
Using Optware packages and startup scripts on dd-wrt router
I'm trying to run a mumble server (umurmur) on my dd-wrt router (Buffalo WZR-HP-AG300H). I flashed one of the recent community versions of dd-wrt on the device (SVN Rev.: 23320), it has an Atheros CPU inside.

After that I mounted a USB pendrive into the filesystem using these guides (Guide 1, Guide 2) and created writable directories. Here is my startup-script saved to nvram (via web-gui)

EDIT: USB pendrive should be partioned before using it with DD-Wrt.

```<code>#!/bin/sh

sleep 5
insmod mbcache
insmod jbd
insmod ext3

mkdir '/mnt/part1'
mkdir '/mnt/part2'
mount -t ext3 -o noatime /dev/sda5 /mnt/part1   # /dev/sda5 -> partition on USB pendrive
mount -t ext3 -o noatime /dev/sda7 /mnt/part2   # /dev/sda7 -> partition on USB pendrive
swapon /dev/sda6                                # /dev/sda6 -> partition on USB pendrive

sleep 2
if [ -f /mnt/part1/optware.enable ];then
#mount -o bind /mnt/part2 /mnt/part1/root
mount -o bind /mnt/part1        /jffs
mount -o bind /mnt/part1/etc    /etc
mount -o bind /mnt/part1/opt    /opt
mount -o bind /mnt/part1/root   /tmp/root
else
exit
fi

if [ -d /opt/usr ]; then
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/lib:/usr/lib:/opt/lib:/opt/usr/lib:/jffs/usr/lib:/jffs/usr/local/lib
export PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/jffs/bin:/opt/bin:/opt/sbin:/opt/usr/bin:/opt/usr/sbin
export IPKG_INSTROOT=/opt
else
exit
fi
</code>```

The script works well and I can use opkg to install packages. I can also run umurmur manually but I'm struggling on making umurmur autostart. I recognized that the umurmur startup script placed in /opt/etc/init.d/ requires arguments like start and stop but it seems they are called without any arguments.

Another way described here did not work too.

Has anyone a working solution on problems like these? Please help!

答:
Its unclear i the page you referred to has changed - and indeed my setup is fairly different to yours, but to get scripts working on startup I did the following -

mkdir -p /jffs/etc/config

copy script into /jffs/etc/config directory, renaming it to end with .startup

chmod 755 /jffs/etc/config/scriptname.startup

Body:
I'm trying to run a mumble server (umurmur) on my dd-wrt router (Buffalo WZR-HP-AG300H). I flashed one of the recent community versions of dd-wrt on the device (SVN Rev.: 23320), it has an Atheros CPU inside.

After that I mounted a USB pendrive into the filesystem using these guides (Guide 1, Guide 2) and created writable directories. Here is my startup-script saved to nvram (via web-gui)

EDIT: USB pendrive should be partioned before using it with DD-Wrt.

#!/bin/sh

sleep 5
insmod mbcache
insmod jbd
insmod ext3

mkdir '/mnt/part1'
mkdir '/mnt/part2'
mount -t ext3 -o noatime /dev/sda5 /mnt/part1   # /dev/sda5 -> partition on USB pendrive
mount -t ext3 -o noatime /dev/sda7 /mnt/part2   # /dev/sda7 -> partition on USB pendrive
swapon /dev/sda6                                # /dev/sda6 -> partition on USB pendrive

sleep 2
if [ -f /mnt/part1/optware.enable ];then
#mount -o bind /mnt/part2 /mnt/part1/root
mount -o bind /mnt/part1        /jffs
mount -o bind /mnt/part1/etc    /etc
mount -o bind /mnt/part1/opt    /opt
mount -o bind /mnt/part1/root   /tmp/root
else
exit
fi

if [ -d /opt/usr ]; then
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/lib:/usr/lib:/opt/lib:/opt/usr/lib:/jffs/usr/lib:/jffs/usr/local/lib
export PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/jffs/bin:/opt/bin:/opt/sbin:/opt/usr/bin:/opt/usr/sbin
export IPKG_INSTROOT=/opt
else
exit
fi

The script works well and I can use opkg to install packages. I can also run umurmur manually but I'm struggling on making umurmur autostart. I recognized that the umurmur startup script placed in /opt/etc/init.d/ requires arguments like start and stop but it seems they are called without any arguments.

Another way described here did not work too.

Has anyone a working solution on problems like these? Please help!


问:
Kotlin - chaining of safe call operator. unnecessary operator calls
Take the following example which uses safe call operator (?.):

```<code>class Sample {
    class A(
            val sampleB: B? = B()
    )

    class B(
            val sampleC: C = C()
    )

    class C(
            val sampleInt: Int = 1
    )

    fun test() {
        val intInC: Int? = A().sampleB?.sampleC?.sampleInt
    }
}
</code>```

I understand that we need a safe call operator on sampleB. But why do we need the safe call operator on sampleC.
If I remove that operator, it does not compile.

Based on my understanding of the operator, if sampleB were null, the line returns null. And if sampleB is not null, we can be sure that sampleC is not null, based on its type. But why does Kotlin force safe call operator on sampleC ?

答:
```<code>A().sampleB?.sampleC?.sampleInt
</code>```

parses as

```<code>((A().sampleB)?.sampleC)?.sampleInt
</code>```

The types are

```<code>A(): A
A().sampleB: B?
(A().sampleB)?.sampleC: C?
((A().sampleB)?.sampleC)?.sampleInt: Int?
</code>```

Because the type before sampleC is a B?, the ?. is required.

Body:
Take the following example which uses safe call operator (?.):

class Sample {
    class A(
            val sampleB: B? = B()
    )

    class B(
            val sampleC: C = C()
    )

    class C(
            val sampleInt: Int = 1
    )

    fun test() {
        val intInC: Int? = A().sampleB?.sampleC?.sampleInt
    }
}

I understand that we need a safe call operator on sampleB. But why do we need the safe call operator on sampleC.
If I remove that operator, it does not compile.

Based on my understanding of the operator, if sampleB were null, the line returns null. And if sampleB is not null, we can be sure that sampleC is not null, based on its type. But why does Kotlin force safe call operator on sampleC ?

Body:
A().sampleB?.sampleC?.sampleInt

parses as

((A().sampleB)?.sampleC)?.sampleInt

The types are

A(): A
A().sampleB: B?
(A().sampleB)?.sampleC: C?
((A().sampleB)?.sampleC)?.sampleInt: Int?

Because the type before sampleC is a B?, the ?. is required.


问:
Assembly Return Address Replace
I have seen that by replacing the return address on the stack, the EIP can be made to point at addresses that are part of the stack.

But, for example, JMP needs the programmer to specify the code segment when doing far jumps between segments. What happens when you replace the return address? Does the CS change?

答:
far call / far ret exist too, along with the far jmp you mentioned, but nobody uses them either.  (All mainstream OSes use a flat memory model where cs is constant.)

Any normal compiler-generated code will be using near ret, so it only pops into EIP / RIP, not a wider value into CS:EIP.

If you want your exploit to switch to the OS's 64-bit user-space code segment selector value in a 32-bit process (or vice versa), you're going to have to gain enough control to run a far jmp / call / ret in your payload, or jump to one that exists as part of another instruction somewhere or in data on an executable page.

Beware that the OS may not preserve your modified cs in some cases.  For example, some ways of invoking Linux system calls set cs to the kernel's __USER32_CS constant.

Title: Assembly Return Address Replace


问:
mxnet packages with Rstudio on Virtual machine
I want to install r studio on virtual machine to work with mxnet package.

Here is how to configure Rstudio on microsoft azzure linux virtual machine:
http://moresi.de/posts/2016-04-02-setting-up-r-studio-server-on-microsoft-azure.html

And there is how to install mxnet packages for linux:
https://mxnet.incubator.apache.org/get_started/install.html

My question is: If I will install R-studio and Mxnet package following the step in this 2 tutorial will I be able to use mxnet package from R Studio workspace?

Another question is: It is possible to install all availible r packages in this configuration from R studio workspace?

I know that maybe this is a trivial question, but i am completly new to microsoft azzure, and spend a lot of time looking for an answer on web. Its seems that there wasn't any exemple of using mxnet packages with R on cloud.I would be very grateful even for some tips : )

答:
Yes and no. Yes, you can run mxnet through Rstudio server, I currently do this on my AWS linux instance and login via the browser.

No, you cannot install everything from Rstudio and will have to ssh in and compile/install mxnet and a few other things. Unless you want the CPU mxnet instead of the GPU verion, that might be precompiled. The GPU installation process is a nightmare, I wouldn't recommend unless you have a moderate level of linux experience.


问:
Can I use bindParam always?
I see so many people using "execute(array [...]" in their SQL methods, I always used

execute->bindParam('[...]', $string);

Can I still using bindParam? If no, when should I use it? Thanks

答:
I would only use BindParam to get data out of the query, or if I am actually using the binding e.g. updating the bound variable and then re-calling execute, which is the point of the prepared statement.

If you have a lot (N) of parameters, and they are only one-off unchanging inputs, it's arguably more efficient to simply use the execute array, rather than calling N +1 function calls. (By arguably, I mean it's probably a micro-optimisation compared to your query speed.)

From a simplicity perspective, why go to all the trouble of binding (and risking complexities due to the references) if are not using the mechanism?

Both bind and execute array will provide the same security protection, there is no additional benefit there I know of.

Binding might be more readable - i.e. it's easier to see what is bound to what than the implicit order of the execute array, especially if you are binding to ? not named labels.

I review code with what I feel are "spurious" bindings and I do usually feel like rejecting it and asking them to refactor to a simple execute + array, but then I usually don't bother. I think that shows it's close to being a matter of taste.

Title: Can I use bindParam always?


问:
How to install PHP intl extension in Ubuntu 14.04
I have a hard time to find exact method to install PHP intl extension in Ubuntu 14.04.

I tried with sudo apt-get install php5-intl but displays error Unable to locate package.

I really need this extension for Zend Framework 2 , because of above missing extension I am getting error like this

ERROR: Zend\I18n\Validator component requires the intl PHP extension

I am using PHP 5.5.9.

How can I install PHP-intl extension in a correct way ?

答:
install it from terminal </p>

```<code>sudo apt-get install php-intl
</code>```

Body:
install it from terminal

sudo apt-get install php-intl


问:
Generating a unique ID
I was looking into functions that generate unique IDs - my specific requirement is that the unique ID would need to be 8 digits only.

Anyway I've just realised we can set an ID auto increment field to start from any number. So suppose I have it start from 11111111 - am I right in thinking that all new records will increment from this value? If so then I have my unique 8 digit ID and no need to use a function for this.

And also if a record is deleted then will a new record re-use that deleted ID?

答:
1) Autoincrement-Values are not reused

2) Yes, by setting the autoincrement counter to an 8-digit number (e.g. 10000000), you can achieve this! (Table option "AUTO_INCREMENT = N")

Title: Generating a unique ID


问:
How to remove index.php from the URL in PHP CodeIgniter App hosted on Azure
I'm trying to run a PHP codeigniter website on Azure.

But when I set

```<code>$config['index_page'] = '';
</code>```

of my config.php it shows me an error saying "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable"

So once I set that to

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

I could load my website.

Now in my urls look like this

```<code>http://mysamplesite.azurewebsites.net/helloworld/index.php/Demo
</code>```

But I want that to be like this,

```<code>http://mysamplesite.azurewebsites.net/helloworld/Demo
</code>```

But every time when I remove that index.php part I got the above mentioned error.

I tried to change my htaccess file, but keep getting the error, this is my htaccess file,

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

Also I had to use site_url() instead of base_url.

So how can I drop index.php from the url?

答:
create a .htaccess file at your root directory
and put this code in it.

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

<Files "index.php">
AcceptPathInfo On
</Files>
</code>```

This will work!!!!

Body:
I'm trying to run a PHP codeigniter website on Azure.

But when I set

$config['index_page'] = '';

of my config.php it shows me an error saying "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable"

So once I set that to

$config['index_page'] = 'index.php';

I could load my website.

Now in my urls look like this

http://mysamplesite.azurewebsites.net/helloworld/index.php/Demo

But I want that to be like this,

http://mysamplesite.azurewebsites.net/helloworld/Demo

But every time when I remove that index.php part I got the above mentioned error.

I tried to change my htaccess file, but keep getting the error, this is my htaccess file,

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

Also I had to use site_url() instead of base_url.

So how can I drop index.php from the url?

Body:
create a .htaccess file at your root directory
and put this code in it.

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

<Files "index.php">
AcceptPathInfo On
</Files>

This will work!!!!


问:
how is this 'search' statement working?
I was reading a book and I am not able to find how this search: is working.

```<code>   search:while (true){
    n++;
    for(let i=2;i<=Math.sqrt(n);i++){
        if(n%i===0){
            continue search;
        }
    }
</code>```

Is it predefined in javascript, or what is it?

答:
It's a label, and continue tells the loop to go back to the label.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue#Using_continue_with_a_label

Title: how is this 'search' statement working?

Body:
I was reading a book and I am not able to find how this search: is working.

   search:while (true){
    n++;
    for(let i=2;i<=Math.sqrt(n);i++){
        if(n%i===0){
            continue search;
        }
    }

Is it predefined in javascript, or what is it?


问:
Executing two functions in an excel sheet?
I have this simple function

```<code>=IF(ISBLANK(H2)=TRUE,0,VLOOKUP(H2,$Q$3:$R$14,2,FALSE) J2=3)
</code>```

I want J2 to equal 3 and have it look-up on the table on false, is it possible or will I need to have another table setup for this?

答:
You need to make two formulas - one for vlookup, one for J2:

```<code>=IF(ISBLANK(H2)=TRUE,0,VLOOKUP(H2,$Q$3:$R$14,2,FALSE))
=IF(ISBLANK(H2)=TRUE,0,3)
</code>```

Place second formula to J2 cell.

Body:
I have this simple function

=IF(ISBLANK(H2)=TRUE,0,VLOOKUP(H2,$Q$3:$R$14,2,FALSE) J2=3)

I want J2 to equal 3 and have it look-up on the table on false, is it possible or will I need to have another table setup for this?

Body:
You need to make two formulas - one for vlookup, one for J2:

=IF(ISBLANK(H2)=TRUE,0,VLOOKUP(H2,$Q$3:$R$14,2,FALSE))
=IF(ISBLANK(H2)=TRUE,0,3)

Place second formula to J2 cell.


问:
django manage.py runserver hangs after second request (intermittent)
My Django 1.11 app (using runserver) hangs after several requests. It doesn't matter whether it's accessed by Chrome, Postman, or curl.

When it hangs, not even Ctrl+C can close it. The python.exe process must be killed.

I tried debugging it but when Django is stuck, Python cannot be paused to get the threads/stack.

答:
This actually happens to me due to Avast antivirus's Behavior Shield.

If you google it you find out that Avast has a long history of "hating" Python: https://www.google.co.id/search?q=avast+python

Solution: Avast > Settings > Components > Behavior Shield > Exclusions, then add your python.exe or your virtualenv's python.exe there: