问:
cpp how to make main thread wait until other threads are finished in cycle
I'm trying to run a cpp code in a cycle in different threads, and want my main thread to wait until all other threads are done. I'm doing like this:

```<code>MyClass {
    function(Obj1& res, Obj2& input);
}

AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];

        doSmth1(resvec, inputvec);

        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
        }
        for(int i = 0; i < size; ++i) {
            thpool[i].join();
        }

        doSmth2(resvec);

    }
}
</code>```

But the code returns the wrong answer, however, if I do like this

```<code>MyClass {
    function(Obj1& res, Obj2& input);
}

AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];

        doSmth1(resvec, inputvec);

        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
            thpool[i].join();
        }

        doSmth2(resvec);

    }
}
</code>```

the code returns right answer but does not give an advantage in speed. It seems that I do something wrong in the code, can someone help me? Thanks!
problem occurs when I call scheme.multModSwitchAndEqualVec

method implemented in Scheme

答: simply increase the sleep time of the main thread by using sleep() function.</p>

Body:
I'm trying to run a cpp code in a cycle in different threads, and want my main thread to wait until all other threads are done. I'm doing like this:

MyClass {
    function(Obj1& res, Obj2& input);
}

AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];

        doSmth1(resvec, inputvec);

        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
        }
        for(int i = 0; i < size; ++i) {
            thpool[i].join();
        }

        doSmth2(resvec);

    }
}

But the code returns the wrong answer, however, if I do like this

MyClass {
    function(Obj1& res, Obj2& input);
}

AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];

        doSmth1(resvec, inputvec);

        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
            thpool[i].join();
        }

        doSmth2(resvec);

    }
}

the code returns right answer but does not give an advantage in speed. It seems that I do something wrong in the code, can someone help me? Thanks!
problem occurs when I call scheme.multModSwitchAndEqualVec

method implemented in Scheme


来源: stackexchange

问:
Unable to loop through string array and append to FormData
I am developing a file upload module in AngularJS. I will be having multiple file controls and each control can upload one file at a time (not multiple). Finally on click of submit I am saving all the files. I am dynamically generating file controls using ng-repeat as below.

{{fileInput}}

                    <input type="file" file-data="{{fileInput}}" file-model="{{fileInput}}" />

```

<p>JS code to assign values to file controls     </p>

```$scope.fileInputs = ["Passport","Visa"];
```

<p>Below is my code to upload files.</p>

```myapp.factory('fileUpload', ['$http', function ($http) {
    var fileuploadurl = "http://localhost:19144/" + 'api/Customer/UploadLeaseFiles/' + 2;
    var service = {
        uploadUrl: fileuploadurl,
        pendingFiles: [],
        doUpload: doUpload
    };
    return service;
    function doUpload() {
        debugger;
        var files = new FormData();
        angular.forEach(this.pendingFiles, function (value, index) {
            files.append('file', value);
            files.append('IndexValue', index);

        });
        return $http.post(this.uploadUrl, files, {
            transformRequest: angular.identity,
            headers: {
                'Content-Type': undefined
            }
        })
    }
}]);
```

<p>This is my directive code.</p>

```myapp.directive('fileModel', ['fileUpload', function (fileUpload) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind("change", function (evt) {
                fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
            });
        }
    };
}]);
```

<p>Above code will work only if I assign integers to fileInputs as:</p>

```$scope.fileInputs = [1,2,3];
```

I am struggling to understand why it is working if I assign integer to fileinputs. How can I assign strings and make the above code work?

答:
You are pushing files in an array. Basically you are doing something like:

```<code>pendingFiles[1] = file
</code>```

and again

```<code>pendingFiles["passport"] = file
</code>```

The first case works fine with array, but the second won't.

So the solution is change pending files to an object like:

```<code>var service = {
        uploadUrl: fileuploadurl,
        pendingFiles: {},
        doUpload: doUpload
    };
</code>```

With object you can make properties on it like:

```<code>{
passport : file,
Visa : file2
}
</code>```

and then use this object while you upload.

Update

for sending extra data use data property of formData obj. Like:

```<code> var files = new FormData();
        angular.forEach(this.pendingFiles, function (value, index) {
            files.append('file', value);
            files.append('IndexValue', index);
            files.append ('data', angular.toJson(anyJSObject));

        });
</code>```

Hope it works.

ContentLicense: CC BY-SA 3.0

Body:
I am developing a file upload module in AngularJS. I will be having multiple file controls and each control can upload one file at a time (not multiple). Finally on click of submit I am saving all the files. I am dynamically generating file controls using ng-repeat as below.

{{fileInput}}

                    <input type="file" file-data="{{fileInput}}" file-model="{{fileInput}}" />

JS code to assign values to file controls

$scope.fileInputs = ["Passport","Visa"];

Below is my code to upload files.

myapp.factory('fileUpload', ['$http', function ($http) {
    var fileuploadurl = "http://localhost:19144/" + 'api/Customer/UploadLeaseFiles/' + 2;
    var service = {
        uploadUrl: fileuploadurl,
        pendingFiles: [],
        doUpload: doUpload
    };
    return service;
    function doUpload() {
        debugger;
        var files = new FormData();
        angular.forEach(this.pendingFiles, function (value, index) {
            files.append('file', value);
            files.append('IndexValue', index);

        });
        return $http.post(this.uploadUrl, files, {
            transformRequest: angular.identity,
            headers: {
                'Content-Type': undefined
            }
        })
    }
}]);

This is my directive code.

myapp.directive('fileModel', ['fileUpload', function (fileUpload) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind("change", function (evt) {
                fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
            });
        }
    };
}]);

Above code will work only if I assign integers to fileInputs as:

$scope.fileInputs = [1,2,3];

I am struggling to understand why it is working if I assign integer to fileinputs. How can I assign strings and make the above code work?

Body:
You are pushing files in an array. Basically you are doing something like:

pendingFiles[1] = file

and again

pendingFiles["passport"] = file

The first case works fine with array, but the second won't.

So the solution is change pending files to an object like:

var service = {
        uploadUrl: fileuploadurl,
        pendingFiles: {},
        doUpload: doUpload
    };

With object you can make properties on it like:

{
passport : file,
Visa : file2
}

and then use this object while you upload.

Update

for sending extra data use data property of formData obj. Like:

 var files = new FormData();
        angular.forEach(this.pendingFiles, function (value, index) {
            files.append('file', value);
            files.append('IndexValue', index);
            files.append ('data', angular.toJson(anyJSObject));

        });

Hope it works.


问:
Script php stop without error messages
I want to input in a database some values from a txt files.
I have a loop who extract the data that i want, check if it don't already exist and else insert it.

```<code>$res = mysqli_query($conn, "SELECT COUNT(*) AS nb FROM SITE WHERE domain_site = '".$domain."'");
$res = mysqli_fetch_assoc($res);
if ($res["nb"] == 0) {
    $conn->query("INSERT INTO SITE (domain_site) VALUES ('".$domain."')");
}
</code>```

I have see that in my DB, their is not all the values, so I add this line :

```<code>echo $domain."</br>";
</code>```

and the output stop before the end of my file without reasons and error messages

PS : I have set these parameters in the top of my php

```<code>ini_set('max_execution_time', 1000);
ini_set('memory_limit', '100M');
set_time_limit(0);
ini_set('display_errors',1);
error_reporting(E_ALL);
</code>```

Someone have an idea why my script stop or how to solve it ? Thank you.

答:
Try adding:

printf("Errormessage: %s\n", mysqli_error($conn));

This will print the error(if any from DataBase).

Title: Script php stop without error messages

Body:
I want to input in a database some values from a txt files.
I have a loop who extract the data that i want, check if it don't already exist and else insert it.

$res = mysqli_query($conn, "SELECT COUNT(*) AS nb FROM SITE WHERE domain_site = '".$domain."'");
$res = mysqli_fetch_assoc($res);
if ($res["nb"] == 0) {
    $conn->query("INSERT INTO SITE (domain_site) VALUES ('".$domain."')");
}

I have see that in my DB, their is not all the values, so I add this line :

echo $domain."
";

and the output stop before the end of my file without reasons and error messages

PS : I have set these parameters in the top of my php

ini_set('max_execution_time', 1000);
ini_set('memory_limit', '100M');
set_time_limit(0);
ini_set('display_errors',1);
error_reporting(E_ALL);

Someone have an idea why my script stop or how to solve it ? Thank you.


问:
CSS: Varying Rotation on Wordpress site?
I did try a all sort of codes but i can't seem to get it right.
What i like to see is that the different posts with thumbnail have different degrees for rotation.

Here is the css code that i tryed:

```<code>.hentry .post-thumb li:nth-child(2n){
    -moz-transform: rotate(3deg);
    -webkit-transform: rotate(3deg);
    -o-transform: rotate(3deg);
    transform: rotate(3deg);
}

.hentry .post-thumb li:nth-child(3n){
    -moz-transform: rotate(-3deg);
    -webkit-transform: rotate(-3deg);
    -o-transform: rotate(-3deg);
    transform: rotate(-3deg);
}
</code>```

You can see the site here.

Thanks

答:
The CSS you provide in your question doesn't match the HTML on the site you're linking to. There's no li descendent of a .post-thumb element.

I think you misunderstand how the nth-child() pseudo-class works, though. You should be doing something like this:

```<code>.hentry:nth-child(2n) .post-thumb img { transform: rotate(3deg); /* etc. */ }
.hentry:nth-child(3n) .post-thumb img { transform: rotate(-3deg); /* etc. */ }
</code>```

This will rotate the thumbnails of every second post 3 degrees to the right (i.e. the 2nd, 4th, 6th etc. child of the .posts div), and all thumbnails of every third post 3 degrees to the left (i.e. the 3rd, 6th, 9th etc. child of the .posts div).

I'm not sure if 2n and 3n are quite the expression you intend either, though. Perhaps Sitepoint's "Understanding :nth-child Pseudo-class Expressions" will help.

ContentLicense: CC BY-SA 2.5

Body:
I did try a all sort of codes but i can't seem to get it right.
What i like to see is that the different posts with thumbnail have different degrees for rotation.

Here is the css code that i tryed:

.hentry .post-thumb li:nth-child(2n){
    -moz-transform: rotate(3deg);
    -webkit-transform: rotate(3deg);
    -o-transform: rotate(3deg);
    transform: rotate(3deg);
}

.hentry .post-thumb li:nth-child(3n){
    -moz-transform: rotate(-3deg);
    -webkit-transform: rotate(-3deg);
    -o-transform: rotate(-3deg);
    transform: rotate(-3deg);
}

You can see the site here.

Thanks

Body:
The CSS you provide in your question doesn't match the HTML on the site you're linking to. There's no li descendent of a .post-thumb element.

I think you misunderstand how the nth-child() pseudo-class works, though. You should be doing something like this:

.hentry:nth-child(2n) .post-thumb img { transform: rotate(3deg); /* etc. */ }
.hentry:nth-child(3n) .post-thumb img { transform: rotate(-3deg); /* etc. */ }

This will rotate the thumbnails of every second post 3 degrees to the right (i.e. the 2nd, 4th, 6th etc. child of the .posts div), and all thumbnails of every third post 3 degrees to the left (i.e. the 3rd, 6th, 9th etc. child of the .posts div).

I'm not sure if 2n and 3n are quite the expression you intend either, though. Perhaps Sitepoint's "Understanding :nth-child Pseudo-class Expressions" will help.


问:
How to get all closest matched strings from an array?
I am trying to find closest match from an array.  For this I use levenshtein(), but levenshtein() returns only first matched string or first closest match.

Here is my scenario:

```<code>$words = array('Break Noise','Engine Noise','Vehicle is jerking');
</code>```

If my input is Noise, I want to get both Break Noise and Engine Noise.

Is it possible to do?

levenshtein() returns me only Break Noise which is the first element.

答:
After getting two upvotes, I'm sucked into leaving this answer on the screen.

```<code>$input="Noise";
$words = array('Break Noise','Engine Noise','Noises','Vehicle is jerking','Nose','noise');
$filtered=array_filter($words,function($v)use($input){return stripos($v,$input)!==false;});

