问:
Getting the following code to work in both Chrome and Safari
Can't seem to figure out why this works in Safari but not in chrome. Any help would be much appreciated.

```<code>//Create or use existing DB
var db = openDatabase('myTest', '1.0', 'mySpecialDatabase', 200000);

if (db) {
  //New Transaction
  db.transaction(function (tx) {
  tx.executeSql('DROP TABLE IF EXISTS foo');
  tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
  //Insert test data
  tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "myTest")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (2, "another")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (3, "andYetAnother")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (4, "ohAndAgain")');
    });
    alert("DB success");
 }
else {
    alert("Oooops");
}

db.transaction(function (tx) {
    // Loop rows of DB, print values
    tx.executeSql('SELECT * FROM foo',[], function (tx, results) {
        var rows = results.rows;
        alert(rows.length);
        for (var index = 0; index < rows.length; index++) {
            var x = rows.item(index);
            alert(x.text);
        }
    });
});
</code>```

Throw it in JSFiddle in either browser, works as intended in latest release of Safari but no such luck in chrome.

EDIT

I managed to get it working in the end - code can be seen below.

```<code>var db = openDatabase('CBDB', '1.0', 'mySpecialDatabaseThatWontWork',10*1024*1024);

db.transaction(function (tx){
 tx.executeSql('DROP TABLE IF EXISTS cb');
 alert("dropped table");
 createDB();
 queryDB();
},
function (tx, error) {
    // error
    alert('0.Something went wrong: '+ error.message);
});

function createDB(){
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS cb (id unique, text)');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (1, "myTest")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (2, "another")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (3, "andYetAnother")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (4, "ohAndAgain")');
        alert("DB success");
        },
        function (tx, error) {
            // error
            alert('1.Something went wrong: '+ error.message);
        });
}

function queryDB(){
    db.transaction(function (tx) {
        tx.executeSql('SELECT * FROM cb',[], function (tx, results) {
            var rows = results.rows;
            alert(rows.length);
            for (var index = 0; index < rows.length; index++) {
                var x = rows.item(index);
                alert(x.text);
            }
        },
        function (tx, error) {
        // error
        alert('2.Something went wrong: '+ error.message);
        });
    });
}
</code>```

答:
Updated the code slightly, and this now works..</p>

```<code>var db = openDatabase('CBDB', '1.0', 'mySpecialDatabaseThatWontWork',10*1024*1024);

db.transaction(function (tx){
 tx.executeSql('DROP TABLE IF EXISTS cb');
 alert("dropped table");
 createDB();
 queryDB();
},
function (tx, error) {
    // error
    alert('0.Something went wrong: '+ error.message);
});

function createDB(){
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS cb (id unique, text)');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (1, "myTest")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (2, "another")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (3, "andYetAnother")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (4, "ohAndAgain")');
        alert("DB success");
        },
        function (tx, error) {
            // error
            alert('1.Something went wrong: '+ error.message);
        });
}

function queryDB(){
    db.transaction(function (tx) {
        tx.executeSql('SELECT * FROM cb',[], function (tx, results) {
            var rows = results.rows;
            alert(rows.length);
            for (var index = 0; index < rows.length; index++) {
                var x = rows.item(index);
                alert(x.text);
            }
        },
        function (tx, error) {
        // error
        alert('2.Something went wrong: '+ error.message);
        });
    });
}
</code>```

Body:
Can't seem to figure out why this works in Safari but not in chrome. Any help would be much appreciated.

//Create or use existing DB
var db = openDatabase('myTest', '1.0', 'mySpecialDatabase', 200000);

if (db) {
  //New Transaction
  db.transaction(function (tx) {
  tx.executeSql('DROP TABLE IF EXISTS foo');
  tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
  //Insert test data
  tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "myTest")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (2, "another")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (3, "andYetAnother")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (4, "ohAndAgain")');
    });
    alert("DB success");
 }
else {
    alert("Oooops");
}

db.transaction(function (tx) {
    // Loop rows of DB, print values
    tx.executeSql('SELECT * FROM foo',[], function (tx, results) {
        var rows = results.rows;
        alert(rows.length);
        for (var index = 0; index < rows.length; index++) {
            var x = rows.item(index);
            alert(x.text);
        }
    });
});

Throw it in JSFiddle in either browser, works as intended in latest release of Safari but no such luck in chrome.

EDIT

I managed to get it working in the end - code can be seen below.

var db = openDatabase('CBDB', '1.0', 'mySpecialDatabaseThatWontWork',10*1024*1024);

db.transaction(function (tx){
 tx.executeSql('DROP TABLE IF EXISTS cb');
 alert("dropped table");
 createDB();
 queryDB();
},
function (tx, error) {
    // error
    alert('0.Something went wrong: '+ error.message);
});

function createDB(){
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS cb (id unique, text)');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (1, "myTest")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (2, "another")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (3, "andYetAnother")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (4, "ohAndAgain")');
        alert("DB success");
        },
        function (tx, error) {
            // error
            alert('1.Something went wrong: '+ error.message);
        });
}

function queryDB(){
    db.transaction(function (tx) {
        tx.executeSql('SELECT * FROM cb',[], function (tx, results) {
            var rows = results.rows;
            alert(rows.length);
            for (var index = 0; index < rows.length; index++) {
                var x = rows.item(index);
                alert(x.text);
            }
        },
        function (tx, error) {
        // error
        alert('2.Something went wrong: '+ error.message);
        });
    });
}

Body:
Updated the code slightly, and this now works..

var db = openDatabase('CBDB', '1.0', 'mySpecialDatabaseThatWontWork',10*1024*1024);

db.transaction(function (tx){
 tx.executeSql('DROP TABLE IF EXISTS cb');
 alert("dropped table");
 createDB();
 queryDB();
},
function (tx, error) {
    // error
    alert('0.Something went wrong: '+ error.message);
});

function createDB(){
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS cb (id unique, text)');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (1, "myTest")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (2, "another")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (3, "andYetAnother")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (4, "ohAndAgain")');
        alert("DB success");
        },
        function (tx, error) {
            // error
            alert('1.Something went wrong: '+ error.message);
        });
}

function queryDB(){
    db.transaction(function (tx) {
        tx.executeSql('SELECT * FROM cb',[], function (tx, results) {
            var rows = results.rows;
            alert(rows.length);
            for (var index = 0; index < rows.length; index++) {
                var x = rows.item(index);
                alert(x.text);
            }
        },
        function (tx, error) {
        // error
        alert('2.Something went wrong: '+ error.message);
        });
    });
}


来源: stackexchange

问:
How to check mouseover operation changes the UI colour in selenium
I want to verify whether stars are lit up or not when I hover mouse on top of it.(Attached a Screenshot for better understanding). How can I verify whether it is lit up or not?

HTML structure of the element is as given below:

```<code><span class="wh-rating rating_4_5" style="display: inline-block;">
Rating:
<span data-s13732055i-ir="this" itemprop="ratingValue">4.5</span>
</span>
<div class="wh-rating-choices" style="display: none;">
<div class="wh-rating-choices-holder">
 <a class="hover" href="#">1</a>
 <a class="hover" href="#">2</a>
 <a class="hover" href="#">3</a>
 <a class="hover" href="#">4</a>
 <a class="hover" href="#">5</a>
 </div>
 </div>
</code>```

答:
I am answering this based on example DOM given below

```<code><ul class="rw-ui-stars">
<li class="rw-ui-star-0 rw-ui-star-selected"></li>
<li class="rw-ui-star-1 rw-ui-star-selected"></li>
<li class="rw-ui-star-2 rw-ui-star-selected"></li>
<li class="rw-ui-star-3 rw-ui-star-selected"></li>
<li class="rw-ui-star-4"></li></ul>
</code>```

on mouseovering the star, the class attribute changes to (here i have hoveredon 5stars)

```<code><ul class="rw-ui-stars">
<li class="rw-ui-star-0 rw-ui-star-over"></li>
<li class="rw-ui-star-1 rw-ui-star-over"></li>
<li class="rw-ui-star-2 rw-ui-star-over"></li>
<li class="rw-ui-star-3 rw-ui-star-over"></li>
<li class="rw-ui-star-4 rw-ui-star-over"></li></ul>
</code>```

As you can clearly notice that the class attribute value is changing on mouseover.

you can write following code to get this automated

```<code>public bool isStarsSelectedOnMouseOver(int n){
    Actions action = new Actions(driver);
    action.moveToElement(driver.findElement(by.xpath("//li[@class='rw-ui-star-"+(n-1)+"'"))).build().perform();

    List<WebElement> stars = driver.findElements(by.xpath("//ul[@class='rw-ui-stars'"));

    for(int i = 1; i <= n; i++){
        if(!stars.get(i).getAttribute("class").contains("rw-ui-star-over"))
            return false;
    }
    return true;
}
</code>```

Again the code is for illustration and can be modified according to your need

ContentLicense: CC BY-SA 3.0

Body:
I want to verify whether stars are lit up or not when I hover mouse on top of it.(Attached a Screenshot for better understanding). How can I verify whether it is lit up or not?

HTML structure of the element is as given below:

Rating:
4.5

 1
 2
 3
 4
 5

Body:
I am answering this based on example DOM given below

<ul class="rw-ui-stars">
<li class="rw-ui-star-0 rw-ui-star-selected"></li>
<li class="rw-ui-star-1 rw-ui-star-selected"></li>
<li class="rw-ui-star-2 rw-ui-star-selected"></li>
<li class="rw-ui-star-3 rw-ui-star-selected"></li>
<li class="rw-ui-star-4"></li></ul>

on mouseovering the star, the class attribute changes to (here i have hoveredon 5stars)

<ul class="rw-ui-stars">
<li class="rw-ui-star-0 rw-ui-star-over"></li>
<li class="rw-ui-star-1 rw-ui-star-over"></li>
<li class="rw-ui-star-2 rw-ui-star-over"></li>
<li class="rw-ui-star-3 rw-ui-star-over"></li>
<li class="rw-ui-star-4 rw-ui-star-over"></li></ul>

As you can clearly notice that the class attribute value is changing on mouseover.

you can write following code to get this automated

public bool isStarsSelectedOnMouseOver(int n){
    Actions action = new Actions(driver);
    action.moveToElement(driver.findElement(by.xpath("//li[@class='rw-ui-star-"+(n-1)+"'"))).build().perform();

    List<WebElement> stars = driver.findElements(by.xpath("//ul[@class='rw-ui-stars'"));

    for(int i = 1; i <= n; i++){
        if(!stars.get(i).getAttribute("class").contains("rw-ui-star-over"))
            return false;
    }
    return true;
}

Again the code is for illustration and can be modified according to your need


问:
Load a remote video with guzzle in laravel 5
I am trying to use guzzle to load and play a remote video uploaded in a subdomain (subdomain.domain.com) to a location in the main domain (domain.com).

I am finding it difficult to get the video to play.

The video player in the blade file has the following url for the video source

```<code>`<source src="{{url('video/'.$token.'/'.$videoname)}}" type="{{$video_mime_type}}">
</code>```

....`