usort($filtered,function($a,$b)use($input) {
    return levenshtein($input,$a)>levenshtein($input,$b)?1:-1;
});

var_export($filtered);
</code>```

Output:

```<code>array (
  0 => 'Noises',
  1 => 'noise',
  2 => 'Break Noise',
  3 => 'Engine Noise',
)
</code>```

This will first filter out "Noise-less" elements, then sort your array using levenshtein().

Body:
I am trying to find closest match from an array.  For this I use levenshtein(), but levenshtein() returns only first matched string or first closest match.

Here is my scenario:

$words = array('Break Noise','Engine Noise','Vehicle is jerking');

If my input is Noise, I want to get both Break Noise and Engine Noise.

Is it possible to do?

levenshtein() returns me only Break Noise which is the first element.

Body:
After getting two upvotes, I'm sucked into leaving this answer on the screen.

$input="Noise";
$words = array('Break Noise','Engine Noise','Noises','Vehicle is jerking','Nose','noise');
$filtered=array_filter($words,function($v)use($input){return stripos($v,$input)!==false;});

usort($filtered,function($a,$b)use($input) {
    return levenshtein($input,$a)>levenshtein($input,$b)?1:-1;
});

var_export($filtered);

Output:

array (
  0 => 'Noises',
  1 => 'noise',
  2 => 'Break Noise',
  3 => 'Engine Noise',
)

This will first filter out "Noise-less" elements, then sort your array using levenshtein().


问:
Show only text in Notification without any icon
I want to show a notification that only shows a text instead of an icon!

I just try it as:

```<code>private void showNotification(String msg) {
    try {
        Intent intent = new Intent(this, Act.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        //set the notification
        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setContentText(msg)
            .setAutoCancel(true)
            .setSound(notificationSound)
            .setContentIntent(pendingIntent);

       NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       notificationManager.notify(0, builder.build());

    } catch (Exception exp) {
        Log.e("xmn", exp.toString());
}
}
</code>```

The problem is that the notification never occurs.

答:
You can use RemoteViews to set your custom layout/just a textview or anything.
custom notification </p>

Body:
I want to show a notification that only shows a text instead of an icon!

I just try it as:

private void showNotification(String msg) {
    try {
        Intent intent = new Intent(this, Act.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        //set the notification
        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setContentText(msg)
            .setAutoCancel(true)
            .setSound(notificationSound)
            .setContentIntent(pendingIntent);

       NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       notificationManager.notify(0, builder.build());

    } catch (Exception exp) {
        Log.e("xmn", exp.toString());
}
}

The problem is that the notification never occurs.


问:
Day difference coming wrong
We have to do some security check for which we are getting some date from some part of our code and then we are calculating the difference in days

```<code>String userDate = EncryptUtil.getInstance().decrypt(Constants.USER_DATE);
String currentDate = new SimpleDateFormat("dd/MM/yyyy").format(calendar.getTime());

long startTime = new Date(userDate).getTime();
long presentTime = new Date(currentDate).getTime();
long diffTime = presentTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
</code>```

The userDate value is coming 03/06/2017 and currentDate is 07/06/2017, both are correct, but when I'm calculating day difference (diffDays) it is giving a difference of 122, where it should be actually 4. I don't understand why? Can anybody help.

答:
It seems that your date is parsed not as ddMMyyyy, but as MMddyyyy format. That's why difference in days give you ~4 months, instead of 4 days.

You can stop using Deprecated API (new Date(String) is deprecated since Java 1.1) and start using fresh java time classes https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

Title: Day difference coming wrong

Body:
We have to do some security check for which we are getting some date from some part of our code and then we are calculating the difference in days

String userDate = EncryptUtil.getInstance().decrypt(Constants.USER_DATE);
String currentDate = new SimpleDateFormat("dd/MM/yyyy").format(calendar.getTime());

long startTime = new Date(userDate).getTime();
long presentTime = new Date(currentDate).getTime();
long diffTime = presentTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);

The userDate value is coming 03/06/2017 and currentDate is 07/06/2017, both are correct, but when I'm calculating day difference (diffDays) it is giving a difference of 122, where it should be actually 4. I don't understand why? Can anybody help.


问:
D3 V4 - Trying to Chart a Simple line Graph
I'm struggling to plot a simple line chart in D3 (V4)...

My Data looks as follows and I believe its fine as I can use d3.timeParse() to parse the dates and they console.log fine:

```<code>var parseDate = d3.timeParse("%Y-%m-%d %H:%M:%S");
</code>```

Data Format

```<code>            $myObj = (object)[];
            $myObj->name = $row['CH_FREQ'];
            $myObj->value = $row['RX_POWER'];
            $myObj->date = $row['CREATED_AT'];
            $chartData_RX_Down[] = $myObj;
</code>```

eg: date, name, value - which could be: 2017-03-22 12:20:02, name, -0.2

Most of the Dates are negatives.

Chart Code:

```<code>    // SA MAC Plot Chart - API Doco: http://devdocs.io/d3~4/
    function plotChart(data) {
        $('#chartContainer').empty();

        // Color Scale
        var magma = d3.scaleSequential(d3.interpolateMagma).domain([0,7]);

        // Set the Dimensions and Margins of the Graph
        var margin = {top: 20, right: 20, bottom: 40, left: 60},
            width = 580,
            height = 230;

        // x-Scale with Time Width
        var parseDate = d3.timeParse("%Y-%m-%d %H:%M:%S");      // D3 Expected Date Format
        var x = d3.scaleTime()
            .domain(d3.extent(data, function(d) { return parseDate(d.date); }))
            .range([0, width]);

        // y-Scale
        var y = d3.scaleLinear()
            .domain([0, d3.max(data, function(d) { return d.value; })])
            .range([height, 0]);

        // append the svg object to the body of the page
        // append a 'group' element to 'svg'
        // moves the 'group' element to the top left margin
        var svg = d3.select("#chartContainer").append("svg")
            .attr("width", "100%")
            .attr("height", "300px")
            .append("g")
            .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

       // append the rectangles for the bar chart
        svg.selectAll("path")
            .data(data)
            .enter().append("path")
            .attr("x", function(d) { return d.date; })
            .attr("y", function(d) { return d.value; });

        // X-Axis
        svg.append("g")
            .attr("class", "axis_x")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x).tickPadding(5).tickSize(10));

        // Y-Axis
        svg.append("g")
            .attr("class", "axis_y")
            .call(d3.axisLeft(y).ticks(5).tickPadding(5).tickSize(10));

        // X-Axis Text
        svg.append("text")
            .attr("class", "d3_X_Axis_Text")
            .attr("x", 0)
            .attr("y", 0)
            .attr("fill", "white")
            .attr("transform", "translate(" + (width/2) + " ," + (height + margin.top + 20) + ")")
            .style("text-anchor", "middle")
            .text("Date Time");

        // Y-Axis Text
        svg.append("text")
            .attr("class", "d3_Y_Axis_Text")
            .attr("x", -130)
            .attr("y", -42.5)
            .attr("fill", "white")
            .attr("transform", "rotate(-90)")
            .style("text-anchor", "middle")
            .text("CM DownStream Bytes Received");
    }
</code>```

I get a chart on the screen with dates X-Axis and numbers 0 to -6 Y-Axis so D3 is working and trying to display a chart - I just don't see any data/lines.

Note: I'm looking for a line chart.

I think the issue is related to the following code:

```<code>       // append the rectangles for the bar chart
        svg.selectAll("path")
            .data(data)
            .enter().append("path")
            .attr("x", function(d) { return d.date; })
            .attr("y", function(d) { return d.value; });
</code>```

I tried the following as well:

```<code>        // append the rectangles for the bar chart
        svg.selectAll("path")
            .data(data)
            .enter().append("path")
            .attr("x", function(d) { return d.date; })
            .attr("y", function(d) { return d.value; });
</code>```

Any assistance would be greatly appreciated!!

Cheers
Adam

答:
SVG path element does not have x and y attributes. You should configure its d attribute(path description).
Refer here - developer.mozilla.org/en-US/docs/Web/SVG/Element/path

Code:

```<code>var valueline = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.value); });

 svg.selectAll("path")
      .data(data)
      .enter().append("path")
      .attr("class", "line")
      .attr("d", valueline);