The route for the source leads to a controller with the following code

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;
use Response;
use File;
use GuzzleHttp\Mimetypes;
use GuzzleHttp\Client;
use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Stream\Utils;

class ResourceController extends Controller
{

public function show_video_api($videoname)
{
    $client = new Client(['base_uri' => 'http://subdomain.domain.com/api/']);

    $resp = $client->request('GET',"video/".$videoname,['stream'=>true]);

    $body=$resp->getBody();
    echo $body;

   }

}
</code>```

The subdomain api methos is as follows:

```<code><?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;

class ServiceController extends Controller
{

public function video($videoname)
{

    return response()->file(storage_path("app/lesson-files/$videoname"));
}
}
</code>```

However, the video is not playing. I need this sorted out as fast as I can so I will appreciate any assistance to figure it out.

Thank you

答:
I think in Laravel you have to return a Response, not just print something to standard output (not sure if it's buffered). Do create a Response object instead of just echoing content.

But it's better to look at sink option in Guzzle and use it to output the response directly in cURL, skipping PHP.

But... You probably don't want to do it in PHP in any way, because it's a really slow way to serve video. Take a look at nginx, it's very flexible and fast for such use cases.

Body:
I am trying to use guzzle to load and play a remote video uploaded in a subdomain (subdomain.domain.com) to a location in the main domain (domain.com).

I am finding it difficult to get the video to play.

The video player in the blade file has the following url for the video source

`<source src="{{url('video/'.$token.'/'.$videoname)}}" type="{{$video_mime_type}}">

....`

The route for the source leads to a controller with the following code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;
use Response;
use File;
use GuzzleHttp\Mimetypes;
use GuzzleHttp\Client;
use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Stream\Utils;

class ResourceController extends Controller
{

public function show_video_api($videoname)
{
    $client = new Client(['base_uri' => 'http://subdomain.domain.com/api/']);

    $resp = $client->request('GET',"video/".$videoname,['stream'=>true]);

    $body=$resp->getBody();
    echo $body;

   }

}

The subdomain api methos is as follows:

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;

class ServiceController extends Controller
{

public function video($videoname)
{

    return response()->file(storage_path("app/lesson-files/$videoname"));
}
}

However, the video is not playing. I need this sorted out as fast as I can so I will appreciate any assistance to figure it out.

Thank you


问:
Raising elements of a list to a power
How can I raise the numbers in list to a certain power?</p>

答:
Another map pattern, using lambda instead of function.partial():

```<code>numbers=[1,2,3,4]
squares=list(map(lambda x:pow(x,2),numbers))
print(squares)
</code>```

Title: Raising elements of a list to a power

Body:
Another map pattern, using lambda instead of function.partial():

numbers=[1,2,3,4]
squares=list(map(lambda x:pow(x,2),numbers))
print(squares)


问:
How to autofill values in excel based on the cells above and below
good people, I have a table full of unique id's (as mentioned below) but there are missing values for few id's.

I want a formula/code to fill in the blanks based on the values above and below of any cell.

For example: here there are two empty rows between two unique id~(620006845180).

can anyone help me with filling up these spaces with the same value as above and below. :( I am stuck.

```<code>    620006845180
    xxxxxxxxxxxx
    xxxxxxxxxxxx
    620006845180
    620006845180
</code>```

答:
ok, sure.  this assumes the id's are in column A</p>

```<code>Sub FillBlankCells()

Dim lastRow As Long: lastRow = Cells(Rows.Count, 1).End(xlUp).Row
Dim IDRange As Range: Set IDRange = Range("A1:A" & lastRow)
Dim rng As Range

For Each rng In IDRange
  If rng.Value = "" Then
    If rng.End(xlUp).Value = rng.End(xlDown).Value Then _
    rng.Value = rng.End(xlUp).Value
  End If
Next rng

End Sub
</code>```

Body:
good people, I have a table full of unique id's (as mentioned below) but there are missing values for few id's.

I want a formula/code to fill in the blanks based on the values above and below of any cell.

For example: here there are two empty rows between two unique id~(620006845180).

can anyone help me with filling up these spaces with the same value as above and below. :( I am stuck.

    620006845180
    xxxxxxxxxxxx
    xxxxxxxxxxxx
    620006845180
    620006845180

Body:
ok, sure.  this assumes the id's are in column A

Sub FillBlankCells()

Dim lastRow As Long: lastRow = Cells(Rows.Count, 1).End(xlUp).Row
Dim IDRange As Range: Set IDRange = Range("A1:A" & lastRow)
Dim rng As Range

For Each rng In IDRange
  If rng.Value = "" Then
    If rng.End(xlUp).Value = rng.End(xlDown).Value Then _
    rng.Value = rng.End(xlUp).Value
  End If
Next rng

End Sub


问:
C#: How to make this method non-recursive
I have this recursive method which deletes empty folders:

```<code>    private void DeleteEmpty(DirectoryInfo directory)
    {
        foreach (var d in directory.GetDirectories())
        {
            DeleteEmpty(d);
        }

        if (directory.GetFileSystemInfos().Length == 0)
        {
            try
            {
                directory.Delete();
            }
            catch (Exception)
            {
                // Already gone, no permission, not empty, et cetera
            }
        }
    }