</code>```

Body:
I'm struggling to plot a simple line chart in D3 (V4)...

My Data looks as follows and I believe its fine as I can use d3.timeParse() to parse the dates and they console.log fine:

var parseDate = d3.timeParse("%Y-%m-%d %H:%M:%S");

Data Format

            $myObj = (object)[];
            $myObj->name = $row['CH_FREQ'];
            $myObj->value = $row['RX_POWER'];
            $myObj->date = $row['CREATED_AT'];
            $chartData_RX_Down[] = $myObj;

eg: date, name, value - which could be: 2017-03-22 12:20:02, name, -0.2

Most of the Dates are negatives.

Chart Code:

    // SA MAC Plot Chart - API Doco: http://devdocs.io/d3~4/
    function plotChart(data) {
        $('#chartContainer').empty();

        // Color Scale
        var magma = d3.scaleSequential(d3.interpolateMagma).domain([0,7]);

        // Set the Dimensions and Margins of the Graph
        var margin = {top: 20, right: 20, bottom: 40, left: 60},
            width = 580,
            height = 230;

        // x-Scale with Time Width
        var parseDate = d3.timeParse("%Y-%m-%d %H:%M:%S");      // D3 Expected Date Format
        var x = d3.scaleTime()
            .domain(d3.extent(data, function(d) { return parseDate(d.date); }))
            .range([0, width]);

        // y-Scale
        var y = d3.scaleLinear()
            .domain([0, d3.max(data, function(d) { return d.value; })])
            .range([height, 0]);

        // append the svg object to the body of the page
        // append a 'group' element to 'svg'
        // moves the 'group' element to the top left margin
        var svg = d3.select("#chartContainer").append("svg")
            .attr("width", "100%")
            .attr("height", "300px")
            .append("g")
            .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

       // append the rectangles for the bar chart
        svg.selectAll("path")
            .data(data)
            .enter().append("path")
            .attr("x", function(d) { return d.date; })
            .attr("y", function(d) { return d.value; });

        // X-Axis
        svg.append("g")
            .attr("class", "axis_x")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x).tickPadding(5).tickSize(10));

        // Y-Axis
        svg.append("g")
            .attr("class", "axis_y")
            .call(d3.axisLeft(y).ticks(5).tickPadding(5).tickSize(10));

        // X-Axis Text
        svg.append("text")
            .attr("class", "d3_X_Axis_Text")
            .attr("x", 0)
            .attr("y", 0)
            .attr("fill", "white")
            .attr("transform", "translate(" + (width/2) + " ," + (height + margin.top + 20) + ")")
            .style("text-anchor", "middle")
            .text("Date Time");

        // Y-Axis Text
        svg.append("text")
            .attr("class", "d3_Y_Axis_Text")
            .attr("x", -130)
            .attr("y", -42.5)
            .attr("fill", "white")
            .attr("transform", "rotate(-90)")
            .style("text-anchor", "middle")
            .text("CM DownStream Bytes Received");
    }

I get a chart on the screen with dates X-Axis and numbers 0 to -6 Y-Axis so D3 is working and trying to display a chart - I just don't see any data/lines.

Note: I'm looking for a line chart.

I think the issue is related to the following code:

       // append the rectangles for the bar chart
        svg.selectAll("path")
            .data(data)
            .enter().append("path")
            .attr("x", function(d) { return d.date; })
            .attr("y", function(d) { return d.value; });

I tried the following as well:

        // append the rectangles for the bar chart
        svg.selectAll("path")
            .data(data)
            .enter().append("path")
            .attr("x", function(d) { return d.date; })
            .attr("y", function(d) { return d.value; });

Any assistance would be greatly appreciated!!

Cheers
Adam

Body:
SVG path element does not have x and y attributes. You should configure its d attribute(path description).
Refer here - developer.mozilla.org/en-US/docs/Web/SVG/Element/path

Code:

var valueline = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.value); });

 svg.selectAll("path")
      .data(data)
      .enter().append("path")
      .attr("class", "line")
      .attr("d", valueline);


问:
Are references orthogonal to pointers?
The question is meant as language orthogonal(as is in lack of redundency) features. References (never null[1]) in C++ can be implemented with pointers while compilers check for the semantic differences. There are languages like Java or C# that only have references (maybe null) but no pointers and C has it the other way round. So one is sufficent for a complete language. Is the behaviour in C++ different enough to be orthogonal?

[1] You can de-reference a nullptr but that is undefined.

答:
References are nothing more then stricter pointers in C++,  since you can "convert" a reference to a pointer by taking its address.
That's far from saying they are redundant, but they are the opposite of orthogonal. They essentially do the same thing.</p>

Title: Are references orthogonal to pointers?


问:
Typescript type assertions in parameters
I'm liking typescript so far, but find that i need to do type assertion a lot. For example casting an EventTarget to an HTMLAnchorElement is a common use case for me. However to get that, i need to use something like the following:

```<code>getTabID(eventTarget: EventTarget) : string {
    // without the following variable, the compiler tells me that .hash
    // is not a property of EventTarget, which according to the interface, it isn't.
    // So thats fine, i'll cast it to an Element
    let mEventTarget: HTMLAnchorElement = <HTMLAnchorElement>eventTarget
    let mTabID: string
    if(mEventTarget.hash){
        mTabID = mEventTarget.hash.split('#')[1]
    }
    return mTabID
}
</code>```

However this means that if I don't want the compiler to throw errors I need to create variables in my functions JUST to do type assertions. I don't mind the extra typing, but these end up in the JS as well and ends up wasting bytes in my js files.

I would like to be able to the following:

```<code>getTabID(eventTarget: EventTarget) : string {
    let mTabID: string
    // Do the type assertion in the parameter
    if(<HTMLAnchorElement> eventTarget.hash){
        mTabID = mEventTarget.hash.split('#')[1]
    } else {
        mTabID = mEventTarget.dataset.tabId
    }
    return mTabID
}
</code>```

I've had a good look in the docs and SO and can't seem to find any way to do this. Anyone have any ideas?

答:
You can perform inline type assertions, by surrounding the assertion with parantheses:

```<code>if((<HTMLAnchorElement>eventTarget).hash) {
</code>```

You might also see what you can do to prevent the need for a type assertion, for example:

```<code>getTabID(eventTarget: HTMLAnchorElement) : string {
    let mTabID: string;

    if(eventTarget.hash){
        mTabID = eventTarget.hash.split('#')[1]
    }

    return mTabID
}
</code>```

And lastly, watch out for the casing as you mixed EventTarget and eventTarget in one of your examples.

Body:
I'm liking typescript so far, but find that i need to do type assertion a lot. For example casting an EventTarget to an HTMLAnchorElement is a common use case for me. However to get that, i need to use something like the following:

getTabID(eventTarget: EventTarget) : string {
    // without the following variable, the compiler tells me that .hash
    // is not a property of EventTarget, which according to the interface, it isn't.
    // So thats fine, i'll cast it to an Element
    let mEventTarget: HTMLAnchorElement = <HTMLAnchorElement>eventTarget
    let mTabID: string
    if(mEventTarget.hash){
        mTabID = mEventTarget.hash.split('#')[1]
    }
    return mTabID
}

However this means that if I don't want the compiler to throw errors I need to create variables in my functions JUST to do type assertions. I don't mind the extra typing, but these end up in the JS as well and ends up wasting bytes in my js files.

I would like to be able to the following:

getTabID(eventTarget: EventTarget) : string {
    let mTabID: string
    // Do the type assertion in the parameter
    if(<HTMLAnchorElement> eventTarget.hash){
        mTabID = mEventTarget.hash.split('#')[1]
    } else {
        mTabID = mEventTarget.dataset.tabId
    }
    return mTabID
}

I've had a good look in the docs and SO and can't seem to find any way to do this. Anyone have any ideas?

Body:
You can perform inline type assertions, by surrounding the assertion with parantheses:

if((<HTMLAnchorElement>eventTarget).hash) {

You might also see what you can do to prevent the need for a type assertion, for example:

getTabID(eventTarget: HTMLAnchorElement) : string {
    let mTabID: string;

    if(eventTarget.hash){
        mTabID = eventTarget.hash.split('#')[1]
    }

    return mTabID
}

And lastly, watch out for the casing as you mixed EventTarget and eventTarget in one of your examples.


问:
JSONexception while fetching JSONArray JSONObject
Getting JSON Exception while fetching json response from server.I have tried many solutions given on stackoverflow but thats not working.Below is my code for sending parameters to the sever and fetching json.Please help me guys.Any help will be appreciated.
Thanks

JSON Response from server:

Note:"upload" is an JSONarray .

```<code>  {
        "code": 200,
        "upload": {
        "Booking": {
        "id": "17",
        "contributor_id": "16",
        "table_of_content_id": "1",
        "composition_id": "12",
        "completion": "2017-05-20",
        "approved": null,
        "cdn_id": null,
        "secret_token": null,
        "uploaded_on": null,
        "created": "2017-05-09 14:41:49",
        "modified": "2017-05-09 14:41:49"
        },
        "TableOfContent": {
        "id": "1",
        "name": "গোরা",
        "category_id": "1",
        "language_id": "1",
        "created": "2016-03-09 03:39:01",
        "modified": "2016-03-09 14:39:01"
        }
        }
        }
</code>```

This is how i am trying to do it.

```<code>public void forwardtoOurServer() {
        JSONObject jsonObject=null;
        String tag_string_req = "req_login";
        StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Audio Upload Response Check :" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            String code = json.getString("code");
                            JSONArray obj = json.getJSONArray("upload");
                            Log.d(TAG, "obj Response Check :" + obj);
                            for (int i = 0; i < obj.length(); i++) {

                                JSONObject jsonObject = obj.getJSONObject(i);
                                Log.d(TAG, "jsonObject Response Check :" + jsonObject);
                                JSONObject bookings = obj.getJSONObject(Integer.parseInt("Booking"));

//                                int id = jsonObject.getInt("id");
//
//                                String type = jsonObject.getString("type");

                                // retrieve the values like this so on..

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error Response Check :" + error);

                    }
                }) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("data[Booking][id]",bookingId);
                params.put("data[Booking][contributor_id]",contributor_id);
                params.put("data[Booking][table_of_content_id]",tocId);
                params.put("data[Booking][cdn_id]",vs_cdn_id);
                params.put("data[Booking][secret_token]",secret_token);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                Date now = new Date();
                String strDate = sdf.format(now);
                params.put("data[Booking][uploaded_on]",strDate);
                Log.d(TAG, "Params :" + params);
                return params;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("UUID", device_uuid);
                headers.put("APPID", "2A192A0C22");
                headers.put("USERID", "1");
                headers.put("PLATFORM", "Andriod");
                headers.put("APP_REQUEST", "1");
                headers.put("PLATFORMVERSION",androidOS);
                return headers;
            }

        };

        AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);

    }