</code>```

How can I refactor this method so that it is not recursive?

答:
I had the same problem and I created a nice (imho) solution: beggining in a root directory, I "recursively" get the children directories and I store them in an ArrayList object. In this way, I create a list contaning first the higher level dirs, and at the end the deeper nested directories. This array is ideally divided in sub-arrays using the indexes stored in the levels ArrayList object.
Doing this, I can first check the deeper directories and delete them if they're empty, and then go back to the root level by level.

For example:

```<code>    private void directoryCleanup(string root)
    {
        try
        {
            // Create directory "tree"
            ArrayList dirs = new ArrayList();
            // Beginning and ending indexes for each level
            ArrayList levels = new ArrayList();
            int start = 0;
            dirs.Add(root);
            while (start < dirs.Count)
            {
                ArrayList temp = new ArrayList();
                for (int i = start; i < dirs.Count; i++)
                {
                    DirectoryInfo dinfo = new DirectoryInfo((string)dirs[i]);
                    DirectoryInfo[] children = dinfo.GetDirectories();
                    for (int j = 0; j < children.Length; j++)
                    {
                        temp.Add(children[j].FullName);
                    }
                    Array.Clear(children, 0, children.Length);
                    children = null;
                    dinfo = null;
                }
                start = dirs.Count;
                levels.Add(dirs.Count);
                dirs.AddRange(temp);
                temp.Clear();
                temp = null;
            }
            levels.Reverse();
            // Navigate the directory tree level by level, starting with the deepest one
            for (int i = 0; i < levels.Count - 1; i++)
            {
                int end = (int)levels[i] - 1;
                int begin = (int)levels[i + 1];
                for (int j = end; j >= begin; j--)
                {
                    string path = (string)dirs[j];
                    if (Directory.GetFileSystemEntries(path).Length == 0)
                    {
                        Directory.Delete(path);
                    }
                }
            }
            levels.Clear();
            levels = null;
            dirs.Clear();
            dirs = null;
        }
        catch (IOException ioex)
        {
            // Manage exception
            return;
        }
        catch (Exception e)
        {
            // Manage exception
            return;
        }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this recursive method which deletes empty folders:

    private void DeleteEmpty(DirectoryInfo directory)
    {
        foreach (var d in directory.GetDirectories())
        {
            DeleteEmpty(d);
        }

        if (directory.GetFileSystemInfos().Length == 0)
        {
            try
            {
                directory.Delete();
            }
            catch (Exception)
            {
                // Already gone, no permission, not empty, et cetera
            }
        }
    }

How can I refactor this method so that it is not recursive?

Body:
I had the same problem and I created a nice (imho) solution: beggining in a root directory, I "recursively" get the children directories and I store them in an ArrayList object. In this way, I create a list contaning first the higher level dirs, and at the end the deeper nested directories. This array is ideally divided in sub-arrays using the indexes stored in the levels ArrayList object.
Doing this, I can first check the deeper directories and delete them if they're empty, and then go back to the root level by level.

For example:

    private void directoryCleanup(string root)
    {
        try
        {
            // Create directory "tree"
            ArrayList dirs = new ArrayList();
            // Beginning and ending indexes for each level
            ArrayList levels = new ArrayList();
            int start = 0;
            dirs.Add(root);
            while (start < dirs.Count)
            {
                ArrayList temp = new ArrayList();
                for (int i = start; i < dirs.Count; i++)
                {
                    DirectoryInfo dinfo = new DirectoryInfo((string)dirs[i]);
                    DirectoryInfo[] children = dinfo.GetDirectories();
                    for (int j = 0; j < children.Length; j++)
                    {
                        temp.Add(children[j].FullName);
                    }
                    Array.Clear(children, 0, children.Length);
                    children = null;
                    dinfo = null;
                }
                start = dirs.Count;
                levels.Add(dirs.Count);
                dirs.AddRange(temp);
                temp.Clear();
                temp = null;
            }
            levels.Reverse();
            // Navigate the directory tree level by level, starting with the deepest one
            for (int i = 0; i < levels.Count - 1; i++)
            {
                int end = (int)levels[i] - 1;
                int begin = (int)levels[i + 1];
                for (int j = end; j >= begin; j--)
                {
                    string path = (string)dirs[j];
                    if (Directory.GetFileSystemEntries(path).Length == 0)
                    {
                        Directory.Delete(path);
                    }
                }
            }
            levels.Clear();
            levels = null;
            dirs.Clear();
            dirs = null;
        }
        catch (IOException ioex)
        {
            // Manage exception
            return;
        }
        catch (Exception e)
        {
            // Manage exception
            return;
        }
    }


问:
Call Laravel controller from code and pass HTTP headers to it
To call a controller I use a CURL request like this:

```<code>curl -kX POST https://site/method  -H 'Authorization: Bearer ACCESS_TOKEN\
Content-Type:application/json' -d '
{
    "param1":"value 1",
    "param2":"value 2",
    "param3":"value 3"
}'
</code>```

The route calls UserController@method.

How can I do the same from Laravel code (internal request, not sending CURL)?

I've found an advice to use something like this

```<code>        $controller = app()->make($controllerName);
        $response = app()->call([$controller, 'method'], []);
        echo $response;
</code>```

where the last [] should contain some parameters. But if this is the way, I cannot figure out how the array should look in my case.

P.S. Please, don't answer "it's a bad practice" instead of giving an advice how to implement what I need.

答:
Here is my solution (Laravel 5.4). Inspired by https://stackoverflow.com/a/40366119/518704 but needed much time to dig into the code to find how to pass my Authorization: Bearer token

I need this approach to authorize in a browser-less socket connection (Ratchet), where JS code is not running. So I could not use Ratchet WebSocket, only simple socket Ratchet IoServer. My API controller returns JSON so it's easy to work with the response further. I need this approach mainly to authenticate the socket connection assuming the client knows the access token when one opens the socket (got by REST on login).

First of all I need to use a trait, used in Tests

Next in onMessage code I assume a JSON message is passed with the access token. To simplify here I don't write JSON validity check etc.

```<code>namespace App;

use Ratchet\ConnectionInterface;
use Askedio\LaravelRatchet\RatchetServer as RatchetServerBase;

class RatchetServer extends RatchetServerBase
{
...
    public function onMessage(ConnectionInterface $conn, $input)
    {
          $input = json_decode($input);
          $token = $input->token;

          // Some data (may be taken from JSON $input)
          $data = [
            "param1" => "value 1",
            "param2" => "value 2",
            "param3" => "value 3"
          ];

          // Prepare the server headers
          $server = ['HTTP_AUTHORIZATION' => 'Bearer ' . $token];

          // This way! If calling app() here, it reuses the same Auth::user()
          $app = require __DIR__.'/../bootstrap/app.php';
          $kernel = $app->make(\Illuminate\Contracts\Http\Kernel::class);
          $response = $kernel->handle(
              $request = \Illuminate\Http\Request::create('/user', 'GET', $data, [], [], $server)
          );
          // ~ var_dump(Auth::id());
          $controllerResult = $response->getContent();
          $kernel->terminate($request, $response);

          // My controller hidden under /user route is an API one and returns JSON string
          echo $controllerResult;
    }
...
}
</code>```

My previous solution didn't work. The Auth::user() always returned the
  first logged in user (app() seemed to use singleton). So I leave the
  previous code for reference purpose.

```<code>namespace App;

use Ratchet\ConnectionInterface;
use Askedio\LaravelRatchet\RatchetServer as RatchetServerBase;

class RatchetServer extends RatchetServerBase
{
    use \Illuminate\Foundation\Testing\Concerns\MakesHttpRequests;

...
    public function onMessage(ConnectionInterface $conn, $input)
    {
          $input = json_decode($input);
          $token = $input->token;

          $data = [
            "param1" => "value 1",
            "param2" => "value 2",
            "param3" => "value 3"
          ];

          // The 2 lines below can me moved to the __constructor method
          $this->baseUrl = request()->getSchemeAndHttpHost();
          $this->app     = app();

          // Prepare the server headers
          $server = ['HTTP_AUTHORIZATION' => 'Bearer ' . $token];

          // Call my controller by route (this seems to be internal call)
          $response = $this->call('GET','/method', $data, [], [], $server)->json();
    }
...
}
</code>```

P.S. Just a note for myself when I come here later. Too see available headers and proper naming I did a var_dump in for $this->parameters ./vendor/symfony/http-foundation//ServerBag.php

Body:
To call a controller I use a CURL request like this:

curl -kX POST https://site/method  -H 'Authorization: Bearer ACCESS_TOKEN\
Content-Type:application/json' -d '
{
    "param1":"value 1",
    "param2":"value 2",
    "param3":"value 3"
}'

The route calls UserController@method.

How can I do the same from Laravel code (internal request, not sending CURL)?

I've found an advice to use something like this

        $controller = app()->make($controllerName);
        $response = app()->call([$controller, 'method'], []);
        echo $response;

where the last [] should contain some parameters. But if this is the way, I cannot figure out how the array should look in my case.

P.S. Please, don't answer "it's a bad practice" instead of giving an advice how to implement what I need.

Body:
Here is my solution (Laravel 5.4). Inspired by https://stackoverflow.com/a/40366119/518704 but needed much time to dig into the code to find how to pass my Authorization: Bearer token

I need this approach to authorize in a browser-less socket connection (Ratchet), where JS code is not running. So I could not use Ratchet WebSocket, only simple socket Ratchet IoServer. My API controller returns JSON so it's easy to work with the response further. I need this approach mainly to authenticate the socket connection assuming the client knows the access token when one opens the socket (got by REST on login).

First of all I need to use a trait, used in Tests

Next in onMessage code I assume a JSON message is passed with the access token. To simplify here I don't write JSON validity check etc.

namespace App;

use Ratchet\ConnectionInterface;
use Askedio\LaravelRatchet\RatchetServer as RatchetServerBase;

class RatchetServer extends RatchetServerBase
{
...
    public function onMessage(ConnectionInterface $conn, $input)
    {
          $input = json_decode($input);
          $token = $input->token;

          // Some data (may be taken from JSON $input)
          $data = [
            "param1" => "value 1",
            "param2" => "value 2",
            "param3" => "value 3"
          ];

          // Prepare the server headers
          $server = ['HTTP_AUTHORIZATION' => 'Bearer ' . $token];

          // This way! If calling app() here, it reuses the same Auth::user()
          $app = require __DIR__.'/../bootstrap/app.php';
          $kernel = $app->make(\Illuminate\Contracts\Http\Kernel::class);
          $response = $kernel->handle(
              $request = \Illuminate\Http\Request::create('/user', 'GET', $data, [], [], $server)
          );
          // ~ var_dump(Auth::id());
          $controllerResult = $response->getContent();
          $kernel->terminate($request, $response);

          // My controller hidden under /user route is an API one and returns JSON string
          echo $controllerResult;
    }
...
}

My previous solution didn't work. The Auth::user() always returned the
  first logged in user (app() seemed to use singleton). So I leave the
  previous code for reference purpose.

namespace App;

use Ratchet\ConnectionInterface;
use Askedio\LaravelRatchet\RatchetServer as RatchetServerBase;

class RatchetServer extends RatchetServerBase
{
    use \Illuminate\Foundation\Testing\Concerns\MakesHttpRequests;

...
    public function onMessage(ConnectionInterface $conn, $input)
    {
          $input = json_decode($input);
          $token = $input->token;

          $data = [
            "param1" => "value 1",
            "param2" => "value 2",
            "param3" => "value 3"
          ];

          // The 2 lines below can me moved to the __constructor method
          $this->baseUrl = request()->getSchemeAndHttpHost();
          $this->app     = app();

          // Prepare the server headers
          $server = ['HTTP_AUTHORIZATION' => 'Bearer ' . $token];

          // Call my controller by route (this seems to be internal call)
          $response = $this->call('GET','/method', $data, [], [], $server)->json();
    }
...
}

P.S. Just a note for myself when I come here later. Too see available headers and proper naming I did a var_dump in for $this->parameters ./vendor/symfony/http-foundation//ServerBag.php


问:
How to use row_number() to filter duplicates with multiple joins?
I need to filter duplicates in base of other column. This is the code I am trying. Unfortunately, it doesn't work as the query never finish.

```<code>Select r1, r2, r3...,rb1,..., rc1,...
From (
  Select *, ROW_NUMBER() OVER (PARTITION BY r1 order by r6 DESC) AS rownbr
  From
    table1
    join table2 ON r2=rb1
    Join table3 ON r6=rc1
    Join table4 ON rx=rdx
) source
Where
  rownbr=1
</code>```

Any ideas?

答:
Syntactically, you seem to have got the query correct. However, in joining with 4 tables without any where clause you may be trying to retrieve way too much data. A couple of easy things that could improve the query would be:

only specify the columns that you need in the subquery. I'm pretty sure you don't need everything from all 4 tables.

find out if you can be more specific with the data you are trying to fetch and use it in the where clause. For instance, you may only want data where t1.createdate > '01-01-2016'

if these still don't help, you will have to start looking into indexes.

    Select r1, r2, r3,rb1
    From (
      Select * -- consider specifying only the columns that you need. Pretty sure you don't need every column from all 4 tables.
      , ROW_NUMBER() OVER (PARTITION BY r1 order by r6 DESC) AS rownbr
      From table1 as t1
        join table2 as t2 ON t1.r2 = t2.rb1
        Join table3 as t3 ON t3.r6 = t2.rc1
        Join table4 as t4 ON t4.rx = t3.rdx
        where --may be something like date
        t1.createdate > '01-01-2016'
    ) source
    Where  source.rownbr=1
```

Body:
I need to filter duplicates in base of other column. This is the code I am trying. Unfortunately, it doesn't work as the query never finish.

Select r1, r2, r3...,rb1,..., rc1,...
From (
  Select *, ROW_NUMBER() OVER (PARTITION BY r1 order by r6 DESC) AS rownbr
  From
    table1
    join table2 ON r2=rb1
    Join table3 ON r6=rc1
    Join table4 ON rx=rdx
) source
Where
  rownbr=1

Any ideas?

ContentLicense: CC BY-SA 4.0


问:
css adjusting vertical positioning of fixed element
I'm having troubles with positioning the textbox for my chat. I can only make it look good for one specific resolution. On other screen sizes it just looks terrible. How can I adjust the position of the textbox for all resolutions (>1360px) to fit in the little darkgrey area on the bottom. When I try to adjust it for one resolution it won't look good on the other resolutions.

https://jsfiddle.net/4pvfwz11/1/

```<code><div class="chatdiv hidden-xs hidden-sm  col-lg-2 col-md-3 pull-right" data-spy="affix">
<div class="scrollbar" id="style-2">
    <div class="force-overflow"></div>
    <ol class="chat">
        <div id="fullchat">
            <li class="bot"><div class="avatar"><img src="'+msg.avatar+'" draggable="false"/></div><div class="msg"><div class="name">Username</div><p>The chat text should come here..........</p><time><i class="fa fa-clock-o" aria-hidden="true"></i>19:00</time></div></li>
        </div>
        <div class="chat_error"></div>
    </ol>
</div>
<div class="toggle-sound"></div>
    <input class="textarea" id="chat_textbox" type="text" placeholder="Enter message here"/>

<style type="text/css">

div.chat_error {
    color: #e20f0f;
    padding-left: 10px;
    padding-top: 1rem;
}

.chatdiv
{
    position: fixed;
    left: 40px;
    background-color: #101010;
    height: 90vh;
}

.chatdiv .name{
    top: 3px;
    left: 110px;
    font-size: 10px;
    font-weight: bold;
    color: rgba(256,256,256,0.80);
    cursor: default;
}

/* M E S S A G E S */

.chat {
    list-style: none;
    background: none;
    margin: 0;
    padding: 0 0 50px 0;
    margin-top: 60px;
    margin-bottom: 10px;
}
.chat li {
    padding: 0.5rem;
    overflow: hidden;
    display: flex;
}

.chat .avatar img {
    margin-top: 15px;
    width: 40px;
    height: 40px;
    border-radius: 100%;
    -webkit-border-radius: 100%;
    -moz-border-radius: 100%;
    -ms-border-radius: 100%;
    background-color: rgba(255,255,255,0.9);
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
}

.other .msg {
    order: 1;
    border-top-left-radius: 0px;
    box-shadow: -1px 2px 0px #187006;
    margin-left: 10px;
    background-color: #27af0c;
}

.self {
    justify-content: flex-end;
    align-items: flex-end;
}
.self .msg {
    order: 1;
    border-bottom-right-radius: 0px;
    background-color: #0a95db;
    box-shadow: 1px 2px 0px #055f8c;
    margin-left: 10px;
}

.bot .msg {
    order: 1;
    border-bottom-right-radius: 0px;
    background-color: #a50808;
    box-shadow: 1px 2px 0px #6b0606;
    margin-left: 10px;
}

.msg {
    background: white;
    min-width: 50px;
    padding: 10px;
    border-radius: 2px;
    box-shadow: 0px 2px 0px rgba(0, 0, 0, 0.07);
}
.msg p {
    font-size: 15px;
    margin: 0 0 0.2rem 0;
    color: white;
}

.msg time {
    font-size: 10px;
    color: #ccc;
    margin-top: 3px;
    float: right;
    cursor: default;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
}

/* T Y P E */

input.textarea {
    position: absolute;
    width: 89%;
    height: 50px;
    left: 15px;
    bottom: 3vh;
    background: white;
    border: none;
    outline: none;
    padding-left: 10px;
    padding-right: 10px;
    color: #666;
    font-weight: 400;
}

div.toggle-sound {
    position: fixed;
    bottom: 13vh;
    left: 65px;
    font-weight: bold;
    font-size: 20px;
}

.scrollbar
{
    float: left;
    height: 80vh;
    background-color: #232323;
    overflow-y: scroll;
    margin-bottom: 25px;
    width: 100%;
}

.force-overflow
{
    min-height: 90vh;
}

#style-2::-webkit-scrollbar-track
{
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    border-radius: 10px;
    background-color: #232323;
}

#style-2::-webkit-scrollbar
{
    width: 12px;
    background-color: #232323;
}

#style-2::-webkit-scrollbar-thumb
{
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
    background-color: #E20F0F;
}
</style>
</code>```

答:
If you want different CSS for different screen sizes you can use something called media queries. I don't know exactly what rules you want to change for different screen sizes, but let's do a quick example. Let's say you want to make the background color of the textbox red on screens with a width less than or equal to 900px. This can be done with the following media query:

```<code>@media (max-width: 900px) {
  input.textarea {
    background-color: red;
  }
}
</code>```

So what you can do is just to figure out what CSS changes you want to do on different screen sizes, and then make media queries for all of them. You can read more about media queries here.

Body:
I'm having troubles with positioning the textbox for my chat. I can only make it look good for one specific resolution. On other screen sizes it just looks terrible. How can I adjust the position of the textbox for all resolutions (>1360px) to fit in the little darkgrey area on the bottom. When I try to adjust it for one resolution it won't look good on the other resolutions.

https://jsfiddle.net/4pvfwz11/1/

Username

The chat text should come here..........
<time>19:00</time>

    <input class="textarea" id="chat_textbox" type="text" placeholder="Enter message here"/>

Body:
If you want different CSS for different screen sizes you can use something called media queries. I don't know exactly what rules you want to change for different screen sizes, but let's do a quick example. Let's say you want to make the background color of the textbox red on screens with a width less than or equal to 900px. This can be done with the following media query:

@media (max-width: 900px) {
  input.textarea {
    background-color: red;
  }
}

So what you can do is just to figure out what CSS changes you want to do on different screen sizes, and then make media queries for all of them. You can read more about media queries here.


问:
Binary search tree null pointer exception with traversal
I am implementing a binary search tree in java, writing the methods recursively. I did the insert methods, and now I am stuck on the first traversal method, the in order one. When I call it in my test code, after adding a few elements, (tree.inorderTraversal), I get a null pointer exception at the rescursive in order method, and I don't see why. Could it be something wrong with the insert method? </p>

```<code>public void insertInBinaryTree(E newItem)
{
    BinaryTreeNode<E> node = new BinaryTreeNode<E>(newItem);
    if (root == null) {
        root = node;
    } else {
        insert(root, newItem);
    }
}

// Recursively insert a node containing newItem into a non-empty tree. Used
// by insertInBinaryTree
private void insert(BinaryTreeNode<E> treeNode, E newItem)
{
    if (newItem.compareTo(treeNode.getItem()) < 0) {
        if (treeNode.getLeftChild() != null) {
            insert(treeNode.getLeftChild(), newItem);
        }
        else {
            treeNode.setLeftChild(new BinaryTreeNode<E>(newItem));
        }
    }
    else {
        if (treeNode.getRightChild() != null) {
            insert(treeNode.getRightChild(), newItem);
        }
        else {
            treeNode.setRightChild(new BinaryTreeNode<E>(newItem));
        }
    }
}

// If the tree is not empty, initiates an inorder traversal. This should
// print all items in ascending order. If the tree is empty, just prints
// "Tree is empty"
public void inorderTraversal()
{
    System.out.println("\nInorder Traversal");

    if (root == null) {
        System.out.println("Tree is empty");
    } else {
        inorder(root);
    }

}

// Recursive inorder traversal of a non-empty tree. Used by
// inorderTraversal.
private void inorder(BinaryTreeNode<E> treeNode)
{
    inorder(treeNode.getLeftChild());
    System.out.print(treeNode.getItem());
    inorder(treeNode.getRightChild());
}
</code>```

答: In the inorder method, since its recursive method the first statement should check for null on the argument and if it is so it should return. Otherwise the recursion never ends and it runs into NPE when accessing treeNode.getLeftChild() or treeNode.getRightChild() on  possible null when there is no left child node or right child node.</p>

Body:
I am implementing a binary search tree in java, writing the methods recursively. I did the insert methods, and now I am stuck on the first traversal method, the in order one. When I call it in my test code, after adding a few elements, (tree.inorderTraversal), I get a null pointer exception at the rescursive in order method, and I don't see why. Could it be something wrong with the insert method?

public void insertInBinaryTree(E newItem)
{
    BinaryTreeNode<E> node = new BinaryTreeNode<E>(newItem);
    if (root == null) {
        root = node;
    } else {
        insert(root, newItem);
    }
}

// Recursively insert a node containing newItem into a non-empty tree. Used
// by insertInBinaryTree
private void insert(BinaryTreeNode<E> treeNode, E newItem)
{
    if (newItem.compareTo(treeNode.getItem()) < 0) {
        if (treeNode.getLeftChild() != null) {
            insert(treeNode.getLeftChild(), newItem);
        }
        else {
            treeNode.setLeftChild(new BinaryTreeNode<E>(newItem));
        }
    }
    else {
        if (treeNode.getRightChild() != null) {
            insert(treeNode.getRightChild(), newItem);
        }
        else {
            treeNode.setRightChild(new BinaryTreeNode<E>(newItem));
        }
    }
}

// If the tree is not empty, initiates an inorder traversal. This should
// print all items in ascending order. If the tree is empty, just prints
// "Tree is empty"
public void inorderTraversal()
{
    System.out.println("\nInorder Traversal");

    if (root == null) {
        System.out.println("Tree is empty");
    } else {
        inorder(root);
    }

}

// Recursive inorder traversal of a non-empty tree. Used by
// inorderTraversal.
private void inorder(BinaryTreeNode<E> treeNode)
{
    inorder(treeNode.getLeftChild());
    System.out.print(treeNode.getItem());
    inorder(treeNode.getRightChild());
}


问:
Pass array in post request using Guzzle
I am trying to pass array in post request payload.

```<code>url = http://IP:PortNo/index.php/v1/login
</code>```

payload:

```<code>data={ "terminal_id": "terminal_id", "api_login": "api_login", "api_key": "api_key", "merchant_code": "merchant_code" }
</code>```

what i did is:

```<code>$data = ['terminal_id' => $this->terminal_id , 'api_login' => $this->api_login,
        'api_key' => $this->api_key , 'merchant_code' => $this->merchant_code];
$response = $this->client->post($url, array('data' => $data));
</code>```

but the response i am getting is:

"Request data not found"

this means my data payload is not correctly formed. any idea?

答:
```<code>$response = $this->client->post($url, ['json' => $data]);
</code>```

See the Guzzle6 manual in the section entitled json: http://docs.guzzlephp.org/en/stable/request-options.html#json

Title: Pass array in post request using Guzzle

Body:
I am trying to pass array in post request payload.

url = http://IP:PortNo/index.php/v1/login

payload:

data={ "terminal_id": "terminal_id", "api_login": "api_login", "api_key": "api_key", "merchant_code": "merchant_code" }

what i did is:

$data = ['terminal_id' => $this->terminal_id , 'api_login' => $this->api_login,
        'api_key' => $this->api_key , 'merchant_code' => $this->merchant_code];
$response = $this->client->post($url, array('data' => $data));

but the response i am getting is:

"Request data not found"

this means my data payload is not correctly formed. any idea?

Body:
$response = $this->client->post($url, ['json' => $data]);

See the Guzzle6 manual in the section entitled json: http://docs.guzzlephp.org/en/stable/request-options.html#json


问:
How to change dynamically the xib of a UIVIewController
I have an UIVIewController "controller1" for instance. This controller is instanciated with initWithNibName... with "file1.xib".
I want to dynamically change the xib file of my "controller1" to "file2.xib"

To resume :

"controller1" <-> "file1.xib"
and I want to dynamically have :
"controler1" <-> "file2.xib"

How can I do this ?

Hope I was clear.

答:
When you want to change views in a UIViewController just just use this code:</p>

```<code>NSArray *nibObjs = [[NSBundle mainBundle] loadNibNamed:@"file2" owner:self options:nil];
UIView *aView = [nibObjs objectAtIndex:0];
self.view = aView;
</code>```

Body:
When you want to change views in a UIViewController just just use this code:

NSArray *nibObjs = [[NSBundle mainBundle] loadNibNamed:@"file2" owner:self options:nil];
UIView *aView = [nibObjs objectAtIndex:0];
self.view = aView;


问:
How to deploy a wolkenkit application to digital ocean?
Currently I'm working on a project using wolkenkit (https://www.wolkenkit.io/).
Everything works fine locally on my machine (it comes with a docker container). Now I want to deploy it to digital ocean to go one step further.

In the official documentation there are a few lines about assigning a docker machine (https://docs.wolkenkit.io/1.0.1/reference/configuring-an-application/assigning-a-docker-machine/).

Are there any guides/advices/tutorials addressing this topic in a more detail way suitable for digital ocean?

答:
Disclaimer: I am one of the developers of wolkenkit, so please take my answer with a grain of salt.

Basically, it first depends on how you have created the machine: As you basically need a machine that runs Docker, the easiest way is to use docker-machine to set it up. For details on this see the Docker documentation.

Once you have done this, you have two options of how to proceed:

You can use the docker-machine env command to select the DigitalOcean machine is the currently active machine, and then run wolkenkit start as usual. Since the selected machine is stored within a number of environment variables such as DOCKER_HOST, the wolkenkit CLI tool uses these information to access the Docker host.

The second option is to add a new environment to your wolkenkit application's package.json file as described here. Generally, all you need to do is to provide the name of the docker-machine machine that you have created. In this case, the wolkenkit CLI will take care of configuring the connection automatically, so you don't have to do this manually. You then start your application using wolkenkit start --env production, assuming that your environment is called production.

The first approach works best if you don't often change your machines. The second is best if you to work locally most of the times, and rarely deploy to the cloud. The latter approach also enables you to define multiple environments, such as production, staging, test, … and deploy to one or the other, depending on a command-line flag.

Please note that you may also use the WOLKENKIT_ENV environment variable to define a default environment other than default (which is the CLI's default value).

Hope this helps :-)

PS: Please note that your droplet should have at least 1 GByte of RAM, so the smallest instance may be too small. If you use a droplet with too little RAM, the Docker containers seem to start as expected, but they won't be reachable from the outside.

PPS: Please also note that you need to have a valid certificate for your droplet, otherwise the CLI will not be able to detect whether the application is running or not (because it then can't get past beyond the invalid certificate). This will probably be changed in a future version of the CLI.


问:
c++ template recursion double linked list error gcc (but clang++ accepts)
This example code:

```<code>#include <string>
#include <iostream>

template <int i>
struct Wrapper
{
    static const std::string _str;
    typedef const Wrapper<i+1> NextType_t; // template recursion
    static NextType_t _nxt;
    typedef const Wrapper<i-1> PrevType_t; // template recursion
    static PrevType_t _prev;
};

template<int i>
const std::string Wrapper<i>::_str = std::to_string(i);

template<int i>
typename Wrapper<i>::NextType_t Wrapper<i>::_nxt;

template<int i>
typename Wrapper<i>::PrevType_t Wrapper<i>::_prev;

// recursion termination - lower bound
template <>
struct Wrapper<-1>
{
        static const std::string _str;
        typedef const Wrapper<0> NextType_t;
        static NextType_t _nxt;
        typedef const Wrapper<-1> PrevType_t;
        static PrevType_t _prev;
};

const std::string Wrapper<-1>::_str = std::to_string(-1);

typename Wrapper<-1>::NextType_t Wrapper<-1>::_nxt;
typename Wrapper<-1>::PrevType_t Wrapper<-1>::_prev;

// recursion termination - upper bound
template <>
struct Wrapper<UPPER_LIMIT>
{
    static const std::string _str;
    typedef const Wrapper<-1> NextType_t;
    static NextType_t _nxt;
    typedef const Wrapper<UPPER_LIMIT-1> PrevType_t;
    static PrevType_t _prev;
};

const std::string Wrapper<UPPER_LIMIT>::_str = std::to_string(UPPER_LIMIT);

typename Wrapper<UPPER_LIMIT>::NextType_t Wrapper<UPPER_LIMIT>::_nxt;
typename Wrapper<UPPER_LIMIT>::PrevType_t Wrapper<UPPER_LIMIT>::_prev;

int
main(
    int argc,
    char **)
{
    Wrapper<0> wrapperFirst;
    Wrapper<UPPER_LIMIT> wrapperLast;

    // here's the list
    std::cout << wrapperFirst._str << std::endl;
    std::cout << wrapperFirst._nxt._str << std::endl;
    std::cout << wrapperFirst._nxt._nxt._str << std::endl;
    // [...]

    // and the final element
    std::cout << wrapperLast._str << std::endl;
    std::cout << wrapperLast._prev._str << std::endl;
    std::cout << wrapperLast._prev._prev._str << std::endl;
    // [...]

    // and the tailing NIL
    std::cout << Wrapper<UPPER_LIMIT>::NextType_t::_str << std::endl;

    return 0;
}
</code>```

fails for gcc:

```<code>> g++ -std=c++11 -DUPPER_LIMIT=100 -ftemplate-depth=500 -o test main.cpp
main.cpp: In instantiation of ‘struct Wrapper<499>’:
main.cpp:24:33:   recursively required from ‘struct Wrapper<1>’
main.cpp:24:33:   required from ‘struct Wrapper<0>’
main.cpp:43:47:   required from here
main.cpp:24:33: fatal error: template instantiation depth exceeds maximum of 500 (use -ftemplate-depth= to increase the maximum)
 typename Wrapper<i>::NextType_t Wrapper<i>::_nxt;
                             ^~~~~~~~~~
compilation terminated.
</code>```

but succeeds for clang:

```<code>> clang++ -std=c++11 -DUPPER_LIMIT=100 -ftemplate-depth=500 -o test main.cpp
> ./test
0
1
2
100
99
98
-1
</code>```

Is there something wrong in the code? I wonder that gcc wants to go beyond the UPPER_LIMIT, because there is a terminating specialization for that.

答:
Wrapper<-1> is instantiated on this line

```<code>typename Wrapper<-1>::NextType_t Wrapper<-1>::_nxt;
</code>```

This causes Wrapper<0> to be instantiated, which causes Wrapper<1> to be instantiated, etc.  At that point in the code, the specialization for Wrapper<UPPER_LIMIT> has not been defined, so this causes an infinite recursion.

Moving the definition of the Wrapper<UPPER_LIMIT> specialization above the Wrapper<-1>::_nxt definition solves the problem.

Apparently Clang defers instantiation, so that this problem doesn't arise.

Body:
This example code:

#include <string>
#include <iostream>

template <int i>
struct Wrapper
{
    static const std::string _str;
    typedef const Wrapper NextType_t; // template recursion
    static NextType_t _nxt;
    typedef const Wrapper PrevType_t; // template recursion
    static PrevType_t _prev;
};

template<int i>
const std::string Wrapper::_str = std::to_string(i);

template<int i>
typename Wrapper::NextType_t Wrapper::_nxt;

template<int i>
typename Wrapper::PrevType_t Wrapper::_prev;

// recursion termination - lower bound
template <>
struct Wrapper<-1>
{
        static const std::string _str;
        typedef const Wrapper<0> NextType_t;
        static NextType_t _nxt;
        typedef const Wrapper<-1> PrevType_t;
        static PrevType_t _prev;
};

const std::string Wrapper<-1>::_str = std::to_string(-1);

typename Wrapper<-1>::NextType_t Wrapper<-1>::_nxt;
typename Wrapper<-1>::PrevType_t Wrapper<-1>::_prev;

// recursion termination - upper bound
template <>
struct Wrapper<UPPER_LIMIT>
{
    static const std::string _str;
    typedef const Wrapper<-1> NextType_t;
    static NextType_t _nxt;
    typedef const Wrapper<UPPER_LIMIT-1> PrevType_t;
    static PrevType_t _prev;
};

const std::string Wrapper<UPPER_LIMIT>::_str = std::to_string(UPPER_LIMIT);

typename Wrapper<UPPER_LIMIT>::NextType_t Wrapper<UPPER_LIMIT>::_nxt;
typename Wrapper<UPPER_LIMIT>::PrevType_t Wrapper<UPPER_LIMIT>::_prev;

int
main(
    int argc,
    char **)
{
    Wrapper<0> wrapperFirst;
    Wrapper<UPPER_LIMIT> wrapperLast;

    // here's the list
    std::cout << wrapperFirst._str << std::endl;
    std::cout << wrapperFirst._nxt._str << std::endl;
    std::cout << wrapperFirst._nxt._nxt._str << std::endl;
    // [...]

    // and the final element
    std::cout << wrapperLast._str << std::endl;
    std::cout << wrapperLast._prev._str << std::endl;
    std::cout << wrapperLast._prev._prev._str << std::endl;
    // [...]

    // and the tailing NIL
    std::cout << Wrapper<UPPER_LIMIT>::NextType_t::_str << std::endl;

    return 0;
}

fails for gcc:

> g++ -std=c++11 -DUPPER_LIMIT=100 -ftemplate-depth=500 -o test main.cpp
main.cpp: In instantiation of ‘struct Wrapper<499>’:
main.cpp:24:33:   recursively required from ‘struct Wrapper<1>’
main.cpp:24:33:   required from ‘struct Wrapper<0>’
main.cpp:43:47:   required from here
main.cpp:24:33: fatal error: template instantiation depth exceeds maximum of 500 (use -ftemplate-depth= to increase the maximum)
 typename Wrapper::NextType_t Wrapper::_nxt;
                             ^~~~~~~~~~
compilation terminated.

but succeeds for clang:

> clang++ -std=c++11 -DUPPER_LIMIT=100 -ftemplate-depth=500 -o test main.cpp
> ./test
0
1
2
100
99
98
-1

Is there something wrong in the code? I wonder that gcc wants to go beyond the UPPER_LIMIT, because there is a terminating specialization for that.

Body:
Wrapper<-1> is instantiated on this line

typename Wrapper<-1>::NextType_t Wrapper<-1>::_nxt;

This causes Wrapper<0> to be instantiated, which causes Wrapper<1> to be instantiated, etc.  At that point in the code, the specialization for Wrapper<UPPER_LIMIT> has not been defined, so this causes an infinite recursion.

Moving the definition of the Wrapper<UPPER_LIMIT> specialization above the Wrapper<-1>::_nxt definition solves the problem.

Apparently Clang defers instantiation, so that this problem doesn't arise.


问:
How to make a site in malayalam language?
I want to create a website. Its contents must be displayed in malayalam language. In admin panel I can edit that malayalam contents of the site also.

How can I do that? Please share your ideas with me. Also help me on this, how to create that kind of a content editor?

答: It is no different from any other kind of website. You just need to make sure that the character encoding being used supports the characters you need. All modern websites should use a Unicode encoding (such as UTF-8) so that should be taken care of already.</p>


问:
VBA transferring data to another workbook

In the attached picture, this is the end goal.

I would like to transfer data from one sheet to another sheet using VBA.
So far, when I click "Submit", the data for Country, Name, Surname will be sent correctly to the sheet named "data". However, I am unsure how to populate the "Race" field in the sheet named "data". I understand that I should be using an if statement, but i'm not sure how to incorporate it into the VBA code.

This is the vba code at the moment.

```<code>Private Sub CommandButton1_Click()

     Dim Country As String, Name As String, Surname As String, Race As String
     Worksheets("form").Select

     Country = Range("B4")
     Name = Range("B6")
     Surname = Range("B7")
     Race = Range("B13")

     Worksheets("data").Select
     Worksheets("data").Range("A1").Select
     If Worksheets("data").Range("A1").Offset(1, 0) <> "" Then
          Worksheets("data").Range("A1").End(xlDown).Select
     End If

     ActiveCell.Offset(1, 0).Select
     ActiveCell.Value = Country
     ActiveCell.Offset(0, 1).Select
     ActiveCell.Value = Name
     ActiveCell.Offset(0, 1).Select
     ActiveCell.Value = Surname
     ActiveCell.Offset(0, 1).Select
     ActiveCell.Value = Race

     Worksheets("form").Select
     Worksheets("form").Range("A4").Select
End Sub
</code>```

I am new to VBA, any assistance with this matter would be greatly appreciated.

答:
Here's something for you, however i have some critique for you

1) Selecting/Activating/Copy/Pasting are all bad habits. You end up writing tons of pointless code to get any use out of it and you slow down the entire prcoess. This matters if there's tons of things youre interacting with.

2). Race on the form tab looks to be a merged cell. my code snippet here is working under the assumption that race is in fact cells b13, c13 and d13. Merged cells are annoying, and might be the under lying cause to your issue. OR i could be totally wrong and you really are super new. Either way youre learning something.

```<code>Private Sub CommandButton1_Click()
     Dim Country As String, Name As String, Surname As String, Race As String
     dim ws as worksheet, wb as workbook, ws1 as worksheet

     set wb = ThisWorkbook
     set ws = wb.Sheets("form")
     set ws1 = wb.Sheets("data")
     Country = ws.Range("B4").value
     Name = ws.Range("B6").value
     Surname = ws.Range("B7").value

     If ws.Range("B13").Value <> "" Then Race = "White"
     If ws.Range("C13").Value <> "" Then Race = "Black"
     If ws.Range("D13").Value <> "" Then Race = "Asian"

     ws1.Cells(ws1.Rows.Count,1).End(xlUp).Offset(1,0).Value = Country
     ws1.Cells(ws1.Rows.Count,1).End(xlUp).Offset(0,1).Value = Name
     ws1.Cells(ws1.Rows.Count,1).End(xlUp).Offset(0,2).Value = Surname
     ws1.Cells(ws1.Rows.Count,1).End(xlUp).Offset(0,3).Value = Race
End Sub
</code>```

I actually kind of like this better, less variables. Instead of using pointless variables to store values you could just store the values in an array and move them all over at once, which i also think saves on over head. Granted I understand I used the same amount fo variables to make sheets/workbooks objects but you could write them out the long way (i actually prefer to do that even though its a blanket of text at that point).

I also included some checks just in case more than one race was chosen, or none at all.

```<code>Private Sub here()

    Dim ws As Worksheet, wb As Workbook, ws1 As Worksheet
    Dim arr(0, 4) As String

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")
    Set ws1 = wb.Sheets("Sheet2")
    arr(0, 0) = ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Value + 1
    arr(0, 1) = ws.Range("B4").Value
    arr(0, 2) = ws.Range("B6").Value
    arr(0, 3) = ws.Range("B7").Value

    If (ws.Range("B13").Value <> "" And ws.Range("C13").Value <> "") _
        Or (ws.Range("B13").Value <> "" And ws.Range("D13").Value <> "") _
            Or (ws.Range("D13").Value <> "" And ws.Range("C13").Value <> "") Then
        arr(0, 4) = "Mixed Race"
    Else
        arr(0, 4) = IIf(ws.Range("B13").Value <> "", "White", _
            IIf(ws.Range("C13").Value <> "", "Black", _
                IIf(ws.Range("D13").Value <> "", "Asian", "Must Be Non-Human")))
    End If

    ws1.Range(ws1.Cells(ws1.UsedRange.Rows.Count + 1, 1), _
        ws1.Cells(ws1.UsedRange.Rows.Count + 1, 5)).Value2 = arr

End Sub
</code>```

Body:
In the attached picture, this is the end goal.

I would like to transfer data from one sheet to another sheet using VBA.
So far, when I click "Submit", the data for Country, Name, Surname will be sent correctly to the sheet named "data". However, I am unsure how to populate the "Race" field in the sheet named "data". I understand that I should be using an if statement, but i'm not sure how to incorporate it into the VBA code.

This is the vba code at the moment.

Private Sub CommandButton1_Click()

     Dim Country As String, Name As String, Surname As String, Race As String
     Worksheets("form").Select

     Country = Range("B4")
     Name = Range("B6")
     Surname = Range("B7")
     Race = Range("B13")

     Worksheets("data").Select
     Worksheets("data").Range("A1").Select
     If Worksheets("data").Range("A1").Offset(1, 0) <> "" Then
          Worksheets("data").Range("A1").End(xlDown).Select
     End If

     ActiveCell.Offset(1, 0).Select
     ActiveCell.Value = Country
     ActiveCell.Offset(0, 1).Select
     ActiveCell.Value = Name
     ActiveCell.Offset(0, 1).Select
     ActiveCell.Value = Surname
     ActiveCell.Offset(0, 1).Select
     ActiveCell.Value = Race

     Worksheets("form").Select
     Worksheets("form").Range("A4").Select
End Sub

I am new to VBA, any assistance with this matter would be greatly appreciated.

Body:
Here's something for you, however i have some critique for you

1) Selecting/Activating/Copy/Pasting are all bad habits. You end up writing tons of pointless code to get any use out of it and you slow down the entire prcoess. This matters if there's tons of things youre interacting with.

2). Race on the form tab looks to be a merged cell. my code snippet here is working under the assumption that race is in fact cells b13, c13 and d13. Merged cells are annoying, and might be the under lying cause to your issue. OR i could be totally wrong and you really are super new. Either way youre learning something.

Private Sub CommandButton1_Click()
     Dim Country As String, Name As String, Surname As String, Race As String
     dim ws as worksheet, wb as workbook, ws1 as worksheet

     set wb = ThisWorkbook
     set ws = wb.Sheets("form")
     set ws1 = wb.Sheets("data")
     Country = ws.Range("B4").value
     Name = ws.Range("B6").value
     Surname = ws.Range("B7").value

     If ws.Range("B13").Value <> "" Then Race = "White"
     If ws.Range("C13").Value <> "" Then Race = "Black"
     If ws.Range("D13").Value <> "" Then Race = "Asian"

     ws1.Cells(ws1.Rows.Count,1).End(xlUp).Offset(1,0).Value = Country
     ws1.Cells(ws1.Rows.Count,1).End(xlUp).Offset(0,1).Value = Name
     ws1.Cells(ws1.Rows.Count,1).End(xlUp).Offset(0,2).Value = Surname
     ws1.Cells(ws1.Rows.Count,1).End(xlUp).Offset(0,3).Value = Race
End Sub

I actually kind of like this better, less variables. Instead of using pointless variables to store values you could just store the values in an array and move them all over at once, which i also think saves on over head. Granted I understand I used the same amount fo variables to make sheets/workbooks objects but you could write them out the long way (i actually prefer to do that even though its a blanket of text at that point).

I also included some checks just in case more than one race was chosen, or none at all.

Private Sub here()

    Dim ws As Worksheet, wb As Workbook, ws1 As Worksheet
    Dim arr(0, 4) As String

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")
    Set ws1 = wb.Sheets("Sheet2")
    arr(0, 0) = ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Value + 1
    arr(0, 1) = ws.Range("B4").Value
    arr(0, 2) = ws.Range("B6").Value
    arr(0, 3) = ws.Range("B7").Value

    If (ws.Range("B13").Value <> "" And ws.Range("C13").Value <> "") _
        Or (ws.Range("B13").Value <> "" And ws.Range("D13").Value <> "") _
            Or (ws.Range("D13").Value <> "" And ws.Range("C13").Value <> "") Then
        arr(0, 4) = "Mixed Race"
    Else
        arr(0, 4) = IIf(ws.Range("B13").Value <> "", "White", _
            IIf(ws.Range("C13").Value <> "", "Black", _
                IIf(ws.Range("D13").Value <> "", "Asian", "Must Be Non-Human")))
    End If

    ws1.Range(ws1.Cells(ws1.UsedRange.Rows.Count + 1, 1), _
        ws1.Cells(ws1.UsedRange.Rows.Count + 1, 5)).Value2 = arr

End Sub


问:
How to make my game adapt to all android devices?
I'm  developing a game and I'm a beginner in Android game development. I'm using Android Studio and libgdx. I need screen to be adaptable on all devices. I am using screen width and height in my code which is changing the position and view of the game screen in different devices. How can I solve this? Can anyone help me getting this done with neat code?

答:
When dealing with different screens it is often necessary to decide
  for a certain strategy how those different screen sizes and aspect
  ratios should be handled. Camera and Stage support different viewport
  strategies.

LibGDX provides a more convenient way of dealing with this problem: Viewport

Gdx.graphics.getWidth() and Gdx.graphics.getHeight() returns the width and height (in pixels) of the window (or on mobile, the screen) that your application is running in.

viewport worldWidth/height is the width and height of the view of the camera, in whatever unit is applicable for you.

The Viewport relates to where and how much of the game world you see, in world units. The Gdx.graphics.getWidth() is the physical pixels of the screen or window.


问:
Is the order of evaluation for initialization lists in constructors fixed?
I was under the impression that the following is prone to leaks

```<code>class Something {
    std::unique_ptr<A> a;
    std::unique_ptr<int> b{new int{3}};
    std::unique_ptr<C> c;
public:
    Something() : a{new A{}}, c{new C{}} {};
};
</code>```

if the order of evaluation was the following

new A{}

new int{3}

new C{}

a{}

b{}

c{}

I was taking a look at the new C++17 feature (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0145r3.pdf) that fixes order of evaluation faults in previous versions of C++, but it only seems to talk about function argument evaluations.

I took a look at the cppreference documentation on order of evaluation (http://en.cppreference.com/w/cpp/language/eval_order) and it does not seem to mention this either.

Does the above have a well defined order of evaluation? (either now in C++17 or in previous versions of C++)

答:
No, that order is not allowed; the language isn't that insane.

These are completely distinct full-expressions, so it's controlled by [intro.execution]/16:

Every value computation and side effect associated with a
  full-expression is sequenced before every value computation and side
  effect associated with the next full-expression to be evaluated.

Body:
I was under the impression that the following is prone to leaks

class Something {
    std::unique_ptr a;
    std::unique_ptr<int> b{new int{3}};
    std::unique_ptr<C> c;
public:
    Something() : a{new A{}}, c{new C{}} {};
};

if the order of evaluation was the following

new A{}

new int{3}

new C{}

a{}

b{}

c{}

I was taking a look at the new C++17 feature (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0145r3.pdf) that fixes order of evaluation faults in previous versions of C++, but it only seems to talk about function argument evaluations.

I took a look at the cppreference documentation on order of evaluation (http://en.cppreference.com/w/cpp/language/eval_order) and it does not seem to mention this either.

Does the above have a well defined order of evaluation? (either now in C++17 or in previous versions of C++)


问:
Why does not the event pass?
Why does not alert ("onEnded") work? All like doing on the manual.

How to launch it in PlayerContainer?

var PLAYER_ID = 'player';
var Player = React.createClass({
    componentDidMount: function() {
        document.getElementById(PLAYER_ID).addEventListener( 'ended', this.onEnded )
    },
    componentWillUnmount: function() {
        document.getElementById(PLAYER_ID).removeEventListener( 'ended', this.onEnded )
    },
    render: function () {
        return (
            <video
                id={PLAYER_ID}
                src={this.props.src}
            </video>
        )
    }
});
var PlayerContainer = React.createClass({
    onEnded: function () {
        alert("onEnded")
    },
    render: function() {
        return <Player
            src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"/>
    }
});
React.render(
    <PlayerContainer />,
    document.body
);```

How to fix it?

Sorry for the stupid question. I study React.js

答:
this in this.onEnded refers to Player instance not PlayerContainer instance, and Player doesn't have onEnded method, Try this:

var PLAYER_ID = 'player';
var Player = React.createClass({
    componentDidMount: function() {
        document.getElementById(PLAYER_ID).addEventListener( 'ended', this.props.onEnded )
    },
    componentWillUnmount: function() {
        document.getElementById(PLAYER_ID).removeEventListener( 'ended', this.props.onEnded )
    },
    render: function () {
        return (
            <video
                id={PLAYER_ID}
                src={this.props.src}
            </video>
        )
    }
});
var PlayerContainer = React.createClass({
    onEnded: function () {
        alert("onEnded")
    },
    render: function() {
        return <Player
            src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
            onEnded={this.onEnded}/>
    }
});
React.render(
    <PlayerContainer />,
    document.body
);```

Title: Why does not the event pass?

Body:
Why does not alert ("onEnded") work? All like doing on the manual.

How to launch it in PlayerContainer?

var PLAYER_ID = 'player';
var Player = React.createClass({
    componentDidMount: function() {
        document.getElementById(PLAYER_ID).addEventListener( 'ended', this.onEnded )
    },
    componentWillUnmount: function() {
        document.getElementById(PLAYER_ID).removeEventListener( 'ended', this.onEnded )
    },
    render: function () {
        return (
            <video
                id={PLAYER_ID}
                src={this.props.src}
            </video>
        )
    }
});
var PlayerContainer = React.createClass({
    onEnded: function () {
        alert("onEnded")
    },
    render: function() {
        return <Player
            src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"/>
    }
});
React.render(
    <PlayerContainer />,
    document.body
);

How to fix it?

Sorry for the stupid question. I study React.js


问:
Error accessing s3 bucket from lambda - InvalidBucketName
Using Java AWS SDK I've created a lambda function to read a csv file from an s3 bucket.  I've made the bucket public and can access it and the file easily from any browser.
To test it, I'm using the test button on the lambda console.  I'm just using the hello world test config input template.

It fails with:

Error Message: The specified bucket is not valid. (Service: Amazon S3; Status Code: 400; Error Code: InvalidBucketName; Request ID: XXXXXXXXXXXXXXX)

Lambda function and s3 bucket are in the same region (us-east-1).

I've added AmazonS3FullAccess to lambda_basic_execution role.

```<code>AmazonS3 s3Client = AmazonS3ClientBuilder.standard().build();
</code>```

also tried

```<code>AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient();
</code>```

then the call

```<code>S3Object s3object = s3Client.getObject(new GetObjectRequest(
                bucketName, keyName));
</code>```

bucketName is:

```<code>https://s3.amazonaws.com/<allAlphaLowerCaseBucketName>
</code>```

keyName is:

```<code><allAlphaLowerCaseKeyName>.csv
</code>```

Any help is appreciated.

答:
The bucket name is not the URL to the bucket, but only the actual name of your bucket.</p>

```<code>S3Object s3object = s3Client.getObject(
                      new GetObjectRequest(
                          <allAlphaLowerCaseBucketName>,
                          <allAlphaLowerCaseKeyName>.csv
                      )
                   );
</code>```

Body:
Using Java AWS SDK I've created a lambda function to read a csv file from an s3 bucket.  I've made the bucket public and can access it and the file easily from any browser.
To test it, I'm using the test button on the lambda console.  I'm just using the hello world test config input template.

It fails with:

Error Message: The specified bucket is not valid. (Service: Amazon S3; Status Code: 400; Error Code: InvalidBucketName; Request ID: XXXXXXXXXXXXXXX)

Lambda function and s3 bucket are in the same region (us-east-1).

I've added AmazonS3FullAccess to lambda_basic_execution role.

AmazonS3 s3Client = AmazonS3ClientBuilder.standard().build();

also tried

AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient();

then the call

S3Object s3object = s3Client.getObject(new GetObjectRequest(
                bucketName, keyName));

bucketName is:

https://s3.amazonaws.com/<allAlphaLowerCaseBucketName>

keyName is:

<allAlphaLowerCaseKeyName>.csv

Any help is appreciated.

Body:
The bucket name is not the URL to the bucket, but only the actual name of your bucket.

S3Object s3object = s3Client.getObject(
                      new GetObjectRequest(
                          <allAlphaLowerCaseBucketName>,
                          <allAlphaLowerCaseKeyName>.csv
                      )
                   );


问:
How can I use a HammerJS pinch gesture on iOS without scrolling a page?
I'm using Ember-Gestures which implements Hammer.js in a Cordova app to implement some simple gesture controls.

I'm running into a major problem whereby any gesture that triggers an animation (transition, transform, SVG animations), if the screen is scrolling any amount, that animation will freeze and be at its end state when scrolling is complete. In particular, I have an element on a vertically scrollable page which should (ideally) be able to be pinched in and out to expand it into multiple elements or back into one.

I'm familiar that as an optimization iOS freezes all animation during scroll. However, since pinch and swipe gestures can both slightly scroll the screen, this is terrible for user experience because elaborate transitions can be completely frozen if the user swipes, for example, slightly up and to the left rather than just directly left.

I've tried a few solutions to enable rendering during scroll like those here, but these don't seem to work on contemporary versions of iOS. I've also tried the hammerJS e.preventDefault() method to freeze scrolling during gestures called through the Ember-gestures extension, so my method looks like:

```<code>swipeLeft(e) {
    e.originalEvent.gesture.srcEvent.preventDefault()
    // Do stuff
},
</code>```

...but this doesn't have any appreciable effect. (Maybe there's something wrong here? gesture had no preventDefault() method itself, and ember-gestures seems to try to abstract some of this away.

Is there any way I can either keep animations rendering during scrolling (this seems unlikely), or alternately STOP a page from scrolling right before performing an animation (and prevent scroll while it's executing)?

Alternately is there any way I can add constraints to what is interpreted as a "pinch" or "swipe" gesture such that those that would also be interpreted as scroll gestures are excluded.

答:
My solution here ended up being to add event handlers such that when the screen is touched with multiple fingers, the body is set to fixed position such that it's unscrollable for the duration of the touch (with the fixed position removed when touch is ended). I added the handlers to the pinchStart and pinchEnd events

I suspect there might be a more elegant solution out there, but for the purpose of disabling accidental scrolling while pinching so that D3.js animations won't freeze midway, this was a quick and effective fix.

Body:
I'm using Ember-Gestures which implements Hammer.js in a Cordova app to implement some simple gesture controls.

I'm running into a major problem whereby any gesture that triggers an animation (transition, transform, SVG animations), if the screen is scrolling any amount, that animation will freeze and be at its end state when scrolling is complete. In particular, I have an element on a vertically scrollable page which should (ideally) be able to be pinched in and out to expand it into multiple elements or back into one.

I'm familiar that as an optimization iOS freezes all animation during scroll. However, since pinch and swipe gestures can both slightly scroll the screen, this is terrible for user experience because elaborate transitions can be completely frozen if the user swipes, for example, slightly up and to the left rather than just directly left.

I've tried a few solutions to enable rendering during scroll like those here, but these don't seem to work on contemporary versions of iOS. I've also tried the hammerJS e.preventDefault() method to freeze scrolling during gestures called through the Ember-gestures extension, so my method looks like:

swipeLeft(e) {
    e.originalEvent.gesture.srcEvent.preventDefault()
    // Do stuff
},

...but this doesn't have any appreciable effect. (Maybe there's something wrong here? gesture had no preventDefault() method itself, and ember-gestures seems to try to abstract some of this away.

Is there any way I can either keep animations rendering during scrolling (this seems unlikely), or alternately STOP a page from scrolling right before performing an animation (and prevent scroll while it's executing)?

Alternately is there any way I can add constraints to what is interpreted as a "pinch" or "swipe" gesture such that those that would also be interpreted as scroll gestures are excluded.


问:
Java - determine disk format (RAW or FS)
Let's say I have a windows host, holding 10 disks:
Half of them are in RAW format and the other half are in some FileSystem format.
I'm looking for a way to determine, from within java code, which drive is in RAW format and which is in FileSystem format.
Till now, I was able to gain information (such as capacity, block size, index and more) about the disks using WMI queries, but I couldn't find a way to determine what is the disk format.</p>

答:
I found a way to determine the disk format via diskpart utility.
I'm running detail disk on all of the disks and then parsing the output to know whether it is RAW/FS (the output is different for RAW/FS disks).

My script basically looks like:

```<code>select disk 1
detail disk
...
select disk n
detail disk
</code>```

Body:
I found a way to determine the disk format via diskpart utility.
I'm running detail disk on all of the disks and then parsing the output to know whether it is RAW/FS (the output is different for RAW/FS disks).

My script basically looks like:

select disk 1
detail disk
...
select disk n
detail disk


答:
When creating react apps you should avoid accessing the DOM yourself. React provides callbacks for events on html elements. You need to pass the callback to your video component via props:

```<code>var Player = React.createClass({
    render: function () {
        return (
            <video
                id={PLAYER_ID}
                src={this.props.src}
                // pass the callback provided in the props to your video element
                onEnded={this.props.onEnded}
            />
        )
    }
});
var PlayerContainer = React.createClass({
    onEnded: function () {
        alert("onEnded")
    },
    render: function() {
        return (
            <Player
                src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
                // pass the callback to your Player component so that it will have it in it's props
                onEnded={this.onEnded}
            />
        );
    }
});
React.render(
    <PlayerContainer />,
    document.body
);
</code>```

Also if you are new to react i recommend you to use it with ES6 syntax and to do the very good tutorial which also uses ES6.

The same components in ES6 syntax:

```<code>import React, {Component} from 'react';

const Player = ({src, onEnded}) => (
    <video src={src} onEnded={onEnded} />
);

class PlayerContainer extends Component {
    onEnded = () => {
        alert("onEnded");
    }

    render() {
        return (
             <Player
                 src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
                 onEnded={this.onEnded}
             />
        );
    }
}

React.render(
    <PlayerContainer />,
    document.body
);
</code>```

Hint: The <video> element has no body.

Title: Why does not the event pass?

Body:
When creating react apps you should avoid accessing the DOM yourself. React provides callbacks for events on html elements. You need to pass the callback to your video component via props:

var Player = React.createClass({
    render: function () {
        return (
            <video
                id={PLAYER_ID}
                src={this.props.src}
                // pass the callback provided in the props to your video element
                onEnded={this.props.onEnded}
            />
        )
    }
});
var PlayerContainer = React.createClass({
    onEnded: function () {
        alert("onEnded")
    },
    render: function() {
        return (
            <Player
                src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
                // pass the callback to your Player component so that it will have it in it's props
                onEnded={this.onEnded}
            />
        );
    }
});
React.render(
    <PlayerContainer />,
    document.body
);

Also if you are new to react i recommend you to use it with ES6 syntax and to do the very good tutorial which also uses ES6.

The same components in ES6 syntax:

import React, {Component} from 'react';

const Player = ({src, onEnded}) => (
    <video src={src} onEnded={onEnded} />
);

class PlayerContainer extends Component {
    onEnded = () => {
        alert("onEnded");
    }

    render() {
        return (
             <Player
                 src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
                 onEnded={this.onEnded}
             />
        );
    }
}

React.render(
    <PlayerContainer />,
    document.body
);

Hint: The <video> element has no body.


答:
You have to pass onEnded as a props from PlayerContainer to Player, so in PlayerContainer you have to call this.props.onEnded instead of this.onEnded

I reproduced this scenario, check this out:

https://codepen.io/henriquebertoldi/pen/awRmzb

Title: Why does not the event pass?


问:
Generate javascript file on the fly in asp.net mvc
Friends,

I am trying to use DyGraph in my application. Please look at the code below -

```<code><head>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
    <title>crosshairs</title>

    <script type="text/javascript" src="dygraph-combined.js"></script>

    <script type="text/javascript" src="data.js"></script>
  </head>
</code>```

The code uses data.js file containing function to get some static data.
I want data.js to be generated using a controller method so that it will generate data using database.

Can anybody help me out to resolve this issue.

Thanks for sharing your valuable time.

答:
Full Disclosure

This answer is copy/pasted from another question:

Dynamically generated Javascript, CSS in ASP.NET MVC

This answer is similar to other answers here.

This answer uses cshtml pages rather than ascx controls.

This answer offers a View-Only solution rather than a Controller-Only solution.

I don't think my answer is 'better' but I think it might be easier for some.

Dynamic CSS in a CSHTML File

I use CSS comments /* */ to comment out a new
```

<p><strong>Dynamic JS in a CSHTML File</strong></p>

<p>I use JavaScript comments <code>//</code> to comment out a new <code>
</code>```

MyDynamicCss.cshtml

```<code>@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");

}