</code>```

Log:

```<code>06-07 12:44:18.865 13701-13903/com.showhow2.www.thetagoreproject D/Null: Params :{data[Booking][cdn_id]=326929293, data[Booking][table_of_content_id]=1, data[Booking][id]=16, data[Booking][secret_token]=s-0DT7x, data[Booking][contributor_id]=16, data[Booking][uploaded_on]=2017-06-07T07:14:18Z}
06-07 12:44:20.629 13701-13701/com.showhow2.www.thetagoreproject D/Null: Audio Upload Response Check :{"code":200,"upload":{"Booking":{"id":"17","contributor_id":"16","table_of_content_id":"1","composition_id":"12","completion":"2017-05-20","approved":null,"cdn_id":null,"secret_token":null,"uploaded_on":null,"created":"2017-05-09 14:41:49","modified":"2017-05-09 14:41:49"},"TableOfContent":{"id":"1","name":"\u0997\u09cb\u09b0\u09be","category_id":"1","language_id":"1","created":"2016-03-09 03:39:01","modified":"2016-03-09 14:39:01"},"Composition":{"id":"12","content":"\u09ac\u09bf\u09a8\u09df \u0993 \u0997\u09cb\u09b0\u09be \u09aa\u09b0\u09c7\u09b6\u09c7\u09b0 \u09ac\u09be\u09dc\u09bf \u09b9\u0987\u09a4\u09c7 \u09b0\u09be\u09b8\u09cd\u09a4\u09be\u09df \u09ac\u09be\u09b9\u09bf\u09b0 \u09b9\u0987\u09b2\u09c7 \u09ac\u09bf\u09a8\u09df \u0995\u09b9\u09bf\u09b2, "\u0997\u09cb\u09b0\u09be, \u098f\u0995\u099f\u09c1 \u0986\u09b8\u09cd\u09a4\u09c7 \u0986\u09b8\u09cd\u09a4\u09c7 \u099a\u09b2\u09cb \u09ad\u09be\u0987-- \u09a4\u09cb\u09ae\u09be\u09b0 \u09aa\u09be \u09a6\u09c1\u099f\u09cb \u0986\u09ae\u09be\u09a6\u09c7\u09b0 \u099a\u09c7\u09df\u09c7 \u0985\u09a8\u09c7\u0995 \u09ac\u09dc\u09cb-- \u0993\u09b0 \u099a\u09be\u09b2\u099f\u09be \u098f\u0995\u099f\u09c1 \u0996\u09be\u099f\u09cb \u09a8\u09be \u0995\u09b0\u09b2\u09c7 \u09a4\u09cb\u09ae\u09be\u09b0 \u09b8\u0999\u09cd\u0997\u09c7 \u09af\u09c7\u09a4\u09c7 \u0986\u09ae\u09b0\u09be \u09b9\u09be\u0981\u09aa\u09bf\u09df\u09c7 \u09aa\u09dc\u09bf\u0964"\n \u0997\u09cb\u09b0\u09be \u0995\u09b9\u09bf\u09b2, "\u0986\u09ae\u09bf \u098f\u0995\u09b2\u09be\u0987 \u09af\u09c7\u09a4\u09c7 \u099a\u09be\u0987, \u0986\u09ae\u09be\u09b0 \u0986\u099c \u0985\u09a8\u09c7\u0995 \u0995\u09a5\u09be \u09ad\u09be\u09ac\u09ac\u09be\u09b0 \u0986\u099b\u09c7\u0964"\n \u09ac\u09b2\u09bf\u09df\u09be \u09a4\u09be\u09b9\u09be\u09b0 \u09b8\u09cd\u09ac\u09be\u09ad\u09be\u09ac\u09bf\u0995 \u09a6\u09cd\u09b0\u09c1\u09a4\u0997\u09a4\u09bf\u09a4\u09c7 \u09b8\u09c7 \u09ac\u09c7\u0997\u09c7 \u099a\u09b2\u09bf\u09df\u09be \u0997\u09c7\u09b2\u0964\n \u09ac\u09bf\u09a8\u09df\u09c7\u09b0 \u09ae\u09a8\u09c7 \u0986\u0998\u09be\u09a4 \u09b2\u09be\u0997\u09bf\u09b2\u0964 \u09b8\u09c7 \u0986\u099c \u0997\u09cb\u09b0\u09be\u09b0 \u09ac\u09bf\u09b0\u09c1\u09a6\u09cd\u09a7\u09c7 \u09ac\u09bf\u09a6\u09cd\u09b0\u09cb\u09b9 \u0995\u09b0\u09bf\u09df\u09be \u09a4\u09be\u09b9\u09be\u09b0 \u09a8\u09bf\u09df\u09ae \u09ad\u0999\u09cd\u0997 \u0995\u09b0\u09bf\u09df\u09be\u099b\u09c7\u0964 \u09b8\u09c7 \u09b8\u09ae\u09cd\u09ac\u09a8\u09cd\u09a7\u09c7 \u0997\u09cb\u09b0\u09be\u09b0 \u0995\u09be\u099b\u09c7 \u09a4\u09bf\u09b0\u09b8\u09cd\u0995\u09be\u09b0 \u09ad\u09cb\u0997 \u0995\u09b0\u09bf\u09b2\u09c7 \u09b8\u09c7 \u0996\u09c1\u09b6\u09bf \u09b9\u0987\u09a4\u0964 \u098f\u0995\u099f\u09be \u099d\u09dc \u09b9\u0987\u09df\u09be \u0997\u09c7\u09b2\u09c7\u0987 \u09a4\u09be\u09b9\u09be\u09a6\u09c7\u09b0 \u099a\u09bf\u09b0\u09a6\u09bf\u09a8\u09c7\u09b0 \u09ac\u09a8\u09cd\u09a7\u09c1\u09a4\u09cd\u09ac\u09c7\u09b0 \u0986\u0995\u09be\u09b6 \u09b9\u0987\u09a4\u09c7 \u0997\u09c1\u09ae\u099f \u0995\u09be\u099f\u09bf\u09df\u09be \u09af\u09be\u0987\u09a4 \u098f\u09ac\u0982 \u09b8\u09c7 \u09b9\u09be\u0981\u09aa \u099b\u09be\u09dc\u09bf\u09df\u09be \u09ac\u09be\u0981\u099a\u09bf\u09a4\u0964\n \u09a4\u09be\u09b9\u09be \u099b\u09be\u09dc\u09be \u0986\u09b0-\u098f\u0995\u099f\u09be \u0995\u09a5\u09be \u09a4\u09be\u09b9\u09be\u0995\u09c7 \u09aa\u09c0\u09dc\u09be \u09a6\u09bf\u09a4\u09c7\u099b\u09bf\u09b2\u0964 \u0986\u099c \u09b9\u09a0\u09be\u09ce \u0997\u09cb\u09b0\u09be \u09aa\u09b0\u09c7\u09b6\u09c7\u09b0 \u09ac\u09be\u09dc\u09bf\u09a4\u09c7 \u09aa\u09cd\u09b0\u09a5\u09ae \u0986\u09b8\u09bf\u09df\u09be\u0987 \u09ac\u09bf\u09a8\u09df\u0995\u09c7 \u09b8\u09c7\u0996\u09be\u09a8\u09c7 \u09ac\u09a8\u09cd\u09a7\u09c1\u09ad\u09be\u09ac\u09c7 \u09ac\u09b8\u09bf\u09df\u09be \u09a5\u09be\u0995\u09bf\u09a4\u09c7 \u09a6\u09c7\u0996\u09bf\u09df\u09be \u09a8\u09bf\u09b6\u09cd\u099a\u09df\u0987 \u09ae\u09a8\u09c7 \u0995\u09b0\u09bf\u09df\u09be\u099b\u09c7 \u09ac\u09bf\u09a8\u09df \u098f \u09ac\u09be\u
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err: org.json.JSONException: Value {"Booking":{"id":"17","contributor_id":"16","table_of_content_id":"1","composition_id":"12","completion":"2017-05-20","approved":null,"cdn_id":null,"secret_token":null,"uploaded_on":null,"created":"2017-05-09 14:41:49","modified":"2017-05-09 14:41:49"},"TableOfContent":{"id":"1","name":"গোরা","category_id":"1","language_id":"1","created":"2016-03-09 03:39:01","modified":"2016-03-09 14:39:01"},"Composition":{"id":"12","content":"বিনয় ও গোরা পরেশের বাড়ি হইতে রাস্তায় বাহির হইলে বিনয় কহিল, "গোরা, একটু আস্তে আস্তে চলো ভাই-- তোমার পা দুটো আমাদের চেয়ে অনেক বড়ো-- ওর চালটা একটু খাটো না করলে তোমার সঙ্গে যেতে আমরা হাঁপিয়ে পড়ি।"\n গোরা কহিল, "আমি একলাই যেতে চাই, আমার আজ অনেক কথা ভাববার আছে।"\n বলিয়া তাহার স্বাভাবিক দ্রুতগতিতে সে বেগে চলিয়া গেল।\n বিনয়ের মনে আঘাত লাগিল। সে আজ গোরার বিরুদ্ধে বিদ্রোহ করিয়া তাহার নিয়ম ভঙ্গ করিয়াছে। সে সম্বন্ধে গোরার কাছে তিরস্কার ভোগ করিলে সে খুশি হইত। একটা ঝড় হইয়া গেলেই তাহাদের চিরদিনের বন্ধুত্বের আকাশ হইতে গুমট কাটিয়া যাইত এবং সে হাঁপ ছাড়িয়া বাঁচিত।\n তাহা ছাড়া আর-একটা কথা তাহাকে পীড়া দিতেছিল। আজ হঠাৎ গোরা পরেশের বাড়িতে প্রথম আসিয়াই বিনয়কে সেখানে বন্ধুভাবে বসিয়া থাকিতে দেখিয়া নিশ্চয়ই মনে করিয়াছে বিনয় এ বাড়িতে সর্বদাই যাতায়াত করে। অবশ্য, যাতায়াত করিলে যে কোনো অপরাধ আছে তাহা নয়; গোরা যাহাই বলুক পরেশবাবুর সুশিক্ষিত পরিবারের সঙ্গে অন্তরঙ্গভাবে পরিচিত হইবার সুযোগ পাওয়া বিনয় একটা বিশেষ লাভ বলিয়া গণ্য করিতেছে; ইঁহাদের সঙ্গে মেশামেশি করাতে গোরা যদি কোনো দোষ দেখে তবে সেটা তাহার নিতান্ত গোঁড়ামি; কিন্তু পূর্বের কথাবার্তায় গোরা নাকি জানিয়াছে যে বিনয় পরেশবাবুর বাড়িতে যাওয়া-আসা করে না, আজ সহসা তাহার মনে হইতে পারে যে সে কথাটা সত্য নয়। বিশেষত বরদাসুন্দরী তাহাকে বিশেষ করিয়া ঘরে ডাকিয়া লইয়া গেলেন, সেখানে তাঁহার মেয়েদের সঙ্গে তাহার আলাপ হইতে লাগিল-- গোরার তীক্ষ্ণ লক্ষ হইতে ইহা এড়াইয়া যায় নাই। মেয়েদের সঙ্গে এইরূপ মেলামেশায় ও বরদাসুন্দরীর আত্মীয়তায় মনে মনে বিনয় ভার�
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at org.json.JSON.typeMismatch(JSON.java:100)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:588)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.showhow2.www.thetagoreproject.RecordComposition$16.onResponse(RecordComposition.java:704)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.showhow2.www.thetagoreproject.RecordComposition$16.onResponse(RecordComposition.java:694)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Looper.loop(Looper.java:148)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
06-07 12:44:20.664 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
06-07 12:44:20.664 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
Your json is not valid, Remove the keys for items in the json array (Booking, modified) or move those objects from the array . Your json parsing code should be</p>

```<code>try {
      JSONObject json = new JSONObject(response);
      String code = json.getString("code");

      JsonObject upload = jsonObject.getJSONObject("upload");
      //get the other object like this

      } catch (JSONException e) {
          e.printStackTrace();

      }
</code>```

Body:
Getting JSON Exception while fetching json response from server.I have tried many solutions given on stackoverflow but thats not working.Below is my code for sending parameters to the sever and fetching json.Please help me guys.Any help will be appreciated.
Thanks

JSON Response from server:

Note:"upload" is an JSONarray .

  {
        "code": 200,
        "upload": {
        "Booking": {
        "id": "17",
        "contributor_id": "16",
        "table_of_content_id": "1",
        "composition_id": "12",
        "completion": "2017-05-20",
        "approved": null,
        "cdn_id": null,
        "secret_token": null,
        "uploaded_on": null,
        "created": "2017-05-09 14:41:49",
        "modified": "2017-05-09 14:41:49"
        },
        "TableOfContent": {
        "id": "1",
        "name": "গোরা",
        "category_id": "1",
        "language_id": "1",
        "created": "2016-03-09 03:39:01",
        "modified": "2016-03-09 14:39:01"
        }
        }
        }

This is how i am trying to do it.

public void forwardtoOurServer() {
        JSONObject jsonObject=null;
        String tag_string_req = "req_login";
        StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Audio Upload Response Check :" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            String code = json.getString("code");
                            JSONArray obj = json.getJSONArray("upload");
                            Log.d(TAG, "obj Response Check :" + obj);
                            for (int i = 0; i < obj.length(); i++) {

                                JSONObject jsonObject = obj.getJSONObject(i);
                                Log.d(TAG, "jsonObject Response Check :" + jsonObject);
                                JSONObject bookings = obj.getJSONObject(Integer.parseInt("Booking"));

//                                int id = jsonObject.getInt("id");
//
//                                String type = jsonObject.getString("type");

                                // retrieve the values like this so on..

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error Response Check :" + error);

                    }
                }) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("data[Booking][id]",bookingId);
                params.put("data[Booking][contributor_id]",contributor_id);
                params.put("data[Booking][table_of_content_id]",tocId);
                params.put("data[Booking][cdn_id]",vs_cdn_id);
                params.put("data[Booking][secret_token]",secret_token);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                Date now = new Date();
                String strDate = sdf.format(now);
                params.put("data[Booking][uploaded_on]",strDate);
                Log.d(TAG, "Params :" + params);
                return params;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("UUID", device_uuid);
                headers.put("APPID", "2A192A0C22");
                headers.put("USERID", "1");
                headers.put("PLATFORM", "Andriod");
                headers.put("APP_REQUEST", "1");
                headers.put("PLATFORMVERSION",androidOS);
                return headers;
            }

        };

        AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);

    }