/*
</code>```

MyDynamicJavsScript.cshtml

```<code>@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
fieldArray = string.Join(",", fieldList);

}

//<script type="text/javascript">

$(document).ready(function () {
    var fieldList = "@Html.Raw(fieldArray)";
    var fieldArray = fieldList.split(',');
    var arrayLength = fieldArray.length;
    var selector = '';
    for (var i = 0; i < arrayLength; i++) {
        var field = fieldArray[i];
        selector += (selector == '' ? '' : ',')
                    + 'input[name="' + field + '"]'
                  + ',select[name="' + field + '"]';
    }
    $(selector).attr('disabled', 'disabled');
    $(selector).addClass('disabled');
});
@{return;}</script>
</code>```

No Controller Required (using Views/Shared)

I put both of my dynamic scripts into Views/Shared/ and I can easily embed them into any existing page (or in _Layout.cshtml) using the following code:

```<code>
<script type="text/javascript">@Html.Partial("MyDynamicJavaScript")</script>
</code>```

Using a Controller (optional)

If you prefer you may create a controller e.g.

```<code><link rel="stylesheet" type="text/css" href="@Url.Action("MyDynamicCss", "MyDynamicCode")">
<script type="text/javascript" src="@Url.Action("MyDynamicJavaScript", "MyDynamicCode")"></script>
</code>```

Here's what the controller might look like

MyDynamicCodeController.cs (optional)

```<code>[HttpGet]
public ActionResult MyDynamicCss()
{
    Response.ContentType = "text/css";
    return View();
}

[HttpGet]
public ActionResult MyDynamicJavaScript()
{
    Response.ContentType = "application/javascript";
    return View();
}
</code>```

Notes

The controller version is not tested.  I just typed that off the top of my head.

After re-reading my answer, it occurs to me it might be just as easy to comment out the closing tags rather than use the cshtml @{return;}, but I haven't tried it.  I imagine it's a matter of preference.

Concerning my entire answer, if you find any syntax errors or improvements please let me know.

Body:
Friends,

I am trying to use DyGraph in my application. Please look at the code below -

    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
    <title>crosshairs</title>

The code uses data.js file containing function to get some static data.
I want data.js to be generated using a controller method so that it will generate data using database.

Can anybody help me out to resolve this issue.

Thanks for sharing your valuable time.

Body:
Full Disclosure

This answer is copy/pasted from another question:

Dynamically generated Javascript, CSS in ASP.NET MVC

This answer is similar to other answers here.

This answer uses cshtml pages rather than ascx controls.

This answer offers a View-Only solution rather than a Controller-Only solution.

I don't think my answer is 'better' but I think it might be easier for some.

Dynamic CSS in a CSHTML File

I use CSS comments /* */ to comment out a new <style> tag and then I return; before the closing style tag:

/*<style type="text/css">/* */

    CSS GOES HERE

@{return;}</style>

Dynamic JS in a CSHTML File

I use JavaScript comments // to comment out a new <script> tag and then I return; before the closing script tag:

//<script type="text/javascript">

    JAVASCRIPT GOES HERE

@{return;}</script>

MyDynamicCss.cshtml

@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");

}

/*<style type="text/css">/* */

@foreach (var field in fieldList) {<text>

input[name="@field"]
, select[name="@field"]
{
    background-color: #bbb;
    color: #6f6f6f;
}

</text>}

@{return;}</style>

MyDynamicJavsScript.cshtml

@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
fieldArray = string.Join(",", fieldList);

}

//<script type="text/javascript">

$(document).ready(function () {
    var fieldList = "@Html.Raw(fieldArray)";
    var fieldArray = fieldList.split(',');
    var arrayLength = fieldArray.length;
    var selector = '';
    for (var i = 0; i < arrayLength; i++) {
        var field = fieldArray[i];
        selector += (selector == '' ? '' : ',')
                    + 'input[name="' + field + '"]'
                  + ',select[name="' + field + '"]';
    }
    $(selector).attr('disabled', 'disabled');
    $(selector).addClass('disabled');
});
@{return;}</script>

No Controller Required (using Views/Shared)