Log:

06-07 12:44:18.865 13701-13903/com.showhow2.www.thetagoreproject D/Null: Params :{data[Booking][cdn_id]=326929293, data[Booking][table_of_content_id]=1, data[Booking][id]=16, data[Booking][secret_token]=s-0DT7x, data[Booking][contributor_id]=16, data[Booking][uploaded_on]=2017-06-07T07:14:18Z}
06-07 12:44:20.629 13701-13701/com.showhow2.www.thetagoreproject D/Null: Audio Upload Response Check :{"code":200,"upload":{"Booking":{"id":"17","contributor_id":"16","table_of_content_id":"1","composition_id":"12","completion":"2017-05-20","approved":null,"cdn_id":null,"secret_token":null,"uploaded_on":null,"created":"2017-05-09 14:41:49","modified":"2017-05-09 14:41:49"},"TableOfContent":{"id":"1","name":"\u0997\u09cb\u09b0\u09be","category_id":"1","language_id":"1","created":"2016-03-09 03:39:01","modified":"2016-03-09 14:39:01"},"Composition":{"id":"12","content":"\u09ac\u09bf\u09a8\u09df \u0993 \u0997\u09cb\u09b0\u09be \u09aa\u09b0\u09c7\u09b6\u09c7\u09b0 \u09ac\u09be\u09dc\u09bf \u09b9\u0987\u09a4\u09c7 \u09b0\u09be\u09b8\u09cd\u09a4\u09be\u09df \u09ac\u09be\u09b9\u09bf\u09b0 \u09b9\u0987\u09b2\u09c7 \u09ac\u09bf\u09a8\u09df \u0995\u09b9\u09bf\u09b2, "\u0997\u09cb\u09b0\u09be, \u098f\u0995\u099f\u09c1 \u0986\u09b8\u09cd\u09a4\u09c7 \u0986\u09b8\u09cd\u09a4\u09c7 \u099a\u09b2\u09cb \u09ad\u09be\u0987-- \u09a4\u09cb\u09ae\u09be\u09b0 \u09aa\u09be \u09a6\u09c1\u099f\u09cb \u0986\u09ae\u09be\u09a6\u09c7\u09b0 \u099a\u09c7\u09df\u09c7 \u0985\u09a8\u09c7\u0995 \u09ac\u09dc\u09cb-- \u0993\u09b0 \u099a\u09be\u09b2\u099f\u09be \u098f\u0995\u099f\u09c1 \u0996\u09be\u099f\u09cb \u09a8\u09be \u0995\u09b0\u09b2\u09c7 \u09a4\u09cb\u09ae\u09be\u09b0 \u09b8\u0999\u09cd\u0997\u09c7 \u09af\u09c7\u09a4\u09c7 \u0986\u09ae\u09b0\u09be \u09b9\u09be\u0981\u09aa\u09bf\u09df\u09c7 \u09aa\u09dc\u09bf\u0964"\n \u0997\u09cb\u09b0\u09be \u0995\u09b9\u09bf\u09b2, "\u0986\u09ae\u09bf \u098f\u0995\u09b2\u09be\u0987 \u09af\u09c7\u09a4\u09c7 \u099a\u09be\u0987, \u0986\u09ae\u09be\u09b0 \u0986\u099c \u0985\u09a8\u09c7\u0995 \u0995\u09a5\u09be \u09ad\u09be\u09ac\u09ac\u09be\u09b0 \u0986\u099b\u09c7\u0964"\n \u09ac\u09b2\u09bf\u09df\u09be \u09a4\u09be\u09b9\u09be\u09b0 \u09b8\u09cd\u09ac\u09be\u09ad\u09be\u09ac\u09bf\u0995 \u09a6\u09cd\u09b0\u09c1\u09a4\u0997\u09a4\u09bf\u09a4\u09c7 \u09b8\u09c7 \u09ac\u09c7\u0997\u09c7 \u099a\u09b2\u09bf\u09df\u09be \u0997\u09c7\u09b2\u0964\n \u09ac\u09bf\u09a8\u09df\u09c7\u09b0 \u09ae\u09a8\u09c7 \u0986\u0998\u09be\u09a4 \u09b2\u09be\u0997\u09bf\u09b2\u0964 \u09b8\u09c7 \u0986\u099c \u0997\u09cb\u09b0\u09be\u09b0 \u09ac\u09bf\u09b0\u09c1\u09a6\u09cd\u09a7\u09c7 \u09ac\u09bf\u09a6\u09cd\u09b0\u09cb\u09b9 \u0995\u09b0\u09bf\u09df\u09be \u09a4\u09be\u09b9\u09be\u09b0 \u09a8\u09bf\u09df\u09ae \u09ad\u0999\u09cd\u0997 \u0995\u09b0\u09bf\u09df\u09be\u099b\u09c7\u0964 \u09b8\u09c7 \u09b8\u09ae\u09cd\u09ac\u09a8\u09cd\u09a7\u09c7 \u0997\u09cb\u09b0\u09be\u09b0 \u0995\u09be\u099b\u09c7 \u09a4\u09bf\u09b0\u09b8\u09cd\u0995\u09be\u09b0 \u09ad\u09cb\u0997 \u0995\u09b0\u09bf\u09b2\u09c7 \u09b8\u09c7 \u0996\u09c1\u09b6\u09bf \u09b9\u0987\u09a4\u0964 \u098f\u0995\u099f\u09be \u099d\u09dc \u09b9\u0987\u09df\u09be \u0997\u09c7\u09b2\u09c7\u0987 \u09a4\u09be\u09b9\u09be\u09a6\u09c7\u09b0 \u099a\u09bf\u09b0\u09a6\u09bf\u09a8\u09c7\u09b0 \u09ac\u09a8\u09cd\u09a7\u09c1\u09a4\u09cd\u09ac\u09c7\u09b0 \u0986\u0995\u09be\u09b6 \u09b9\u0987\u09a4\u09c7 \u0997\u09c1\u09ae\u099f \u0995\u09be\u099f\u09bf\u09df\u09be \u09af\u09be\u0987\u09a4 \u098f\u09ac\u0982 \u09b8\u09c7 \u09b9\u09be\u0981\u09aa \u099b\u09be\u09dc\u09bf\u09df\u09be \u09ac\u09be\u0981\u099a\u09bf\u09a4\u0964\n \u09a4\u09be\u09b9\u09be \u099b\u09be\u09dc\u09be \u0986\u09b0-\u098f\u0995\u099f\u09be \u0995\u09a5\u09be \u09a4\u09be\u09b9\u09be\u0995\u09c7 \u09aa\u09c0\u09dc\u09be \u09a6\u09bf\u09a4\u09c7\u099b\u09bf\u09b2\u0964 \u0986\u099c \u09b9\u09a0\u09be\u09ce \u0997\u09cb\u09b0\u09be \u09aa\u09b0\u09c7\u09b6\u09c7\u09b0 \u09ac\u09be\u09dc\u09bf\u09a4\u09c7 \u09aa\u09cd\u09b0\u09a5\u09ae \u0986\u09b8\u09bf\u09df\u09be\u0987 \u09ac\u09bf\u09a8\u09df\u0995\u09c7 \u09b8\u09c7\u0996\u09be\u09a8\u09c7 \u09ac\u09a8\u09cd\u09a7\u09c1\u09ad\u09be\u09ac\u09c7 \u09ac\u09b8\u09bf\u09df\u09be \u09a5\u09be\u0995\u09bf\u09a4\u09c7 \u09a6\u09c7\u0996\u09bf\u09df\u09be \u09a8\u09bf\u09b6\u09cd\u099a\u09df\u0987 \u09ae\u09a8\u09c7 \u0995\u09b0\u09bf\u09df\u09be\u099b\u09c7 \u09ac\u09bf\u09a8\u09df \u098f \u09ac\u09be\u
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err: org.json.JSONException: Value {"Booking":{"id":"17","contributor_id":"16","table_of_content_id":"1","composition_id":"12","completion":"2017-05-20","approved":null,"cdn_id":null,"secret_token":null,"uploaded_on":null,"created":"2017-05-09 14:41:49","modified":"2017-05-09 14:41:49"},"TableOfContent":{"id":"1","name":"গোরা","category_id":"1","language_id":"1","created":"2016-03-09 03:39:01","modified":"2016-03-09 14:39:01"},"Composition":{"id":"12","content":"বিনয় ও গোরা পরেশের বাড়ি হইতে রাস্তায় বাহির হইলে বিনয় কহিল, "গোরা, একটু আস্তে আস্তে চলো ভাই-- তোমার পা দুটো আমাদের চেয়ে অনেক বড়ো-- ওর চালটা একটু খাটো না করলে তোমার সঙ্গে যেতে আমরা হাঁপিয়ে পড়ি।"\n গোরা কহিল, "আমি একলাই যেতে চাই, আমার আজ অনেক কথা ভাববার আছে।"\n বলিয়া তাহার স্বাভাবিক দ্রুতগতিতে সে বেগে চলিয়া গেল।\n বিনয়ের মনে আঘাত লাগিল। সে আজ গোরার বিরুদ্ধে বিদ্রোহ করিয়া তাহার নিয়ম ভঙ্গ করিয়াছে। সে সম্বন্ধে গোরার কাছে তিরস্কার ভোগ করিলে সে খুশি হইত। একটা ঝড় হইয়া গেলেই তাহাদের চিরদিনের বন্ধুত্বের আকাশ হইতে গুমট কাটিয়া যাইত এবং সে হাঁপ ছাড়িয়া বাঁচিত।\n তাহা ছাড়া আর-একটা কথা তাহাকে পীড়া দিতেছিল। আজ হঠাৎ গোরা পরেশের বাড়িতে প্রথম আসিয়াই বিনয়কে সেখানে বন্ধুভাবে বসিয়া থাকিতে দেখিয়া নিশ্চয়ই মনে করিয়াছে বিনয় এ বাড়িতে সর্বদাই যাতায়াত করে। অবশ্য, যাতায়াত করিলে যে কোনো অপরাধ আছে তাহা নয়; গোরা যাহাই বলুক পরেশবাবুর সুশিক্ষিত পরিবারের সঙ্গে অন্তরঙ্গভাবে পরিচিত হইবার সুযোগ পাওয়া বিনয় একটা বিশেষ লাভ বলিয়া গণ্য করিতেছে; ইঁহাদের সঙ্গে মেশামেশি করাতে গোরা যদি কোনো দোষ দেখে তবে সেটা তাহার নিতান্ত গোঁড়ামি; কিন্তু পূর্বের কথাবার্তায় গোরা নাকি জানিয়াছে যে বিনয় পরেশবাবুর বাড়িতে যাওয়া-আসা করে না, আজ সহসা তাহার মনে হইতে পারে যে সে কথাটা সত্য নয়। বিশেষত বরদাসুন্দরী তাহাকে বিশেষ করিয়া ঘরে ডাকিয়া লইয়া গেলেন, সেখানে তাঁহার মেয়েদের সঙ্গে তাহার আলাপ হইতে লাগিল-- গোরার তীক্ষ্ণ লক্ষ হইতে ইহা এড়াইয়া যায় নাই। মেয়েদের সঙ্গে এইরূপ মেলামেশায় ও বরদাসুন্দরীর আত্মীয়তায় মনে মনে বিনয় ভার�
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at org.json.JSON.typeMismatch(JSON.java:100)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:588)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.showhow2.www.thetagoreproject.RecordComposition$16.onResponse(RecordComposition.java:704)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.showhow2.www.thetagoreproject.RecordComposition$16.onResponse(RecordComposition.java:694)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Looper.loop(Looper.java:148)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
06-07 12:44:20.664 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
06-07 12:44:20.664 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
Your json is not valid, Remove the keys for items in the json array (Booking, modified) or move those objects from the array . Your json parsing code should be

try {
      JSONObject json = new JSONObject(response);
      String code = json.getString("code");

      JsonObject upload = jsonObject.getJSONObject("upload");
      //get the other object like this

      } catch (JSONException e) {
          e.printStackTrace();

      }


问:
Handling $_SESSION object in a load-balanced setup, PHP
I have a setup where I have a host which routes multiple requests in a load-balanced fashion. My backend uses PHP. Now, I need to use the $_SESSION object for some of my processing.

Will $_SESSION work where I have 3 backend servers which can receive any request at any time?

If not, Can one suggest alternatives to handle such cases?

EDIT: I do understand that we can store sessions in a database and find a way to track it. But, the problem in a realtime load-balanced production scenario is the number of calls that go into a DB. That can be a real bummer for my performance. I'm kind of hoping that, we can handle this at an webserver level.

Not sure, if it is possible, but, if two webservers have some kind of replication mechanism like databases do, it will be brilliant. I dont have to do a thing.

If such a thing does not exist, PHP should be modified to support it. That will actually, make it a seriously robust language.

答:
You can store sessions in memcache in order to share session among servers.

Please have a look on documentation here


问:
Are Functional Programming & Markov Chains related somehow?
David Silver describes a property of Markov Chains as:

The future is independent of the past given the present

https://www.youtube.com/watch?v=lfHX2hHRMVQ (4 mins into video)

This struck a chord with me because I am currently learning about functional programming(FP).

In FP you can also ignore the past because your functions only need the current state in order to perform some action and output a new state. THis isn't necessarily true with Object Oriented because your output might depend on several states in different places.

Is there some deeper connection between FP and Markov chains that I am unaware of?

Is it accurate to say, for example, that functions written in FP are deterministic Markov chains?

答:
There is indeed a connection between a Markov chain and Functional Programming. A Markov chain is a type of a non-deterministic Finite-State Machine (FSM), whereas chaining pure functions would produce a deterministic FSM. The caveat here is that in the real-world (e.g., Web applications) you often need also functions that are not pure (e.g., modify or query an external database).

I have found it very useful to model program state as a Finite-State Machine (FSM), both as a metaphor and as a concrete way to model states and transitions. For example, a FSM represents nicely which actions are allowed at which state when implementing (Web) user interfaces.


问:
How can I check wether an array contains any item or is completely empty?
If I define an integer array:

```<code>int[] a = new int[13];
</code>```

and I do not insert any item into it, how can I know whether the array a contains any items or is completely empty?
Do I have to iterate through all the a.Length indices?
In a list

```<code>List<int> b = new List<int>();
</code>```

if I check:

```<code>if(b.Count == 0)
{
    // The list does not contain any items.
}
</code>```

Is there an equivalent way to check an array?
I found on the internet the check if an array is null or empty.
In my case I know for sure that the array is not null.
I just wish to know whether it contains any item or not.
I do not care in which position within the array and also not exactly which item.
Thank you very much in advance.

答:
You can create your own class which encapsulates the Array class and keeps track of whether the array has been changed yet or not.

```<code>public class MyArray<T>
{
    private T[] array;
    private bool altered = false;

    public MyArray(int size)
    {
        array= new T[size + 1];
    }

    public T this[int index]
    {
        get
        {
            return array[index];
        }
        set
        {
            altered = true;
            array[index] = value;
        }

    }

    public bool HasBeenAltered()
    {
        return altered;
    }
}
</code>```

The function HasBeenAltered() tells whether any item of the array has been updated.

```<code>MyArray<int> arr = new MyArray<int>(10);
arr.HasBeenAltered(); // false

arr[4] = 4;
arr.HasBeenAltered(); // true
</code>```

Body:
If I define an integer array:

int[] a = new int[13];

and I do not insert any item into it, how can I know whether the array a contains any items or is completely empty?
Do I have to iterate through all the a.Length indices?
In a list

List<int> b = new List<int>();

if I check:

if(b.Count == 0)
{
    // The list does not contain any items.
}

Is there an equivalent way to check an array?
I found on the internet the check if an array is null or empty.
In my case I know for sure that the array is not null.
I just wish to know whether it contains any item or not.
I do not care in which position within the array and also not exactly which item.
Thank you very much in advance.

Body:
You can create your own class which encapsulates the Array class and keeps track of whether the array has been changed yet or not.

public class MyArray<T>
{
    private T[] array;
    private bool altered = false;

    public MyArray(int size)
    {
        array= new T[size + 1];
    }

    public T this[int index]
    {
        get
        {
            return array[index];
        }
        set
        {
            altered = true;
            array[index] = value;
        }

    }

    public bool HasBeenAltered()
    {
        return altered;
    }
}

The function HasBeenAltered() tells whether any item of the array has been updated.

MyArray<int> arr = new MyArray<int>(10);
arr.HasBeenAltered(); // false

arr[4] = 4;
arr.HasBeenAltered(); // true


问:
get repeated values in JSON object with javascript (JQuery)
I have this JSON object:

```<code>[
    {
        "idMaterial": "Alloy 450 (15Cr6Ni1.5Cu)_S45000",
        "tipoMaterial": "Alloy 450 (15Cr6Ni1.5Cu)",
        "uns": "S45000",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Recocido + endurecimiento por envejecido a 620ºC",
        "dureza": "31",
        "comentarios": "Cualquier combinación ",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "AISI 415 (12Cr5NiMo)_S41500",
        "tipoMaterial": "AISI 415 (12Cr5NiMo)",
        "uns": "S41500",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4NiMo_S42400",
        "tipoMaterial": "13Cr4NiMo",
        "uns": "S42400",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41425",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41425",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "28",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41426",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41426",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 105 Ksi. Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4Ni_S41429",
        "tipoMaterial": "13Cr4Ni",
        "uns": "S41429",
        "temperatura": "NL",
        "ph": "≥4,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "templado + revenido o normalizado +revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 120 Ksi .Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    }
]
</code>```

and that I want is to get all the repeated objects with the same "idMaterial" and "uns" value and put them in other object. Thanks for all (I havn't write all JSON data because is too long).

答:
var data = [{"id":"aaa","uns":"123"},{"id":"bbb","uns":"023"},{"id":"aaa","uns":"123"},{"id":"ccc","uns":"765"},{"id":"ddd","uns":"256"}];

var isEqualFunction = function(a, b){
  return a.id === b.id && a.uns === b.uns;
}

var compareFunction = function(a, b){
  return a.id === b.id
    ? (a.uns === b.uns ? 0 : (a.uns < b.uns ? -1 : 1))
    : (a.id < b.id ? -1 : 1);
}

var arrayOrdenado = data.sort(compareFunction);
var repetidos = [];
for (var i = 0; i < arrayOrdenado.length - 1; i++) {
  if (isEqualFunction(arrayOrdenado[i + 1], arrayOrdenado[i]))
  {
    repetidos.push(arrayOrdenado[i]);
  }
}
console.log(repetidos);```
</div>
</div>
</p>

<p>Another way to do it: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [{"id":"aaa","uns":"123"},{"id":"bbb","uns":"023"},{"id":"aaa","uns":"123"},{"id":"ccc","uns":"765"},{"id":"ddd","uns":"256"}];

var compareFunction = function(a, b){
  return a.id === b.id
    ? (a.uns === b.uns ? 0 : (a.uns < b.uns ? -1 : 1))
    : (a.id < b.id ? -1 : 1);
}

var arrayOrdenado = data.sort(compareFunction);
var repetidos = [];
for (var i = 0; i < arrayOrdenado.length - 1; i++) {
  if (compareFunction(arrayOrdenado[i + 1], arrayOrdenado[i]) === 0)
  {
    repetidos.push(arrayOrdenado[i]);
  }
}
console.log(repetidos);</code>```

This question was asked and resolved in SO spanish, and this is the link of it https://es.stackoverflow.com/questions/76231/obtener-los-objetos-que-se-repiten-en-un-array-de-objetos-json-con-javascript-j

Body:
I have this JSON object:

[
    {
        "idMaterial": "Alloy 450 (15Cr6Ni1.5Cu)_S45000",
        "tipoMaterial": "Alloy 450 (15Cr6Ni1.5Cu)",
        "uns": "S45000",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Recocido + endurecimiento por envejecido a 620ºC",
        "dureza": "31",
        "comentarios": "Cualquier combinación ",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "AISI 415 (12Cr5NiMo)_S41500",
        "tipoMaterial": "AISI 415 (12Cr5NiMo)",
        "uns": "S41500",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4NiMo_S42400",
        "tipoMaterial": "13Cr4NiMo",
        "uns": "S42400",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + doble revenido",
        "dureza": "23",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41425",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41425",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "28",
        "comentarios": "Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr5Ni2Mo (Súper 13 Cr)_S41426",
        "tipoMaterial": "13Cr5Ni2Mo (Súper 13 Cr)",
        "uns": "S41426",
        "temperatura": "NL",
        "ph": "≥3,5",
        "concetracionClMax": "NL",
        "azufreElemental": "No",
        "tratamientoTermico": "Austenitizado + templado + revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 105 Ksi. Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    },
    {
        "idMaterial": "13Cr4Ni_S41429",
        "tipoMaterial": "13Cr4Ni",
        "uns": "S41429",
        "temperatura": "NL",
        "ph": "≥4,5",
        "concetracionClMax": "NL",
        "azufreElemental": "ND",
        "tratamientoTermico": "templado + revenido o normalizado +revenido",
        "dureza": "27",
        "comentarios": "Grado máximo 120 Ksi .Cualquier combinación de T y [Cl] en medios de producción es aceptable",
        "origen": "NORMATIVA",
        "idEnsayo": "",
        "susceptibilidadSsc": null,
        "tipoResultado": "A",
        "ensayos": null,
        "h2S": "0,103"
    }
]

and that I want is to get all the repeated objects with the same "idMaterial" and "uns" value and put them in other object. Thanks for all (I havn't write all JSON data because is too long).

Body:
var data = [{"id":"aaa","uns":"123"},{"id":"bbb","uns":"023"},{"id":"aaa","uns":"123"},{"id":"ccc","uns":"765"},{"id":"ddd","uns":"256"}];

var isEqualFunction = function(a, b){
  return a.id === b.id && a.uns === b.uns;
}

var compareFunction = function(a, b){
  return a.id === b.id
    ? (a.uns === b.uns ? 0 : (a.uns < b.uns ? -1 : 1))
    : (a.id < b.id ? -1 : 1);
}

var arrayOrdenado = data.sort(compareFunction);
var repetidos = [];
for (var i = 0; i < arrayOrdenado.length - 1; i++) {
  if (isEqualFunction(arrayOrdenado[i + 1], arrayOrdenado[i]))
  {
    repetidos.push(arrayOrdenado[i]);
  }
}
console.log(repetidos);

Another way to do it:

var data = [{"id":"aaa","uns":"123"},{"id":"bbb","uns":"023"},{"id":"aaa","uns":"123"},{"id":"ccc","uns":"765"},{"id":"ddd","uns":"256"}];

var compareFunction = function(a, b){
  return a.id === b.id
    ? (a.uns === b.uns ? 0 : (a.uns < b.uns ? -1 : 1))
    : (a.id < b.id ? -1 : 1);
}

var arrayOrdenado = data.sort(compareFunction);
var repetidos = [];
for (var i = 0; i < arrayOrdenado.length - 1; i++) {
  if (compareFunction(arrayOrdenado[i + 1], arrayOrdenado[i]) === 0)
  {
    repetidos.push(arrayOrdenado[i]);
  }
}
console.log(repetidos);

This question was asked and resolved in SO spanish, and this is the link of it https://es.stackoverflow.com/questions/76231/obtener-los-objetos-que-se-repiten-en-un-array-de-objetos-json-con-javascript-j


问:
Fetch local date and time using lat-long
I've found tons of resources that are able to give the local offset from UTC using the lat long I supply. However I'm confused because of the different time zones and day light savings. I am looking for a straightforward approach or API where I just plug in my lat and long (because that's all I have in my application) and I get the local time and local date.

Thanks in advance

P.S. - I'm working in PHP and hence need php related solutions :)

答:
Geonames should do the job nicely:

http://www.geonames.org/

They've also got a php library.

For more detail of how this works please check HERE


问:
Service fabric more than one communication listener for service remoting
I am developing few micro services using Azure Service Fabric. I have some use cases which need the communication between micro services and I read about service remoting https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reliable-services-communication-remoting. I just wanted to know is it possible to support more than one listeners in a SF application. E.g. I have an existing stateless web api SF application which is having a listener like below

```<code>protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return new ServiceInstanceListener[]
        {
            new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint"))
        };
    }
</code>```

To the above list, I need to add a ServiceRemotingListener so that I can expose some data from Micro service for others. Is it possible or anything wrong with approach. I have done the Reverse proxy based communication, but bit concerned with the performance(since I am planning to perform a real time read operation from Service 1 to Service 2).

答:
In your CreateServiceInstanceListeners method you are returning an array of listeners. This means that it is possible to create multiple listeners. Just add it like you would with any other array:

```<code>protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
    return new ServiceInstanceListener[]
    {
        new ServiceInstanceListener(serviceContext => this.CreateServiceRemotingListener(serviceContext), "RemotingListener"),
        new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint"))
    };
}
</code>```

Note that even though the listener name is an optional parameter, you have to give your listeners a name. I've also experienced some problems with the service proxy trying to connect to the other endpoint. In order to solve this declare the remoting listener first and your other listeners second.

Body:
I am developing few micro services using Azure Service Fabric. I have some use cases which need the communication between micro services and I read about service remoting https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reliable-services-communication-remoting. I just wanted to know is it possible to support more than one listeners in a SF application. E.g. I have an existing stateless web api SF application which is having a listener like below

protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return new ServiceInstanceListener[]
        {
            new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint"))
        };
    }

To the above list, I need to add a ServiceRemotingListener so that I can expose some data from Micro service for others. Is it possible or anything wrong with approach. I have done the Reverse proxy based communication, but bit concerned with the performance(since I am planning to perform a real time read operation from Service 1 to Service 2).

Body:
In your CreateServiceInstanceListeners method you are returning an array of listeners. This means that it is possible to create multiple listeners. Just add it like you would with any other array:

protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
    return new ServiceInstanceListener[]
    {
        new ServiceInstanceListener(serviceContext => this.CreateServiceRemotingListener(serviceContext), "RemotingListener"),
        new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint"))
    };
}

Note that even though the listener name is an optional parameter, you have to give your listeners a name. I've also experienced some problems with the service proxy trying to connect to the other endpoint. In order to solve this declare the remoting listener first and your other listeners second.


问:
Forward all requests in in Node.js/Koa server from http://server/api/* to another ip?
I'm using Node.js and Koa to build a web server. However, I'd like to merge it with another server located at 192.168.1.5:80. How can I make it so that all requests to {my web server}:80/api/* are exactly the same as requests to 192.168.1.5:80/api/*.

Thanks in advance!

答:
You could use koa-proxy:

https://www.npmjs.com/package/koa-proxy

Then for the proxy, your code could look like this:

```<code>var koa = require('koa');
var proxy = require('koa-proxy');
var app = koa();
app.use(proxy({
    host:  'http://192.168.1.5', // proxy to 192.168.1.5:80...
    match: /^\/api\//        // ...just the /api routes
}));
app.listen(80);
</code>```

hope that helps ... (not testet)

Body:
You could use koa-proxy:

https://www.npmjs.com/package/koa-proxy

Then for the proxy, your code could look like this:

var koa = require('koa');
var proxy = require('koa-proxy');
var app = koa();
app.use(proxy({
    host:  'http://192.168.1.5', // proxy to 192.168.1.5:80...
    match: /^\/api\//        // ...just the /api routes
}));
app.listen(80);

hope that helps ... (not testet)


答:
Don't rely on the constructor of java.util.Date that takes a string. It's deprecated, so you should not be using it anyway. Parse the string using SimpleDateFormat:

```<code>DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
long startTime = fmt.parse(userDate).getTime();
</code>```

Also, what you are doing with currentDate is an unnecessarily complicated and roundabout way to get the timestamp in milliseconds from calendar. You could just do this:

```<code>long presentTime = calendar.getTime().getTime();
</code>```

No need for the variable currentDate.

Better yet would be to use the Java 8 date and time API (package java.time) instead of the old java.util.Date and java.util.Calendar classes.

Title: Day difference coming wrong

Body:
Don't rely on the constructor of java.util.Date that takes a string. It's deprecated, so you should not be using it anyway. Parse the string using SimpleDateFormat:

DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
long startTime = fmt.parse(userDate).getTime();

Also, what you are doing with currentDate is an unnecessarily complicated and roundabout way to get the timestamp in milliseconds from calendar. You could just do this:

long presentTime = calendar.getTime().getTime();

No need for the variable currentDate.

Better yet would be to use the Java 8 date and time API (package java.time) instead of the old java.util.Date and java.util.Calendar classes.


问:
Difference between using [] and list() in Python when using with set() function
Could anyone tell me why this function work:

```<code>def findDisappearedNumbers(self, nums):
    return list(set(range(1,len(nums)+1)) - set(nums))
</code>```

but this function doesn't work:

```<code>def findDisappearedNums(self, nums):
    return [set(range(1, len(nums)+1)) - set(nums)]
</code>```

I would like to use [] instead of list() because [] has a better performance, but using [] with set() function would give me an error while list() with set() function works fine. Thanks.

```<code>>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718enter code here
</code>```

答:
They do different things.

list(set('abc')) gives you a list with three elements: 'a', 'b', and 'c' in it.

[set('abc')] gives you a list with exactly one element: the set.

Body:
Could anyone tell me why this function work:

def findDisappearedNumbers(self, nums):
    return list(set(range(1,len(nums)+1)) - set(nums))

but this function doesn't work:

def findDisappearedNums(self, nums):
    return [set(range(1, len(nums)+1)) - set(nums)]

I would like to use [] instead of list() because [] has a better performance, but using [] with set() function would give me an error while list() with set() function works fine. Thanks.

>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718enter code here


问:
css odd and even selector not working
I'm creating a rating control made of half stars and I want to be able to select odd and even labels inside the .rating control. The selector shoudl look like this but it's not working here is my codepen check my html out while your there

```<code>.rating {
    label:nth-child(odd)::before {} // not working
}
.rating {
    label:nth-child(even)::before {} // not working
}
</code>```

Full CSS:

```<code>@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css);

html, body {
  margin: 0;
  height: 100%;
  min-height: 100%;
}

body {
  background: #272727;
}

.rating {
position: absolute;
display: inline-block;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

label {
  font-size: 24px;
  font-family: FontAwesome;
  color: #afa302;
}

label.half_l::before {
  content: '\f006';
  display: inline-block;
  width: 11px;
  overflow: hidden;
}

label.half_r {

  width: 12px;
  position: relative;
  overflow: hidden;
  display: inline-block;
  margin-right: 3px;
}
label.half_r::before {
  content: '\f006';
  display: inline-block;
  left: -11px;
  position: relative;
}

label {
  float: right;
}

label:hover {
  color: #fff239;
}

> input {
  display: none;
}

label.half_l:hover:before,
label.half_l:hover ~ label.half_l:before {
  content: '\f089';
  color: #fff239;
}

label.half_l:hover ~ label.half_r::before {
  content: '\f005';
  color: #fff239;
}

label.half_r:hover:before {
  content: '\f005';
  color: #fff239;
}

label.half_r:hover ~ label.half_r::before,
label.half_r:hover ~ label.half_l:before {
  content: '\f005';
  color: #fff239;
}

input[type=radio]:checked ~ label.half_l:before,
input[type=radio]:checked ~ label.half_r:before{
  content: '\f005';
}
</code>```

}

答:
If to use the nth-child selector you need to bypass the input's since it count all children no matter their type

The nth-child(4n+4) start from the 4:th element (your second label) and then counts to every 4:th and apply the rule, which in your case will be every even label

The nth-child(4n+2) start from the 2:nd element (your first label) and then counts to every 4:th and apply the rule, which in your case will be every odd label.

Note, one can also use nth-child(4n) instead of nth-child(4n+4), which will start from the 0:th element (which does not exists) and then counts to every 4:th.

```<code>.rating {
    label:nth-child(4n+4)::before {
      background: yellow;
  }
}
.rating {
    label:nth-child(4n+2)::before {
      background: blue;
  }
}
</code>```

Updated codepen

Title: css odd and even selector not working

Body:
I'm creating a rating control made of half stars and I want to be able to select odd and even labels inside the .rating control. The selector shoudl look like this but it's not working here is my codepen check my html out while your there

.rating {
    label:nth-child(odd)::before {} // not working
}
.rating {
    label:nth-child(even)::before {} // not working
}

Full CSS:

@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css);

html, body {
  margin: 0;
  height: 100%;
  min-height: 100%;
}

body {
  background: #272727;
}

.rating {
position: absolute;
display: inline-block;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

label {
  font-size: 24px;
  font-family: FontAwesome;
  color: #afa302;
}

label.half_l::before {
  content: '\f006';
  display: inline-block;
  width: 11px;
  overflow: hidden;
}

label.half_r {

  width: 12px;
  position: relative;
  overflow: hidden;
  display: inline-block;
  margin-right: 3px;
}
label.half_r::before {
  content: '\f006';
  display: inline-block;
  left: -11px;
  position: relative;
}

label {
  float: right;
}

label:hover {
  color: #fff239;
}

> input {
  display: none;
}

label.half_l:hover:before,
label.half_l:hover ~ label.half_l:before {
  content: '\f089';
  color: #fff239;
}

label.half_l:hover ~ label.half_r::before {
  content: '\f005';
  color: #fff239;
}

label.half_r:hover:before {
  content: '\f005';
  color: #fff239;
}

label.half_r:hover ~ label.half_r::before,
label.half_r:hover ~ label.half_l:before {
  content: '\f005';
  color: #fff239;
}

input[type=radio]:checked ~ label.half_l:before,
input[type=radio]:checked ~ label.half_r:before{
  content: '\f005';
}

}

Body:
If to use the nth-child selector you need to bypass the input's since it count all children no matter their type

The nth-child(4n+4) start from the 4:th element (your second label) and then counts to every 4:th and apply the rule, which in your case will be every even label

The nth-child(4n+2) start from the 2:nd element (your first label) and then counts to every 4:th and apply the rule, which in your case will be every odd label.

Note, one can also use nth-child(4n) instead of nth-child(4n+4), which will start from the 0:th element (which does not exists) and then counts to every 4:th.

.rating {
    label:nth-child(4n+4)::before {
      background: yellow;
  }
}
.rating {
    label:nth-child(4n+2)::before {
      background: blue;
  }
}

Updated codepen


问:
jQuery autocomplete on various data in single textbox
I have a textbox on which i want to bind multiple autocomplete JSON data. For example, if I type

Name:

the autocomplete data should display names of employees and after a delimeter (, OR ;) suppose I type

Department:

the autocomplete data should display options to select departments, so on and so forth. Any guidance as to how can this be achieved?

答: I like this jQuery autocomplete plugin. One of its features is, it can get its autocomplete data over AJAX. So it'll call your script (PHP or what have you) on the server and pass the current contents of the autocomplete text field as a parameter. From there, you can do whatever you want. Pick apart their text at whatever delimiter you choose, return whatever are sensible options for autocompletion, etc, etc. It's all in your hands at that point.</p>


答:
list() and [] do different things. list takes an iterable, and puts all of its elements into a list. [] takes individual elements, and puts them into a list.

Hence, list(iterable) will get you a list of the same length (and elements) as the iterable. [iterable] will make a list of length 1, where the only element in the list is the iterable, which in turn may contain multiple elements.

Title: Difference between using [] and list() in Python when using with set() function


问:
Videogular2 Ima implementation in Ionic 3
I use Videogular 2 on Ionic 3.
I follow this tutorial (https://videogular.github.io/videogular2/modules/ima-ads/) for the implementation. But when Videogular tries to load ads on VgImaAds.loadAds method, it gives this error 'googletag is not defined'. I have imported every module needed in App.module.ts.Here is the imports in App.module.ts.

```<code>imports: [
IonicModule.forRoot(MyApp,{
  backButtonText:'',
  backButtonIcon:'arrow-back',
  iconMode:'md',
  modalEnter: 'modal-slide-in',
  modalLeave: 'modal-slide-out',
}),
IonicStorageModule.forRoot(),
BrowserModule,
VgCoreModule,
VgControlsModule,
VgOverlayPlayModule,
VgBufferingModule,
VgImaAdsModule]
</code>```

Here is my page's component html.

```<code> <ion-content>
    <vg-player id="demo-player">
        <vg-ima-ads
            [vgCompanion]="'companion-ad'"
            [vgCompanionSize]="[728, 90]"
            [vgNetwork]="'6062'"
            [vgUnitPath]="'iab_vast_samples'"
            [vgAdTagUrl]="'http://pubads.g.doubleclick.net/gampad/ads?sz=640x360&iu=/20277799247/Tv8-App-Preroll&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&url=[referrer_url]&description_url=[description_url]&correlator='"
            [vgSkipButton]="'.skip-button'">
        </vg-ima-ads>

        <video [vgMedia]="media" #media id="singleVideo" preload="auto" crossorigin>
            <source [src]="liveStreamLink" type="application/x-mpegURL">
        </video>
    </vg-player>
    <div class='skip-button'>custom skip ad button</div>
    <div id="companion-ad"></div>
</ion-content>
</code>```

Also, i have added the  tag in the head section of index.html. But apparently, it can't find the googletag property of this script on VgImaAds.loadAds . What should i do?

答:
You need to initialize googletag property before declaration for the ima script in index.html</p>

```<code><script>
    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
    (function() {
    var gads = document.createElement('script');
    gads.async = true; gads.type = 'text/javascript';
    gads.src = 'https://www.googletagservices.com/tag/js/gpt.js';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gads, node);
    })();
</script>
</code>```

Body:
I use Videogular 2 on Ionic 3.
I follow this tutorial (https://videogular.github.io/videogular2/modules/ima-ads/) for the implementation. But when Videogular tries to load ads on VgImaAds.loadAds method, it gives this error 'googletag is not defined'. I have imported every module needed in App.module.ts.Here is the imports in App.module.ts.

imports: [
IonicModule.forRoot(MyApp,{
  backButtonText:'',
  backButtonIcon:'arrow-back',
  iconMode:'md',
  modalEnter: 'modal-slide-in',
  modalLeave: 'modal-slide-out',
}),
IonicStorageModule.forRoot(),
BrowserModule,
VgCoreModule,
VgControlsModule,
VgOverlayPlayModule,
VgBufferingModule,
VgImaAdsModule]

Here is my page's component html.

 <ion-content>
    <vg-player id="demo-player">
        <vg-ima-ads
            [vgCompanion]="'companion-ad'"
            [vgCompanionSize]="[728, 90]"
            [vgNetwork]="'6062'"
            [vgUnitPath]="'iab_vast_samples'"
            [vgAdTagUrl]="'http://pubads.g.doubleclick.net/gampad/ads?sz=640x360&iu=/20277799247/Tv8-App-Preroll&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&url=[referrer_url]&description_url=[description_url]&correlator='"
            [vgSkipButton]="'.skip-button'">
        </vg-ima-ads>

        <video [vgMedia]="media" #media id="singleVideo" preload="auto" crossorigin>
            <source [src]="liveStreamLink" type="application/x-mpegURL">
        </video>
    </vg-player>

custom skip ad button

</ion-content>

Also, i have added the  tag in the head section of index.html. But apparently, it can't find the googletag property of this script on VgImaAds.loadAds . What should i do?

Body:
You need to initialize googletag property before declaration for the ima script in index.html

<script>
    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
    (function() {
    var gads = document.createElement('script');
    gads.async = true; gads.type = 'text/javascript';
    gads.src = 'https://www.googletagservices.com/tag/js/gpt.js';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gads, node);
    })();
</script>