I put both of my dynamic scripts into Views/Shared/ and I can easily embed them into any existing page (or in _Layout.cshtml) using the following code:

<style type="text/css">@Html.Partial("MyDynamicCss")</style>
<script type="text/javascript">@Html.Partial("MyDynamicJavaScript")</script>

Using a Controller (optional)

If you prefer you may create a controller e.g.

<link rel="stylesheet" type="text/css" href="@Url.Action("MyDynamicCss", "MyDynamicCode")">
<script type="text/javascript" src="@Url.Action("MyDynamicJavaScript", "MyDynamicCode")"></script>

Here's what the controller might look like

MyDynamicCodeController.cs (optional)

[HttpGet]
public ActionResult MyDynamicCss()
{
    Response.ContentType = "text/css";
    return View();
}

[HttpGet]
public ActionResult MyDynamicJavaScript()
{
    Response.ContentType = "application/javascript";
    return View();
}

Notes

The controller version is not tested.  I just typed that off the top of my head.

After re-reading my answer, it occurs to me it might be just as easy to comment out the closing tags rather than use the cshtml @{return;}, but I haven't tried it.  I imagine it's a matter of preference.

Concerning my entire answer, if you find any syntax errors or improvements please let me know.


答:
Each member initialisation is treated as a separate statement, and the order between these statements is strictly defined.

So in your example, the order is going to be defined as:

new A{}

a{}

new int{3}

b{}

new C{}

c{}

Title: Is the order of evaluation for initialization lists in constructors fixed?


问:
Javascript text file encoding with Arabic and English for macro file
I am trying to export a text file using JavaScript to be used as macro for Microsoft Dynamics GP.

The problem is Arabic letters don't render correctly when I try to use the macro in GP.

For example "النسر" would render as "ط§ظ„ظ†ط³ط±"

My JavaScript code uses FileSaver.js

```<code>var file = new Blob([text], {type:"text/plain;charset=utf-8;"});
saveAs(file, filename);
</code>```

One solution I found was that after downloading the file I save it with ANSI encoding. But if I changed my charset in the JavaScript Blob object to "ansi" or "Windows-1252" or "cp-1252" it doesn't work.

Note: I am using Chrome on Windows 7

答:
From my experience I have found that Dynamics GP macros uses ANSI.

You will first need to encode your text to ANSI that includes arabic (windows-1256/CP1256).

I used this js library to encode the text:
https://github.com/mathiasbynens/windows-1256

```<code>var text= windows1256.encode(text);
</code>```

Then you will need to convert it to 8 bit unsigned integers and export it using a Blob.

```<code>var uint8 = new Uint8Array(text.length);
for (var i = 0; i < uint8.length; i++)
{
  uint8[i] = text.charCodeAt(i);
}
var file = new Blob([uint8], {type: 'text/plain;charset=windows-1256'});
</code>```

I know this answer is too late but I hope it helps.

Body:
I am trying to export a text file using JavaScript to be used as macro for Microsoft Dynamics GP.

The problem is Arabic letters don't render correctly when I try to use the macro in GP.

For example "النسر" would render as "ط§ظ„ظ†ط³ط±"

My JavaScript code uses FileSaver.js

var file = new Blob([text], {type:"text/plain;charset=utf-8;"});
saveAs(file, filename);

One solution I found was that after downloading the file I save it with ANSI encoding. But if I changed my charset in the JavaScript Blob object to "ansi" or "Windows-1252" or "cp-1252" it doesn't work.

Note: I am using Chrome on Windows 7

Body:
From my experience I have found that Dynamics GP macros uses ANSI.

You will first need to encode your text to ANSI that includes arabic (windows-1256/CP1256).

I used this js library to encode the text:
https://github.com/mathiasbynens/windows-1256

var text= windows1256.encode(text);

Then you will need to convert it to 8 bit unsigned integers and export it using a Blob.

var uint8 = new Uint8Array(text.length);
for (var i = 0; i < uint8.length; i++)
{
  uint8[i] = text.charCodeAt(i);
}
var file = new Blob([uint8], {type: 'text/plain;charset=windows-1256'});

I know this answer is too late but I hope it helps.


问:
Cobol technical demonstration
I'm working as a COBOL programmer - have a 6 months work experience - for a consulting firm . Today, with the rest the COBOL "department", I had a meeting with the new director of my company.

After an initial analysis made by the new team in charge, they noticed that, comparing to the other services/technologies our company has to offer - Java, C++, Objective-C, etc - COBOL was lacking "advertisement". He stated that whenever members of other teams are in-between projects they implement small demos which then can be shown to our clients whenever there is a presentation of our company. He gave examples of widgets for mobile devices in Objective-C, cool web-pages with HTML5, etc.
And noticed that there is nothing in COBOL like that. So he wants us to develop some kind of tool/app to show what our competences.

We already told him that COBOL is used under the hood, and doesn't have bells and whistles to show. Also that when hiring a COBOL programmer/analyst the most important for the client is that he shows he has "business logic" knowledge.

I know that the coding part is very important but after a two weeks introduction to the mainframe environment and to COBOL I was capable of doing my programming tasks easily. But with a 6 months experience working in a bank I find myself having to, nearly everyday, ask questions regarding "business logic" to the "gurus" just so that I don't end up changing the logic of the process when performing some maintenance task.

Can we really make something (tool/app) that shows or future clients that we have something different to offer than all the other company's which provide the same services? Or if not, is there anything that we can say to our manager so that he understands that COBOL is different from the other languages and it's purpose is not to display pretty graphics on the screen.

Thank you!

答:
As you are working in a mainframe environment (I presume it's IBM) I suggest you check out the following link http://www-01.ibm.com/software/awdtools/cobol/ to IBM'S COBOL compiler section. There's information there about linking COBOL with web services and Java, in a mainframe environment.

As a previous answer mentioned, you could also look at Visual COBOL from Micro Focus. It's not a mainframe product but is a COBOL complier within Visual Studio and deploying in .NET

http://www.microfocus.com/products/micro-focus-developer/micro-focus-cobol/windows-and-net/micro-focus-visual-cobol.aspx

Title: Cobol technical demonstration