问:
C++ passing Dynamically-sized 2D Array to function
I'm trying to figure out how to pass 2D array, which is constructed dynamically to a function.
I know that number of columns must be specified, but it my case it depends on user input.

Are there any workarounds?

Example:

```<code>// Some function
void function(matrix[i][j]) {
// do stuff
}
// Main function
int N;
cout << "Size: ";
cin >> N;

int matrix[N][N];

for (int i=0;i<N;i++) { //
 for (int j=0;j<N;j++) {
  cin >> matrix[N][N];
 }
}

sort(matrix);
</code>```

You get the idea :)

答:
In C++, the compiler can figure out the size, since it's part of the type.  Won't work with dynamically sized matrices though.

```<code>template<size_t N, size_t M>
void function(int (&matrix)[N][M])
{
  // do stuff
}
</code>```

EDIT: In GCC only, which is required for your code defining the array, you can pass variable-length arrays directly:

```<code>void func(int N, int matrix[N][N])
{
  //do stuff
}
</code>```

See the gcc documentation

Body:
I'm trying to figure out how to pass 2D array, which is constructed dynamically to a function.
I know that number of columns must be specified, but it my case it depends on user input.

Are there any workarounds?

Example:

// Some function
void function(matrix[i][j]) {
// do stuff
}
// Main function
int N;
cout << "Size: ";
cin >> N;

int matrix[N][N];

for (int i=0;i<N;i++) { //
 for (int j=0;j<N;j++) {
  cin >> matrix[N][N];
 }
}

sort(matrix);

You get the idea :)

Body:
In C++, the compiler can figure out the size, since it's part of the type.  Won't work with dynamically sized matrices though.

template<size_t N, size_t M>
void function(int (&matrix)[N][M])
{
  // do stuff
}

EDIT: In GCC only, which is required for your code defining the array, you can pass variable-length arrays directly:

void func(int N, int matrix[N][N])
{
  //do stuff
}

See the gcc documentation


来源: stackexchange

问:
How to get servers time
Okay so i need a countdown to the servers midnight because when the server reach midnight it will run a cronjob which is relevant to the users so they need to see how many hours that are left untill it is midnight on the server and not in their own timezone.

Sample page here

The date_default_timezone_get(); is europe/copenhagen

PHP

(The page the Ajax is requesting)

```<code>echo time() * 1000;
</code>```

Javascript

```<code>            (function () {
                var test = document.getElementById("test");
                var difference = document.getElementById("difference");

                var serverMilli = document.getElementById("serverMilli");
                var serverCountdown = document.getElementById("serverCountdown");

                var machineMilli = document.getElementById("machineMilli");
                var machineCountdown = document.getElementById("machineCountdown");

                let serverTime;
                var localTime;

                var http = new XMLHttpRequest();
                var url = "time.php";
                http.open("POST", url, true);
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        serverTime = this.responseText;
                    }
                    ;
                };
                http.send();

                function countDownServer() {

                    var now = new Date();
                    var localTime = now.getTime();
                    var currentDiff = serverTime - localTime;
                    var currentTest = serverTime - currentDiff;

                    var currentTime = currentTest;
                    var eventDate = new Date();
                    eventDate.setDate(now.getDate() + 1);
                    eventDate.setHours(24);
                    eventDate.setMinutes(0);
                    eventDate.setSeconds(0);
                    eventDate.setMilliseconds(0);

                    var eventTime = eventDate.getTime();
                    var remainingTime = eventTime - currentTime;

                    var sekunder = Math.floor(remainingTime / 1000);
                    var minutter = Math.floor(sekunder / 60);
                    var timer = Math.floor(minutter / 60);

                    sekunder %= 60;
                    minutter %= 60;
                    timer %= 24;

                    sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
                    minutter = (minutter < 10) ? "0" + minutter : minutter;
                    timer = (timer < 10) ? "0" + timer : timer;

                    var testServer = timer + ":" + minutter + ":" + sekunder;
                    serverCountdown.textContent = testServer;
                    setTimeout(countDownServer, 1000);
                }
                countDownServer();
                })();
</code>```

Everything "kinda" works... the problem is if i change the timezone on my computer it will display longer hours untill midnight than it really is on the server?
How is this possible when the timezone on server is europe/copenhagen and i use time() ? should it not use the servers timezone?

答:
The JavaScript Date object always uses the user's computer time. You can use a library like Moment Timezone to set a different timezone that can be calculated on the client.

Otherwise you can try and calculate the difference between the server time and local time, but it might be off by an hour a couple times per year due to differences in DST.

ContentLicense: CC BY-SA 3.0

Title: How to get servers time

Body:
Okay so i need a countdown to the servers midnight because when the server reach midnight it will run a cronjob which is relevant to the users so they need to see how many hours that are left untill it is midnight on the server and not in their own timezone.

Sample page here

The date_default_timezone_get(); is europe/copenhagen

PHP

(The page the Ajax is requesting)

echo time() * 1000;

Javascript

            (function () {
                var test = document.getElementById("test");
                var difference = document.getElementById("difference");

                var serverMilli = document.getElementById("serverMilli");
                var serverCountdown = document.getElementById("serverCountdown");

                var machineMilli = document.getElementById("machineMilli");
                var machineCountdown = document.getElementById("machineCountdown");

                let serverTime;
                var localTime;

                var http = new XMLHttpRequest();
                var url = "time.php";
                http.open("POST", url, true);
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        serverTime = this.responseText;
                    }
                    ;
                };
                http.send();

                function countDownServer() {

                    var now = new Date();
                    var localTime = now.getTime();
                    var currentDiff = serverTime - localTime;
                    var currentTest = serverTime - currentDiff;

                    var currentTime = currentTest;
                    var eventDate = new Date();
                    eventDate.setDate(now.getDate() + 1);
                    eventDate.setHours(24);
                    eventDate.setMinutes(0);
                    eventDate.setSeconds(0);
                    eventDate.setMilliseconds(0);

                    var eventTime = eventDate.getTime();
                    var remainingTime = eventTime - currentTime;

                    var sekunder = Math.floor(remainingTime / 1000);
                    var minutter = Math.floor(sekunder / 60);
                    var timer = Math.floor(minutter / 60);

                    sekunder %= 60;
                    minutter %= 60;
                    timer %= 24;

                    sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
                    minutter = (minutter < 10) ? "0" + minutter : minutter;
                    timer = (timer < 10) ? "0" + timer : timer;

                    var testServer = timer + ":" + minutter + ":" + sekunder;
                    serverCountdown.textContent = testServer;
                    setTimeout(countDownServer, 1000);
                }
                countDownServer();
                })();

Everything "kinda" works... the problem is if i change the timezone on my computer it will display longer hours untill midnight than it really is on the server?
How is this possible when the timezone on server is europe/copenhagen and i use time() ? should it not use the servers timezone?


问:
Using regex for the first time
I just started using regex and I'm trying to solve this problem, but it keeps return null. What is wrong with my code?
I want it to return this = (833) 741-2093</p>

```<code>function phoneNumber(numbers){
  var num = numbers.join('');
  var r = /\(\d{3}\)\s\d{3}\-\d{4}/;
  var match = num.match(r);
  return match;
}

var output = phoneNumber([8, 3, 3, 7, 4, 1, 2, 0, 9, 3]);

console.log(output);
</code>```

答:
Regexp is used for parsing and analyzing strings, not for formatting them. In your case, you are trying to format a list of numbers. Make a tiny template-like language:

function format(template, digits) {
  let n = 0;
  return template.replace(/#/g, _ => digits[n++]);
}

console.log(format("(###) ###-####", [8, 3, 3, 7, 4, 1, 2, 0, 9, 3]));```

Title: Using regex for the first time

Body:
I just started using regex and I'm trying to solve this problem, but it keeps return null. What is wrong with my code?
I want it to return this = (833) 741-2093

function phoneNumber(numbers){
  var num = numbers.join('');
  var r = /\(\d{3}\)\s\d{3}\-\d{4}/;
  var match = num.match(r);
  return match;
}

var output = phoneNumber([8, 3, 3, 7, 4, 1, 2, 0, 9, 3]);

console.log(output);


问:
How to generate textarea dynamically when checkbox is checked in angular2
I am new to Angular2, trying to generate textarea dynamically when checkbox is checked and delete textarea when checkbox is unchecked in angular2., Is there any better solution? thanks in advance.</p>

答:
Set ngModel and then store it as a variable:

```<code><input type="checkbox" #isVisible="ngModel" [(ngModel)]="isTextareaVisible">
</code>```

Then use an *ngIf to toggle it:

```<code><textarea *ngIf="isVisible"></textarea>
</code>```

Sidenote: If this is inside a form tag, don't forget to add a name="isTextareaVisible" attribute to the input, or angular will complain.

Body:
Set ngModel and then store it as a variable:

<input type="checkbox" #isVisible="ngModel" [(ngModel)]="isTextareaVisible">

Then use an *ngIf to toggle it:

<textarea *ngIf="isVisible"></textarea>

Sidenote: If this is inside a form tag, don't forget to add a name="isTextareaVisible" attribute to the input, or angular will complain.


问:
How should I loop through this JSON data?
Here is my code I want to print out "song" property from data. Link to JSON is -> http://starlord.hackerearth.com/sureify/cokestudio

```<code><script type="text/javascript">
    var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response;
        showdata(myjsondata);
    }

    function showdata(data){
        var song_name = data;

        for (i = 0; i < 3; i++) {

            document.write(song_name);
            document.write("<br>");

        }
    }

</script>
</code>```

When I run it in browser I get [object Object],[object Object],[object Object],[object Object],[object Object] as OUTPUT or undefined.

答:
You need to use JSON.stringify; and if you plan to write to document I suggest wrapping in pre tags as well to retain string format.

let data = [
  {
    "song":"Afreen Afreen",
    "url":"http://hck.re/Rh8KTk",
    "artists":"Rahat Fateh Ali Khan, Momina Mustehsan",
    "cover_image":"http://hck.re/kWWxUI"
  },
  {
    "song":"Aik Alif",
    "url":"http://hck.re/ZeSJFd",
    "artists":"Saieen Zahoor, Noori",
    "cover_image":"http://hck.re/3Cm0IX"
  },
  {
    "song":"Tajdar e haram",
    "url":"http://hck.re/wxlUcX",
    "artists":"Atif Aslam",
    "cover_image":"http://hck.re/5dh4D5"
  }
];

document.write('```'+ JSON.stringify(data, null, '\t') + '```');```

Body:
Here is my code I want to print out "song" property from data. Link to JSON is -> http://starlord.hackerearth.com/sureify/cokestudio

When I run it in browser I get [object Object],[object Object],[object Object],[object Object],[object Object] as OUTPUT or undefined.

Body:
You need to use JSON.stringify; and if you plan to write to document I suggest wrapping in pre tags as well to retain string format.

let data = [
  {
    "song":"Afreen Afreen",
    "url":"http://hck.re/Rh8KTk",
    "artists":"Rahat Fateh Ali Khan, Momina Mustehsan",
    "cover_image":"http://hck.re/kWWxUI"
  },
  {
    "song":"Aik Alif",
    "url":"http://hck.re/ZeSJFd",
    "artists":"Saieen Zahoor, Noori",
    "cover_image":"http://hck.re/3Cm0IX"
  },
  {
    "song":"Tajdar e haram",
    "url":"http://hck.re/wxlUcX",
    "artists":"Atif Aslam",
    "cover_image":"http://hck.re/5dh4D5"
  }
];

document.write('<pre>'+ JSON.stringify(data, null, '\t') + '</pre>');


问:
TypeError when converting an array of floats to ints
I have a smooth function f(x) = sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2)
The task is to explore a non-smooth function h(x) = int(f(x)) on the interval of 1 to 30. In other words, each value of f (x) is converted to type int and the function takes only integer values. I am trying to build h(x) with help of matplotlib.

```<code>import math
import numpy as np
from scipy.optimize import minimize
from scipy.linalg import *
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x / 5.0) * np.exp(x / 10.0) + 5 * np.exp((-x / 2.0))

def h(x):
    return int(f(x))

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()
</code>```

The code doesn't work. Running the code raises

```<code>TypeError: only length-1 arrays can be converted to Python scalars
</code>```

Using VS I get:

答:
Use rounding down,

```<code>def h(x):
    return np.floor(f(x));
</code>```

or rounding towards zero

```<code>def h(x):
    return np.fix(f(x));
</code>```

instead of the implicit rounding during integer conversion.

Body:
I have a smooth function f(x) = sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2)
The task is to explore a non-smooth function h(x) = int(f(x)) on the interval of 1 to 30. In other words, each value of f (x) is converted to type int and the function takes only integer values. I am trying to build h(x) with help of matplotlib.

import math
import numpy as np
from scipy.optimize import minimize
from scipy.linalg import *
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x / 5.0) * np.exp(x / 10.0) + 5 * np.exp((-x / 2.0))

def h(x):
    return int(f(x))

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()

The code doesn't work. Running the code raises

TypeError: only length-1 arrays can be converted to Python scalars

Using VS I get:

Body:
Use rounding down,

def h(x):
    return np.floor(f(x));

or rounding towards zero

def h(x):
    return np.fix(f(x));

instead of the implicit rounding during integer conversion.


问:
String-literals without escaping null-character
When I built a function which gives the hexadecimal representation of a nibble (4 bits) and I looked at the binary file, for the lookuptable of the digits, there was an additional 0-char even if it was not used.

```<code>const char digits[] = "0123456789abcdef";
</code>```

I know that you can write it in form of an array:

```<code>const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
</code>```

But that would take a while to write and use more disk-space for other numerical-systems with more digits.
But is there any way to write it as a literal, but without the null-character at the end?

(I am using Clang with -std=c++14)

答:
This might be overkill, but if it’s acceptable to use std::array, then you can statically build one from a string literal using constexpr functions:

```<code>#include <array>
#include <iostream>

// A type-level list of indices.

template <size_t... Xs>
struct indices { using type = indices<Xs..., sizeof...(Xs)>; };

// Generate indices from 0 to N.

template <std::size_t N>
struct upto { using type = typename upto<N - 1>::type::type; };

template <>
struct upto<0> { using type = indices<>; };

// Make an array by assigning each character
// from the corresponding index in the source.

template <std::size_t... X, typename A = std::array<char, sizeof...(X)>>
constexpr A make_array(char const *const source, const indices<X...>&) {
    return A{{source[X]...}};
}

// A convenience function that deduces the size.

template <std::size_t N>
constexpr std::array<char, N - 1> string_constant(char const (&data)[N]) {
    return make_array(&data[0], typename upto<N - 1>::type{});
}

int main() {
    constexpr auto s = string_constant("123456");
    std::cout << sizeof(s) << '\n';
}
</code>```

Now sizeof(s) is 6, and if you look at the generated assembly, the string literal is stored as .ascii, not .asciz, so there is no trailing null character. You can use the member functions of std::array such as size(), begin(), and end(), and can cast &s[0] to const char * to access character data directly.

Body:
When I built a function which gives the hexadecimal representation of a nibble (4 bits) and I looked at the binary file, for the lookuptable of the digits, there was an additional 0-char even if it was not used.

const char digits[] = "0123456789abcdef";

I know that you can write it in form of an array:

const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

But that would take a while to write and use more disk-space for other numerical-systems with more digits.
But is there any way to write it as a literal, but without the null-character at the end?

(I am using Clang with -std=c++14)

Body:
This might be overkill, but if it’s acceptable to use std::array, then you can statically build one from a string literal using constexpr functions:

#include <array>
#include <iostream>

// A type-level list of indices.

template <size_t... Xs>
struct indices { using type = indices<Xs..., sizeof...(Xs)>; };

// Generate indices from 0 to N.

template <std::size_t N>
struct upto { using type = typename upto<N - 1>::type::type; };

template <>
struct upto<0> { using type = indices<>; };

// Make an array by assigning each character
// from the corresponding index in the source.

template <std::size_t... X, typename A = std::array<char, sizeof...(X)>>
constexpr A make_array(char const *const source, const indices<X...>&) {
    return A{{source[X]...}};
}

// A convenience function that deduces the size.

template <std::size_t N>
constexpr std::array<char, N - 1> string_constant(char const (&data)[N]) {
    return make_array(&data[0], typename upto<N - 1>::type{});
}

int main() {
    constexpr auto s = string_constant("123456");
    std::cout << sizeof(s) << '\n';
}

Now sizeof(s) is 6, and if you look at the generated assembly, the string literal is stored as .ascii, not .asciz, so there is no trailing null character. You can use the member functions of std::array such as size(), begin(), and end(), and can cast &s[0] to const char * to access character data directly.


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

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

namespace ConsoleApplication1
{
    class Program
    {

        static void clear()
        {

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

        }

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

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

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

            };

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

            Console.ReadKey();

        }
    }
}
</code>```

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

答:
You can call Console.Clear() before every update. This will remove all text from your Console. This would change your code to this:</p>

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

namespace ConsoleApplication1
{
    class Program
    {

        static void clear()
        {

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

        }

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

            client.DownloadProgressChanged += (o, e) =>
            {
                Console.Clear();
                Console.Write(e.ProgressPercentage + "% ");
                clear();

            };

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

            Console.ReadKey();

        }
    }
}
</code>```

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

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

namespace ConsoleApplication1
{
    class Program
    {

        static void clear()
        {

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

        }

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

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

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

            };

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

            Console.ReadKey();

        }
    }
}

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

Body:
You can call Console.Clear() before every update. This will remove all text from your Console. This would change your code to this:

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

namespace ConsoleApplication1
{
    class Program
    {

        static void clear()
        {

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

        }

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

            client.DownloadProgressChanged += (o, e) =>
            {
                Console.Clear();
                Console.Write(e.ProgressPercentage + "% ");
                clear();

            };

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

            Console.ReadKey();

        }
    }
}


问:
How can I select the first specific inner element?
Here is my HTML?

```<code><ul>
    <li>
        <a href="./link1">
            <div>something</div>
            <span><a href="./link2">link</a></span>
        </a>
    </li>
</ul>
</code>```

And this is my jQuery code:

```<code>$('li').on('click', function(){
    var link = $(this).find('a').attr('href');
})
</code>```

As you see, there is two  tags. And .find() refersh to both of them. While I just want to select the  which is right inside (one level) in the
 tag. So expected result is ./link.

What alternative should I use instead of .find() ?

答:
Try with eq(0) .It will get the first a tag

Or

Do with first('a')

```<code>$(this).children().first('a').attr('href')
</code>```

$('li').click(function(){
console.log($(this).children('a').eq(0).attr('href'))

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>click

            <div>something</div>
            <span>link</span>

    </li>
</ul></code>```

Body:
Here is my HTML?

something

            link

And this is my jQuery code:

$('li').on('click', function(){
    var link = $(this).find('a').attr('href');
})

As you see, there is two  tags. And .find() refersh to both of them. While I just want to select the  which is right inside (one level) in the
 tag. So expected result is ./link.

What alternative should I use instead of .find() ?

Body:
Try with eq(0) .It will get the first a tag

Or

Do with first('a')

$(this).children().first('a').attr('href')

$('li').click(function(){
console.log($(this).children('a').eq(0).attr('href'))

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>click
        <a href="./link1">
            <div>something</div>
            <span><a href="./link2">link</a></span>
        </a>
    </li>
</ul>


问:
How do I get rid of zeros at the end of dollars format on JAVA?
I'm having trouble getting rid of the zero's after I compile my program. The program will come out like:
Enter the amount of pennies: 456 <--- whatever number the user enters
456 pennies equals 8.0 dollars and 76.0 cents. I've been having trouble getting rid of the .0 at the end fo dollars and having cents with no zero at the end as well so it shows up like:
Enter the amount of pennies: 456
456 pennies equals 8 dollars and 76 cents.</p>

```<code>import.java.util.Scanner;
import java.util.*;
import java.text.DecimalFormat;
public class Blah

{

 public static void main(String[] args)
 {
  int pennies;
  double dollars;
  double cents=0;
  Scanner input=new Scanner(System.in);
  DecimalFormat decimalFormat = new DecimalFormat("0.#");

  System.out.print("Enter the amount of pennies: ");

  pennies=input.nextInt();

  dollars = pennies/100 - cents;
  cents = pennies % 100;

  if(dollars<0)
         dollars = -dollars;

  System.out.println(pennies + "pennies equals " + dollars + "dollars and " + cents + " cents.");

   }
}
</code>```

答:
You've created a DecimalFormat so now its time to use it

```<code>System.out.println(pennies + " pennies equals "
        + decimalFormat.format(dollars) + " dollars and "
        + decimalFormat.format(cents) + " cents.");
</code>```

Body:
I'm having trouble getting rid of the zero's after I compile my program. The program will come out like:
Enter the amount of pennies: 456 <--- whatever number the user enters
456 pennies equals 8.0 dollars and 76.0 cents. I've been having trouble getting rid of the .0 at the end fo dollars and having cents with no zero at the end as well so it shows up like:
Enter the amount of pennies: 456
456 pennies equals 8 dollars and 76 cents.

import.java.util.Scanner;
import java.util.*;
import java.text.DecimalFormat;
public class Blah

{

 public static void main(String[] args)
 {
  int pennies;
  double dollars;
  double cents=0;
  Scanner input=new Scanner(System.in);
  DecimalFormat decimalFormat = new DecimalFormat("0.#");

  System.out.print("Enter the amount of pennies: ");

  pennies=input.nextInt();

  dollars = pennies/100 - cents;
  cents = pennies % 100;

  if(dollars<0)
         dollars = -dollars;

  System.out.println(pennies + "pennies equals " + dollars + "dollars and " + cents + " cents.");

   }
}

Body:
You've created a DecimalFormat so now its time to use it

System.out.println(pennies + " pennies equals "
        + decimalFormat.format(dollars) + " dollars and "
        + decimalFormat.format(cents) + " cents.");


问:
Rails 5.1 mailer encoding errors
I'm following the Hartl Rails tutorial, v5.0.1 and got stuck on a Mailer test that (presumably) expects a specified encoding.

The relevant test clauses (I get similar errors on either line):

```<code>assert_match user.reset_token, mail.body.encoded
assert_match CGI.escape(user.email), mail.body.encoded
</code>```

The resulting error msg (truncated):

```<code>Failure:
UserMailerTest#test_password_reset
[...demo/test/mailers/user_mailer_test.rb:30]:
Expected /6qyclXtvAeFin0htTK7t7g/ to match # encoding: US-ASCII
</code>```

Please note that I'm using Rails 5.1.1 in my local repo. The mailer templates are using the default encodings, whatever they may be.

The error msg includes a long string of the email template; I can see "charset=UTF-8" and "Content-Transfer-Encoding: 7bit".

The MailerTest file also checks the same combination of user token and CGI-escaped email address for an account activation test case w/o issue.

Any suggestions? The Hartl tutorial hasn't delved into encodings up to this point.

答:
The problem is that mail.body must be a String, but you haven't set it yet in password_reset.

So, first set it:

```<code>def password_reset(user)
  @user = user
  @body = "My message body"

  mail to: user.email, subject: "password reset"
end
</code>```

And, second, use it in your template.

```<code># password_reset.html.erb
<h1>User#password_reset</h1>
<%= @body %>

# password_reset.text.erb
User#password_reset
<%= @body %>
</code>```

You will notice that @greeting has been removed, i did so because it is not longer being used (you will add your message in @body).

Title: Rails 5.1 mailer encoding errors

Body:
I'm following the Hartl Rails tutorial, v5.0.1 and got stuck on a Mailer test that (presumably) expects a specified encoding.

The relevant test clauses (I get similar errors on either line):

assert_match user.reset_token, mail.body.encoded
assert_match CGI.escape(user.email), mail.body.encoded

The resulting error msg (truncated):

Failure:
UserMailerTest#test_password_reset
[...demo/test/mailers/user_mailer_test.rb:30]:
Expected /6qyclXtvAeFin0htTK7t7g/ to match # encoding: US-ASCII

Please note that I'm using Rails 5.1.1 in my local repo. The mailer templates are using the default encodings, whatever they may be.

The error msg includes a long string of the email template; I can see "charset=UTF-8" and "Content-Transfer-Encoding: 7bit".

The MailerTest file also checks the same combination of user token and CGI-escaped email address for an account activation test case w/o issue.

Any suggestions? The Hartl tutorial hasn't delved into encodings up to this point.

Body:
The problem is that mail.body must be a String, but you haven't set it yet in password_reset.

So, first set it:

def password_reset(user)
  @user = user
  @body = "My message body"

  mail to: user.email, subject: "password reset"
end

And, second, use it in your template.

# password_reset.html.erb
<h1>User#password_reset</h1>
<%= @body %>

# password_reset.text.erb
User#password_reset
<%= @body %>

You will notice that @greeting has been removed, i did so because it is not longer being used (you will add your message in @body).


问:
Read JSON from Server (Java)
First of all, sorry for this silly question.

Can anyone help me out with the code about how to read this JSON file from server? I have messed up my java code after watching several tutorials.

```<code>[
  {
    "name": "Coleen Sanford",
    "location": {
      "latitude": -60.489023,
      "longitude": -32.311668
    }
  },
  {
    "name": "Bethany Church",
    "location": {
      "latitude": -1.304805,
      "longitude": -80.670287
    }
  },
  {
    "name": "Kristy Ware",
    "location": {
      "latitude": -46.443562,
      "longitude": -46.426997
    }
  },
  {
    "name": "Avery Navarro",
    "location": {
      "latitude": 35.719469,
      "longitude": -172.783006
    }
  },
  {
    "name": "Robyn Cruz",
    "location": null
  },
  {
    "name": "Vinson Hays",
    "location": null
  }
]
</code>```

This is my code:

```<code>/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray  contacts = new JSONArray (jsonStr);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String name = c.getString("name");

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject("location");
                    String latitude = phone.getString("latitude");
                    String longitude = phone.getString("longitude");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("name", name);
                    contact.put("latitude", latitude);
                    contact.put("longitude", longitude);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "latitude",
                "longitude"}, new int[]{R.id.name,
                R.id.latitude, R.id.longitude});

        lv.setAdapter(adapter);
    }

}}
</code>```

答:
Try that in your AsyncTask for download json file. This method returned String with json.

```<code>@Override
    protected String doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Authorization", "Basic that_my_Basic_Auth");
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        resultJson = buffer.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultJson;
}
</code>```

Then you can get JSONObject like this:

```<code>JSONObject json = new JSONObject(new MyAsyncTask().execute(string_url).get());
</code>```

Title: Read JSON from Server (Java)

Body:
First of all, sorry for this silly question.

Can anyone help me out with the code about how to read this JSON file from server? I have messed up my java code after watching several tutorials.

[
  {
    "name": "Coleen Sanford",
    "location": {
      "latitude": -60.489023,
      "longitude": -32.311668
    }
  },
  {
    "name": "Bethany Church",
    "location": {
      "latitude": -1.304805,
      "longitude": -80.670287
    }
  },
  {
    "name": "Kristy Ware",
    "location": {
      "latitude": -46.443562,
      "longitude": -46.426997
    }
  },
  {
    "name": "Avery Navarro",
    "location": {
      "latitude": 35.719469,
      "longitude": -172.783006
    }
  },
  {
    "name": "Robyn Cruz",
    "location": null
  },
  {
    "name": "Vinson Hays",
    "location": null
  }
]

This is my code:

/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray  contacts = new JSONArray (jsonStr);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String name = c.getString("name");

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject("location");
                    String latitude = phone.getString("latitude");
                    String longitude = phone.getString("longitude");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("name", name);
                    contact.put("latitude", latitude);
                    contact.put("longitude", longitude);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "latitude",
                "longitude"}, new int[]{R.id.name,
                R.id.latitude, R.id.longitude});

        lv.setAdapter(adapter);
    }

}}

Body:
Try that in your AsyncTask for download json file. This method returned String with json.

@Override
    protected String doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Authorization", "Basic that_my_Basic_Auth");
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        resultJson = buffer.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultJson;
}

Then you can get JSONObject like this:

JSONObject json = new JSONObject(new MyAsyncTask().execute(string_url).get());


问:
How to implement a binary search method to find matching string in two different text files
So i have two different text files. The first text file contains:

```<code>Apple
Banana
Berry
Lemon
Orange
</code>```

The second one contains:

```<code>Banana
Juice
Kiwi
Strawberry
Water
</code>```

The matching string I want outputted is "banana". I know how to implement this using hashsets, arraylists, and etc. But i want to use a binary search method. But I keep getting stuck because instead of dealing with integers, I am dealing with strings. Here is what I have so far:

```<code>public static boolean BinarySearch() throws FileNotFoundException {
        String compare;

        java.io.File firstlist= new java.io.File("firstlist.txt");
        Scanner scanner1= new Scanner(firstlist);

        java.io.File secondlist= new java.io.File("secondlist.txt");
        Scanner scanner2= new Scanner(secondlist);

        ArrayList<String> list= new ArrayList<>();
        while (scanner2.hasNextLine()){
            names.add(scanner2.nextLine());
        }

        int low =0;
        int high = list.size() -1;

        for(int i=0; i<list.size(); i++){
            compare=scanner1.nextLine();
            scanner2= new Scanner(list);

            while (high>=low){
                int middle = (low+high)/2;
                if (list.get(middle) == list.get(0)){
                    return 1;
                }
                if (list.get(middle) < list.get(0))
            }

        }
    }
</code>```

答:
You can't compare two strings with operators.

String a, b;

a == b checks if a and b are the SAME OBJECT. This will always be false.

Instead, use String.equals((String) a) or .equalsIgnoreCase() methods.

Body:
So i have two different text files. The first text file contains:

Apple
Banana
Berry
Lemon
Orange

The second one contains:

Banana
Juice
Kiwi
Strawberry
Water

The matching string I want outputted is "banana". I know how to implement this using hashsets, arraylists, and etc. But i want to use a binary search method. But I keep getting stuck because instead of dealing with integers, I am dealing with strings. Here is what I have so far:

public static boolean BinarySearch() throws FileNotFoundException {
        String compare;

        java.io.File firstlist= new java.io.File("firstlist.txt");
        Scanner scanner1= new Scanner(firstlist);

        java.io.File secondlist= new java.io.File("secondlist.txt");
        Scanner scanner2= new Scanner(secondlist);

        ArrayList<String> list= new ArrayList<>();
        while (scanner2.hasNextLine()){
            names.add(scanner2.nextLine());
        }

        int low =0;
        int high = list.size() -1;

        for(int i=0; i<list.size(); i++){
            compare=scanner1.nextLine();
            scanner2= new Scanner(list);

            while (high>=low){
                int middle = (low+high)/2;
                if (list.get(middle) == list.get(0)){
                    return 1;
                }
                if (list.get(middle) < list.get(0))
            }

        }
    }


问:
Converting a input (Password) into MD5
Hi I'm a bit new to this and can't exactly figure out how to get it working.

Here is my current code:

```<code>import hashlib

def PasswordCreate():
    password = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(password.encode('utf-8'))
    return password.hexdigest()

PasswordCreate()
</code>```

The error is:

```<code>AttributeError: '_hashlib.HASH' object has no attribute 'encode'
</code>```

答:
Hello Josh,

Try this code,

```<code>import hashlib
def PasswordCreate():
  inputVar = input(str("Please enter a password next to this text: "))
  password = hashlib.md5()
  password.update(inputVar.encode("utf-8"))
  return password.hexdigest()

# Create Variable for dipslay encoded value.
displayPass = PasswordCreate()
print "User Password is: ",displayPass
</code>```

Title: Converting a input (Password) into MD5

Body:
Hi I'm a bit new to this and can't exactly figure out how to get it working.

Here is my current code:

import hashlib

def PasswordCreate():
    password = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(password.encode('utf-8'))
    return password.hexdigest()

PasswordCreate()

The error is:

AttributeError: '_hashlib.HASH' object has no attribute 'encode'

Body:
Hello Josh,

Try this code,

import hashlib
def PasswordCreate():
  inputVar = input(str("Please enter a password next to this text: "))
  password = hashlib.md5()
  password.update(inputVar.encode("utf-8"))
  return password.hexdigest()

# Create Variable for dipslay encoded value.
displayPass = PasswordCreate()
print "User Password is: ",displayPass


问:
Android Studio List from API
I'm pretty new to Android Studio and I've gone through most of the BigNerdRanch's guide on it. I've done some research but I can't seem to find a method of taking the information from an API and then proceeding to list the information. Also, how would could I sort through the info from the API to find object such as time? Much appreciated!</p>

答:
There is official information with sample app exactly about this.
https://developer.android.com/training/basics/network-ops/connecting.html

good luck!

Title: Android Studio List from API


答:
You need to stringify the object to make it readable.</p>

```<code><html>
<body>
<script type="text/javascript">
    var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response;
        showdata(myjsondata);
    }

    function showdata(data){
        var song_name = data;

        for (i = 0; i < 3; i++) {

            document.write(JSON.stringify(song_name));
            document.write("<br>");

        }
    }

</script>
</body>
</html>
</code>```

Title: How should I loop through this JSON data?

Body:
Here is my code I want to print out "song" property from data. Link to JSON is -> http://starlord.hackerearth.com/sureify/cokestudio

When I run it in browser I get [object Object],[object Object],[object Object],[object Object],[object Object] as OUTPUT or undefined.

Body:
You need to stringify the object to make it readable.

<html>
<body>
<script type="text/javascript">
    var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response;
        showdata(myjsondata);
    }

    function showdata(data){
        var song_name = data;

        for (i = 0; i < 3; i++) {

            document.write(JSON.stringify(song_name));
            document.write("<br>");

        }
    }

</script>
</body>
</html>


问:
Why are string in .net case sensitive by default?
Most times I want to do string comparisons I want them to be case insensitive.

So why are string in .net case sensitive by default?

EDIT 1: To be clear I think the below should return true by default. Or at least allow me to have a compile time flag that makes it so.

```<code>"John Smith" == "JOHN SMITH"
</code>```

EDIT 2: I can think of many more examples of things that should be case insensitive

Examples of things that should be case insensitive

Usernames

Urls

File extensions / File names / Directory names / Paths

Machine / servernames

State / Country / Location etc

FirstName / LastName / Initials

Guids

Month / Day names

Examples of things that should be case sensitive

Passwords

答:
Sorry for the trivial answer, but that's just the way it is :)

At a basic level, strings are represented as a list of characters, where 'a' is different from 'A', so it's probably the easiest representation \ convention overall. In your case, it's probably fair to say that the majority of comparisons is case-insensitive, but I think the other side of the argument holds true at least as much and a convention has been adopted.

I'd imagine utilizing some helper methods \ classes would ease your pain somewhat.

ContentLicense: CC BY-SA 2.5

Body:
Most times I want to do string comparisons I want them to be case insensitive.

So why are string in .net case sensitive by default?

EDIT 1: To be clear I think the below should return true by default. Or at least allow me to have a compile time flag that makes it so.

"John Smith" == "JOHN SMITH"

EDIT 2: I can think of many more examples of things that should be case insensitive

Examples of things that should be case insensitive

Usernames

Urls

File extensions / File names / Directory names / Paths

Machine / servernames

State / Country / Location etc

FirstName / LastName / Initials

Guids

Month / Day names

Examples of things that should be case sensitive

Passwords


问:
In angular-cli, how does the "lazy" attribute work to load global libraries?
By adding them to the scripts property of .angular-cli file, one can load global scripts into your app. This example comes from the documentation:

```<code>"scripts": [
  "global-script.js",
  { "input": "lazy-script.js", "lazy": true },
  { "input": "pre-rename-script.js", "output": "renamed-script" },
]
</code>```

I am however a bit confused by the "lazy" attribute. When building your app, the to-be-lazy-loaded script is no longer packaged in the scripts.bundle.js file.

But how will the library then be loaded after all? What do I have to do to load the file when necessary?

答:
If you configure the "lazy" attribute in the .angular-cli.json to load global libraries, you need to "lazy load" the script when needed.  Here is the steps to setup.

1.Configure .angular-cli.json in the apps[0].scripts array.

```<code>"scripts": [
    { "input": "../node_modules/jquery/dist/jquery.js", "output": "jquery", "lazy": true }
],
</code>```

You'll get an jquery.bundle.js file in the build output.

2.Load the generated script by appending

Body:
By adding them to the scripts property of .angular-cli file, one can load global scripts into your app. This example comes from the documentation:

"scripts": [
  "global-script.js",
  { "input": "lazy-script.js", "lazy": true },
  { "input": "pre-rename-script.js", "output": "renamed-script" },
]

I am however a bit confused by the "lazy" attribute. When building your app, the to-be-lazy-loaded script is no longer packaged in the scripts.bundle.js file.

But how will the library then be loaded after all? What do I have to do to load the file when necessary?

Body:
If you configure the "lazy" attribute in the .angular-cli.json to load global libraries, you need to "lazy load" the script when needed.  Here is the steps to setup.

1.Configure .angular-cli.json in the apps[0].scripts array.

"scripts": [
    { "input": "../node_modules/jquery/dist/jquery.js", "output": "jquery", "lazy": true }
],

You'll get an jquery.bundle.js file in the build output.

2.Load the generated script by appending <script> tag in the DOM (<head>) lazily.

const script = document.createElement('script');
script.src = 'jquery.bundle.js';
script.type = 'text/javascript';
script.async = true;
script.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(script);


问:
What purpose does the Challenge Token really serve in Vtiger Web Services?
I am calling VTiger (6.4) webservices from a multi-threaded Java application. Each time I need to call a web service, I start with getting a Challenge Token from VT, then Login and finally perform my Query.

In reviewing the VT Web Services code, it seems that the above is not "thread safe" since the token obtained by one thread will be overwritten in VT's database by the token obtained in the second thread. If the Java application happened to reverse the execution order of threads when the VT Login web service is called one of those calls would fail as having in incorrect token.

I realize that I could cache the token within my app...but that means implementing mutex locking of shared storage, etc.

So, my question is: Does the Challenge Token really add much security to VTiger's web services? Or, could it be bypassed?

答:
The token prevents your session from being stolen. An alternative to that token would be using your accessKey in every call, but Vtiger Webservices were not built that way.

It certainly can be bypassed if you modify the authentication code in vtiger's base code. At least you would need to modify two files

```<code>vtiger_root/include/Webservices/AuthToken.php
</code>```

and

```<code>vtiger_root/include/Webservices/Login.php
</code>```

I think you should share a single token across threads. Maybe use a singleton to implement the session establishment.

Body:
The token prevents your session from being stolen. An alternative to that token would be using your accessKey in every call, but Vtiger Webservices were not built that way.

It certainly can be bypassed if you modify the authentication code in vtiger's base code. At least you would need to modify two files

vtiger_root/include/Webservices/AuthToken.php

and

vtiger_root/include/Webservices/Login.php

I think you should share a single token across threads. Maybe use a singleton to implement the session establishment.


问:
How to use Azure Automation to start and stop the Service Fabric Nodes?
In our project, we want to use Azure Automation to start and stop Service Fabric Cluster nodes.
At first, we use the:

```<code>Enable-ServiceFabricNode -NodeName "Node1"
Disable-ServiceFabricNode -NodeName "Node1"
</code>```

To start and stop the Nodes, it works in my Windows Powershell Script, but when we add it to the Azure Automation Script, it show
 “The term ‘Enable-ServiceFabricNode’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name … ”

Then, we try to use the Azure Resources Manager to get the scale set VM, then start and stop the VM:

```<code>$Cred = Get-AutomationPSCredential -Name '***@***.com';
Add-AzureRmAccount -Credential $Cred
Set-AzureRmContext -TenantId ‘000000-786D-4361-A787-2C398163274F’

InlineScript
{
    Stop-AzureRmVmss -ResourceGroupName "testRG" -VMScaleSetName "Test"
}
</code>```

Also it works in my windows powershell script, but we try to add it to Azure Automation, it shows:
“The term ‘Stop-AzureRmVmss’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name … ”

The Azure Automation is use the Azure Powershell Script, right?

So is there any way that we can use the Azure Automation Script to Start and Stop the Service Fabric Cluster nodes?

Thanks so much!

答: You most likely don't have the latest Azure Modules. You can get the latest modules by following these steps -> https://learn.microsoft.com/en-us/azure/automation/automation-update-azure-modules</p>

Body:
In our project, we want to use Azure Automation to start and stop Service Fabric Cluster nodes.
At first, we use the:

Enable-ServiceFabricNode -NodeName "Node1"
Disable-ServiceFabricNode -NodeName "Node1"

To start and stop the Nodes, it works in my Windows Powershell Script, but when we add it to the Azure Automation Script, it show
 “The term ‘Enable-ServiceFabricNode’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name … ”

Then, we try to use the Azure Resources Manager to get the scale set VM, then start and stop the VM:

$Cred = Get-AutomationPSCredential -Name '***@***.com';
Add-AzureRmAccount -Credential $Cred
Set-AzureRmContext -TenantId ‘000000-786D-4361-A787-2C398163274F’

InlineScript
{
    Stop-AzureRmVmss -ResourceGroupName "testRG" -VMScaleSetName "Test"
}

Also it works in my windows powershell script, but we try to add it to Azure Automation, it shows:
“The term ‘Stop-AzureRmVmss’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name … ”

The Azure Automation is use the Azure Powershell Script, right?

So is there any way that we can use the Azure Automation Script to Start and Stop the Service Fabric Cluster nodes?

Thanks so much!


答:
The response from the request is an array of json objects and you are just trying to write the return object over and over again. You need to iterate over the returned data and output each object's value. Change your showdata function as:</p>

```<code>function showdata(data){

        for (i = 0; i < 3; i++) {

            document.write(data[i].song);
            document.write("<br>");

        }
    }
</code>```

Body:
The response from the request is an array of json objects and you are just trying to write the return object over and over again. You need to iterate over the returned data and output each object's value. Change your showdata function as:

function showdata(data){

        for (i = 0; i < 3; i++) {

            document.write(data[i].song);
            document.write("<br>");

        }
    }


问:
R: how to use table to tabulate m x n data
```<code>mydat = data.frame(Q1 = c(0, 1, 0, 1), Q2 = c(0, 1, 1, 1),
                   Q3 = c(1, 1, 1, 1), Gender = c("M", "M", "F", "F"))
> mydat
  Q1 Q2 Q3 Gender
1  0  0  1      M
2  1  1  1      M
3  0  1  1      F
4  1  1  1      F

> table(mydat[,1:3], mydat$Gender)

Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?
</code>```

I have a very simple data set with 3 binary questions and a gender variable. I'm interested to see if there is any association between the 3 questions and gender, so I would like to tabulate my data into a 3 (questions) x 2 (gender) count table. I want my table to look something like this

```<code>      Q1    Q2    Q3
M      1     1     2
F      1     2     2
</code>```

Edit:

```<code>mydat = data.frame(Q1 = c(0, 1, NA, 1), Q2 = c(0, 1, 1, 1),
                   Q3 = c(1, NA, 1, 1), Gender = c("M", "M", "F", "F"))

> rowsum(mydat[1:3], mydat$Gender)
  Q1 Q2 Q3
F NA  2  2
M  1  1 NA
</code>```

答:
We can do a group by operation and sum the elements of other columns

```<code>library(dplyr)
mydat %>%
   group_by(Gender) %>%
   summarise_all(funs(sum(., na.rm = TRUE)))
# A tibble: 2 x 4
#   Gender    Q1    Q2    Q3
#   <fctr> <int> <int> <int>
#1      F     1     2     2
#2      M     1     1     2
</code>```

Or using base R

```<code>rowsum(mydat[-4], mydat$Gender, na.rm = TRUE)
#   Q1 Q2 Q3
#F  1  2  2
#M  1  1  2
</code>```

Body:
mydat = data.frame(Q1 = c(0, 1, 0, 1), Q2 = c(0, 1, 1, 1),
                   Q3 = c(1, 1, 1, 1), Gender = c("M", "M", "F", "F"))
> mydat
  Q1 Q2 Q3 Gender
1  0  0  1      M
2  1  1  1      M
3  0  1  1      F
4  1  1  1      F

> table(mydat[,1:3], mydat$Gender)

Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?

I have a very simple data set with 3 binary questions and a gender variable. I'm interested to see if there is any association between the 3 questions and gender, so I would like to tabulate my data into a 3 (questions) x 2 (gender) count table. I want my table to look something like this

      Q1    Q2    Q3
M      1     1     2
F      1     2     2

Edit:

mydat = data.frame(Q1 = c(0, 1, NA, 1), Q2 = c(0, 1, 1, 1),
                   Q3 = c(1, NA, 1, 1), Gender = c("M", "M", "F", "F"))

> rowsum(mydat[1:3], mydat$Gender)
  Q1 Q2 Q3
F NA  2  2
M  1  1 NA

Body:
We can do a group by operation and sum the elements of other columns

library(dplyr)
mydat %>%
   group_by(Gender) %>%
   summarise_all(funs(sum(., na.rm = TRUE)))
# A tibble: 2 x 4
#   Gender    Q1    Q2    Q3
#   <fctr> <int> <int> <int>
#1      F     1     2     2
#2      M     1     1     2

Or using base R

rowsum(mydat[-4], mydat$Gender, na.rm = TRUE)
#   Q1 Q2 Q3
#F  1  2  2
#M  1  1  2


答:
In VB.NET it's possible to set the "option compare" to text to work case-insensitively but I highly discourage it.  My favorite is just to use the string.toLower() method when I need to compare insensitively and read the lower case version of the text.

Why?  Because how else would you compare when case sensitivity matters as it would in some applications?

Title: Why are string in .net case sensitive by default?


问:
How to create or convert text to audio at chromium browser?
While trying to determine a solution to How to use Web Speech API at chromium? found that

```<code>var voices = window.speechSynthesis.getVoices();
</code>```

returns an empty array for voices identifier.

Not certain if lack of support at chromium browser is related to this issue Not OK, Google: Chromium voice extension pulled after spying concerns?

Questions:

1) Are there any workarounds which can implement the requirement of creating or converting audio from text at chromium browser?

2) How can we, the developer community, create an open source database of audio files reflecting both common and uncommon words; served with appropriate CORS headers?

答:
There are several possible workarounds that have found which provide the ability to create audio from text; two of which require requesting an external resource, the other uses meSpeak.js by @masswerk.

Using approach described at Download the Audio Pronunciation of Words from Google, which suffers from not being able to pre-determine which words actually exist as a file at the resource without writing a shell script or performing a HEAD request to check if a network error occurs. For example, the word "do" is not available at the resource used below.

window.addEventListener("load", () => {

  const textarea = document.querySelector("textarea");

  const audio = document.createElement("audio");

  const mimecodec = "audio/webm; codecs=opus";

  audio.controls = "controls";

  document.body.appendChild(audio);

  audio.addEventListener("canplay", e => {
    audio.play();
  });

  let words = textarea.value.trim().match(/\w+/g);

  const url = "https://ssl.gstatic.com/dictionary/static/sounds/de/0/";

  const mediatype = ".mp3";

  Promise.all(
    words.map(word =>
      fetch(`https://query.yahooapis.com/v1/public/yql?q=select * from data.uri where url="${url}${word}${mediatype}"&format=json&callback=`)
      .then(response => response.json())
      .then(({query: {results: {url}}}) =>
        fetch(url).then(response => response.blob())
        .then(blob => blob)
      )
    )
  )
  .then(blobs => {
    // const a = document.createElement("a");
    audio.src = URL.createObjectURL(new Blob(blobs, {
                  type: mimecodec
                }));
    // a.download = words.join("-") + ".webm";
    // a.click()
  })
  .catch(err => console.log(err));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea>what it does my ninja?</textarea></code>```

Resources at Wikimedia Commons Category:Public domain are not necessary served from same directory, see How to retrieve Wiktionary word content?, wikionary API - meaning of words.

If the precise location of the resource is known, the audio can be requested, though the URL may include prefixes other than the word itself.

fetch("https://upload.wikimedia.org/wikipedia/commons/c/c5/En-uk-hello-1.ogg")
.then(response => response.blob())
.then(blob => new Audio(URL.createObjectURL(blob)).play());```
</div>
</div>
</p>

<p>Not entirely sure how to use the Wikipedia API, How to get Wikipedia content using Wikipedia's API?, Is there a clean wikipedia API just for retrieve content summary? to get only the audio file. The <code>JSON</code> response would need to be parsed for text ending in <code>.ogg</code>, then a second request would need to be made for the resource itself.</p>

```fetch("https://en.wiktionary.org/w/api.php?action=parse&format=json&prop=text&callback=?&page=hello")
.then(response => response.text())
.then(data => {
  new Audio(location.protocol + data.match(/\/\/upload\.wikimedia\.org\/wikipedia\/commons\/[\d-/]+[\w-]+\.ogg/).pop()).play()
})
// "//upload.wikimedia.org/wikipedia/commons/5/52/En-us-hello.ogg\"
```

<p>which logs</p>

```Fetch API cannot load https://en.wiktionary.org/w/api.php?action=parse&format=json&prop=text&callback=?&page=hello. No 'Access-Control-Allow-Origin' header is present on the requested resource
```

<p>when not requested from same origin. We would need to try to use <code>YQL</code> again, though not certain how to formulate the query to avoid errors.</p>

<p>The third approach uses a slightly modified version of <code>meSpeak.js</code> to generate the audio without making an external request. The modification was to create a proper callback for <code>.loadConfig()</code> method</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>fetch("https://gist.githubusercontent.com/guest271314/f48ee0658bc9b948766c67126ba9104c/raw/958dd72d317a6087df6b7297d4fee91173e0844d/mespeak.js")
  .then(response => response.text())
  .then(text => {
    const script = document.createElement("script");
    script.textContent = text;
    document.body.appendChild(script);

    return Promise.all([
      new Promise(resolve => {
        meSpeak.loadConfig("https://gist.githubusercontent.com/guest271314/8421b50dfa0e5e7e5012da132567776a/raw/501fece4fd1fbb4e73f3f0dc133b64be86dae068/mespeak_config.json", resolve)
      }),
      new Promise(resolve => {
        meSpeak.loadVoice("https://gist.githubusercontent.com/guest271314/fa0650d0e0159ac96b21beaf60766bcc/raw/82414d646a7a7ef11bb04ddffe4091f78ef121d3/en.json", resolve)
      })
    ])
  })
  .then(() => {
    // takes approximately 14 seconds to get here
    console.log(meSpeak.isConfigLoaded());
    meSpeak.speak("what it do my ninja", {
      amplitude: 100,
      pitch: 5,
      speed: 150,
      wordgap: 1,
      variant: "m7"
    });
})
.catch(err => console.log(err));</code>```

one caveat of the above approach being that it takes approximately 14 and a half seconds for the three files to load before the audio is played back. However, avoids external requests.

It would be a positive to either or both 1) create a FOSS, developer maintained database or directory of sounds for both common and uncommon words; 2) perform further development of meSpeak.js to reduce load time of the three necessary files; and use Promise based approaches to provide notifications of the progress of of the loading of the files and readiness of the application.

In this users' estimation, it would be a useful resource if developers themselves created and contributed to an online database of files which responded with an audio file of the specific word. Not entirely sure if github is the appropriate venue to host audio files? Will have to consider the possible options if interest in such a project is shown.

Body:
While trying to determine a solution to How to use Web Speech API at chromium? found that

var voices = window.speechSynthesis.getVoices();

returns an empty array for voices identifier.

Not certain if lack of support at chromium browser is related to this issue Not OK, Google: Chromium voice extension pulled after spying concerns?

Questions:

1) Are there any workarounds which can implement the requirement of creating or converting audio from text at chromium browser?

2) How can we, the developer community, create an open source database of audio files reflecting both common and uncommon words; served with appropriate CORS headers?

Body:
There are several possible workarounds that have found which provide the ability to create audio from text; two of which require requesting an external resource, the other uses meSpeak.js by @masswerk.

Using approach described at Download the Audio Pronunciation of Words from Google, which suffers from not being able to pre-determine which words actually exist as a file at the resource without writing a shell script or performing a HEAD request to check if a network error occurs. For example, the word "do" is not available at the resource used below.

window.addEventListener("load", () => {

  const textarea = document.querySelector("textarea");

  const audio = document.createElement("audio");

  const mimecodec = "audio/webm; codecs=opus";

  audio.controls = "controls";

  document.body.appendChild(audio);

  audio.addEventListener("canplay", e => {
    audio.play();
  });

  let words = textarea.value.trim().match(/\w+/g);

  const url = "https://ssl.gstatic.com/dictionary/static/sounds/de/0/";

  const mediatype = ".mp3";

  Promise.all(
    words.map(word =>
      fetch(`https://query.yahooapis.com/v1/public/yql?q=select * from data.uri where url="${url}${word}${mediatype}"&format=json&callback=`)
      .then(response => response.json())
      .then(({query: {results: {url}}}) =>
        fetch(url).then(response => response.blob())
        .then(blob => blob)
      )
    )
  )
  .then(blobs => {
    // const a = document.createElement("a");
    audio.src = URL.createObjectURL(new Blob(blobs, {
                  type: mimecodec
                }));
    // a.download = words.join("-") + ".webm";
    // a.click()
  })
  .catch(err => console.log(err));
});

<textarea>what it does my ninja?</textarea>

Resources at Wikimedia Commons Category:Public domain are not necessary served from same directory, see How to retrieve Wiktionary word content?, wikionary API - meaning of words.

If the precise location of the resource is known, the audio can be requested, though the URL may include prefixes other than the word itself.

fetch("https://upload.wikimedia.org/wikipedia/commons/c/c5/En-uk-hello-1.ogg")
.then(response => response.blob())
.then(blob => new Audio(URL.createObjectURL(blob)).play());

Not entirely sure how to use the Wikipedia API, How to get Wikipedia content using Wikipedia's API?, Is there a clean wikipedia API just for retrieve content summary? to get only the audio file. The JSON response would need to be parsed for text ending in .ogg, then a second request would need to be made for the resource itself.

fetch("https://en.wiktionary.org/w/api.php?action=parse&format=json&prop=text&callback=?&page=hello")
.then(response => response.text())
.then(data => {
  new Audio(location.protocol + data.match(/\/\/upload\.wikimedia\.org\/wikipedia\/commons\/[\d-/]+[\w-]+\.ogg/).pop()).play()
})
// "//upload.wikimedia.org/wikipedia/commons/5/52/En-us-hello.ogg\"

which logs

Fetch API cannot load https://en.wiktionary.org/w/api.php?action=parse&format=json&prop=text&callback=?&page=hello. No 'Access-Control-Allow-Origin' header is present on the requested resource

when not requested from same origin. We would need to try to use YQL again, though not certain how to formulate the query to avoid errors.

The third approach uses a slightly modified version of meSpeak.js to generate the audio without making an external request. The modification was to create a proper callback for .loadConfig() method

fetch("https://gist.githubusercontent.com/guest271314/f48ee0658bc9b948766c67126ba9104c/raw/958dd72d317a6087df6b7297d4fee91173e0844d/mespeak.js")
  .then(response => response.text())
  .then(text => {
    const script = document.createElement("script");
    script.textContent = text;
    document.body.appendChild(script);

    return Promise.all([
      new Promise(resolve => {
        meSpeak.loadConfig("https://gist.githubusercontent.com/guest271314/8421b50dfa0e5e7e5012da132567776a/raw/501fece4fd1fbb4e73f3f0dc133b64be86dae068/mespeak_config.json", resolve)
      }),
      new Promise(resolve => {
        meSpeak.loadVoice("https://gist.githubusercontent.com/guest271314/fa0650d0e0159ac96b21beaf60766bcc/raw/82414d646a7a7ef11bb04ddffe4091f78ef121d3/en.json", resolve)
      })
    ])
  })
  .then(() => {
    // takes approximately 14 seconds to get here
    console.log(meSpeak.isConfigLoaded());
    meSpeak.speak("what it do my ninja", {
      amplitude: 100,
      pitch: 5,
      speed: 150,
      wordgap: 1,
      variant: "m7"
    });
})
.catch(err => console.log(err));

one caveat of the above approach being that it takes approximately 14 and a half seconds for the three files to load before the audio is played back. However, avoids external requests.

It would be a positive to either or both 1) create a FOSS, developer maintained database or directory of sounds for both common and uncommon words; 2) perform further development of meSpeak.js to reduce load time of the three necessary files; and use Promise based approaches to provide notifications of the progress of of the loading of the files and readiness of the application.

In this users' estimation, it would be a useful resource if developers themselves created and contributed to an online database of files which responded with an audio file of the specific word. Not entirely sure if github is the appropriate venue to host audio files? Will have to consider the possible options if interest in such a project is shown.


问:
CPLEX dvar as condition
I have this problem while trying to find a solution for a resource constraint scheduling problem. Whenever I put dvar as a condition in a forall loop or if condition I have the error that states "Decision variable (or expression) "S" not allowed". </p>

```<code>range activity = 1..16;
dvar float+ S[activity];

dvar float+ rd[jobs];

forall (i in activity)
 forall (t in T:S[i]<=t<=S[i]+D[i]) //boolean b
        b[i][t]==1;

forall (t in T)
  forall (k in R)
    sum (i in activity)b[i][t]*V[i][k]<=Rk[k];//human resources constraint

  forall (j in jobs)
  forall (t in T:rd[j]<=t<=S[maxact[j]])//boolean y
  y[j][t]==1;
</code>```

答:
This will work:</p>
```<code>range activity = 1..16;
dvar float+ S[activity];
range jobs=1..3;
range T=1..3;
range R=1..4;
dvar boolean b[activity][T];
dvar boolean y[jobs][T];
int D[activity];
int Rk[R]; int V[activity][R]; int maxact[j in jobs]=1;

dvar float+ rd[jobs];

subject to {
 forall (i in activity)
  forall (t in T) //boolean b
     ((S[i]<=t) &&(t<=S[i]+D[i])) => (b[i][t]==1);

 forall (t in T)   forall (k in R)
  sum (i in activity)b[i][t]*V[i][k]<=Rk[k];//human resources constraint

   forall (j in jobs)   forall (t in T)//boolean y
 ((rd[j]<=t) &&
 (t<=S[maxact[j]])) =>  (y[j][t]==1);
}
</code>```

Title: CPLEX dvar as condition

Body:
I have this problem while trying to find a solution for a resource constraint scheduling problem. Whenever I put dvar as a condition in a forall loop or if condition I have the error that states "Decision variable (or expression) "S" not allowed".

range activity = 1..16;
dvar float+ S[activity];

dvar float+ rd[jobs];

forall (i in activity)
 forall (t in T:S[i]<=t<=S[i]+D[i]) //boolean b
        b[i][t]==1;

forall (t in T)
  forall (k in R)
    sum (i in activity)b[i][t]*V[i][k]<=Rk[k];//human resources constraint

  forall (j in jobs)
  forall (t in T:rd[j]<=t<=S[maxact[j]])//boolean y
  y[j][t]==1;

Body:
This will work:

range activity = 1..16;
dvar float+ S[activity];
range jobs=1..3;
range T=1..3;
range R=1..4;
dvar boolean b[activity][T];
dvar boolean y[jobs][T];
int D[activity];
int Rk[R]; int V[activity][R]; int maxact[j in jobs]=1;

dvar float+ rd[jobs];

subject to {
 forall (i in activity)
  forall (t in T) //boolean b
     ((S[i]<=t) &&(t<=S[i]+D[i])) => (b[i][t]==1);

 forall (t in T)   forall (k in R)
  sum (i in activity)b[i][t]*V[i][k]<=Rk[k];//human resources constraint

   forall (j in jobs)   forall (t in T)//boolean y
 ((rd[j]<=t) &&
 (t<=S[maxact[j]])) =>  (y[j][t]==1);
}

ContentLicense: CC BY-SA 4.0


问:
Spring @Bean will it be autowired if the class auto scanned
I read about the component scan and as I understood that configuration classes are auto-scanned. my question if I have the following:

```<code>@Configuration
public class AppConfig {
@Bean(name="authenticationService")
    public AuthenticationService getAuthenticationService(){
        return new AuthenticationService();
    }
}
</code>```

if the @Configuration is already scanned (so the app config will be available ), wouldn't be the bean inside it created? I'm little confused as they say the @Bean is not auto scanned

答:
No. Spring won't scan @Bean methods.

Here, you are creating the bean of AuthenticationService just like in any other java program using new keyword.

It is same as AuthenticationService authenticationService = new AuthenticationService();

If you want spring to create a bean of AuthenticationService in AppConfig class, use @Autowired annotation

```<code>@Autowired
private AuthenticationService authenticationService;
</code>```

Hope this helps!

EDIT :

@M.Deinum corrected me that spring doesn't create beans based on @Autowired annotation. Beans are created automatically by spring if their classes are annotated with @Component/ @Configuration / @Service annotations.

@M.Deinum, Thank you.

Body:
I read about the component scan and as I understood that configuration classes are auto-scanned. my question if I have the following:

@Configuration
public class AppConfig {
@Bean(name="authenticationService")
    public AuthenticationService getAuthenticationService(){
        return new AuthenticationService();
    }
}

if the @Configuration is already scanned (so the app config will be available ), wouldn't be the bean inside it created? I'm little confused as they say the @Bean is not auto scanned

Body:
No. Spring won't scan @Bean methods.

Here, you are creating the bean of AuthenticationService just like in any other java program using new keyword.

It is same as AuthenticationService authenticationService = new AuthenticationService();

If you want spring to create a bean of AuthenticationService in AppConfig class, use @Autowired annotation

@Autowired
private AuthenticationService authenticationService;

Hope this helps!

EDIT :

@M.Deinum corrected me that spring doesn't create beans based on @Autowired annotation. Beans are created automatically by spring if their classes are annotated with @Component/ @Configuration / @Service annotations.

@M.Deinum, Thank you.


问:
Is Method local variable will garbage collected if stored in static storage?
I am creating a client class, which will connect to different type of database. Following is the code snippet what I am trying to do.

```<code>public class Client{
    private static Map<ApplicationTypeEnum, Connection> connectionPool = new HashMap<>();

    public void init() throws Exception {

        try {
           Connection con1 = getConnection(someparams...);
           connectionPool.put("app-1",con1)
           Connection con2 = getConnection(someparams...);
           connectionPool.put("app-2",con2)
        } catch (Exception pe) {
            throw pe;
        }
    }
}
</code>```

Now the Connection object are local to init, so is there any chance that the Connectionobjects will be garbage collected when control is out of init method.

答: No. Because you have stored the references in the static connectionPool they are still reachable, and are not eligible for garbage collection.

Body:
I am creating a client class, which will connect to different type of database. Following is the code snippet what I am trying to do.

public class Client{
    private static Map<ApplicationTypeEnum, Connection> connectionPool = new HashMap<>();

    public void init() throws Exception {

        try {
           Connection con1 = getConnection(someparams...);
           connectionPool.put("app-1",con1)
           Connection con2 = getConnection(someparams...);
           connectionPool.put("app-2",con2)
        } catch (Exception pe) {
            throw pe;
        }
    }
}

Now the Connection object are local to init, so is there any chance that the Connectionobjects will be garbage collected when control is out of init method.


问:
Uncaught ReferenceError: writeHTML is not defined
Sorry my English, I am of another nationality

I have a code in js but unfortunately it does not work because of this warning
How to fix it and make it work, thank you

You're right, excuse me, here's the full code, i included this script in phpBB 3.1

These are the affected files

1) overall_footer_after.html

2) overall_header_page_body_before.html

3) scrollamp.js

1) In overall_footer_after.html and loaded the scrollamp.js file this way

```<code><!-- INCLUDEJS scrollamp.js -->
</code>```

2) This is the code I put in the file: overall_header_page_body_before.html

```<code><div class="forabg">
    <div class="inner">
        <ul class="topiclist">
            <li class="header"><dl><dt>News</dt></dl></li>
        </ul>
            <div class="postbody" style="width: 100%">
                <div class="post bg2">
<div class="avviso" style="padding: 0px; width: 400px; height: 200px; margin: 0 auto 0 auto;text-align:center; border: #00ffff 0px solid;">
<script type="text/javascript">
innerHTML()
</script>
</div>
                    </div>
                </div>
            </div>
    </div>
</code>```

3) And this is the code I put in the file scrollamp.js

```<code>function innerHTML() {
document.write("<marquee width\"400\" height\"200\" direction=\"Up\" scrollamount=\"1\" scrolldelay=\"1\">");
document.write("<p style=\"font-size:25px;font-weight: bold;color:red;text-align:center;text-decoration:underline blink;\">.:| AVVISO IMPORTANTE |:.<\/p>");
// document.write("<br\/>");
document.write("<p style=\"font-size:15px;font-weight: bold;color:#000;text-align:center;\">Tutti gli Utenti Registrati, dovranno effettuare almeno 5 messaggi per visualizzare tutto il forum<\/p>");
document.write("<\/marquee>");
}
</code>```

答:
I am trying to be nice so I will answer your question.
However, PLEASE DON'T EXPECT PEOPLE TO ANSWER SUCH AN AMBIGUOUS QUESTION.

You have not provided your full html code so no one can give any actual suggestion to you.

Here is what I suspect your problem might be:

Your javascript file is fine but you need to import it before using it.

```<code>ReferenceError: writeHTML is not defined
</code>```

This kind of error will only be thrown when, literally, the object has not yet been defined i.e. you have not imported it yet.

To import a script do this:

```<code><script src="fileName.js"></script>
</code>```

Thats all I could tell from the informations you have provided.

Body:
Sorry my English, I am of another nationality

I have a code in js but unfortunately it does not work because of this warning
How to fix it and make it work, thank you

You're right, excuse me, here's the full code, i included this script in phpBB 3.1

These are the affected files

1) overall_footer_after.html

2) overall_header_page_body_before.html

3) scrollamp.js

1) In overall_footer_after.html and loaded the scrollamp.js file this way

2) This is the code I put in the file: overall_header_page_body_before.html

News

3) And this is the code I put in the file scrollamp.js

function innerHTML() {
document.write("<marquee width\"400\" height\"200\" direction=\"Up\" scrollamount=\"1\" scrolldelay=\"1\">");
document.write("
.:| AVVISO IMPORTANTE |:.<\/p>");
// document.write("
");
document.write("
Tutti gli Utenti Registrati, dovranno effettuare almeno 5 messaggi per visualizzare tutto il forum<\/p>");
document.write("<\/marquee>");
}

Body:
I am trying to be nice so I will answer your question.
However, PLEASE DON'T EXPECT PEOPLE TO ANSWER SUCH AN AMBIGUOUS QUESTION.

You have not provided your full html code so no one can give any actual suggestion to you.

Here is what I suspect your problem might be:

Your javascript file is fine but you need to import it before using it.

ReferenceError: writeHTML is not defined

This kind of error will only be thrown when, literally, the object has not yet been defined i.e. you have not imported it yet.

To import a script do this:

<script src="fileName.js"></script>

Thats all I could tell from the informations you have provided.


问:
navbar-right does not work
Self-explanatory. Why does navbar-right not close out the two nav bar elements to the right? I have added the proper code so I am confused as to why it does not work.

```<code><nav class="navbar fixed-top navbar-toggleable-md navbar-inverse navbar-expanded" id="mainNav">
  <div class="container">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-="data-" toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
    <div class="collapse navbar-collapse" id="navbarResponsive">
      <ul class="nav navbar-nav navbar-left">
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#about">About</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#services">Products</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#pricing">Pricing</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#contact">Contact</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li class="nav-item">
          <a class="nav-link page-scroll" href="sign-up" style="background-color:blue; border-radius:5px">Sign Up</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="sign-in" style="background-color:blue; border-radius:5px">Log In</a></li>
      </ul>
    </div>
  </div>
</nav>
</code>```

答:
Is this what you want? add navbar-right to the parent of that two
 element and remove them from
:

nav {
  margin-top: 100px; /* ignore this, just to show example at stackoverflow*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<nav class="navbar fixed-top navbar-toggleable-md navbar-inverse navbar-expanded" id="mainNav">
  <div class="container">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">My Menu</button>
    <div class="collapse navbar-collapse navbar-right" id="navbarResponsive">
      <ul class="nav navbar-nav">
        <li class="nav-item">
          About</li>
        <li class="nav-item">
          Products</li>
        <li class="nav-item">
          Pricing</li>
        <li class="nav-item">
          Contact</li>
      </ul>
      <ul class="nav navbar-nav">
        <li class="nav-item">
          Sign Up</li>
        <li class="nav-item">
          Log In</li>
      </ul>
    </div>
  </div>
</nav></code>```

Title: navbar-right does not work

Body:
Self-explanatory. Why does navbar-right not close out the two nav bar elements to the right? I have added the proper code so I am confused as to why it does not work.

    <button class="navbar-toggler navbar-toggler-right" type="button" data-="data-" toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

          About

          Products

          Pricing

          Contact

          Sign Up

          Log In

Body:
Is this what you want? add navbar-right to the parent of that two <ul> element and remove them from <ul>:

<div class="collapse navbar-collapse navbar-right" id="navbarResponsive">

nav {
  margin-top: 100px; /* ignore this, just to show example at stackoverflow*/
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<nav class="navbar fixed-top navbar-toggleable-md navbar-inverse navbar-expanded" id="mainNav">
  <div class="container">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">My Menu</button>
    <div class="collapse navbar-collapse navbar-right" id="navbarResponsive">
      <ul class="nav navbar-nav">
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#about">About</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#services">Products</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#pricing">Pricing</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#contact">Contact</a></li>
      </ul>
      <ul class="nav navbar-nav">
        <li class="nav-item">
          <a class="nav-link page-scroll" href="sign-up" style="background-color:blue; border-radius:5px">Sign Up</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="sign-in" style="background-color:blue; border-radius:5px">Log In</a></li>
      </ul>
    </div>
  </div>
</nav>


问:
Tables: How to achieve “normal” td widths, but 100% table width?
On our site we have tables containing data. We like the column widths we get with a normal table, but we like the border-bottom of tds to stretch the entire width of the page like we get with CSS: table { width:100% }, as can be seen on a demo table widths page, which renders like this:

Is it possible to achieve the same column widths as with a normal (non-width-100%) table in a table where the border-bottom stretches the entire width?

And no, td { white-space: nowrap } in combination with an extra width: 100% td (see the link above) is not good, as sometimes the tds are long and so we want the tds to wrap exactly like in a normal table.

We need a solution that works in at least IE6-8 + FF.

Btw, is there a better way (tm) of showing HTML snippets than linking to an external page? I can show just source, but having HTML rendered too is very illustrative.

This was originally posted on Webmasters, but following a suggestion there, I now (re)post it here.

答:
I finally figured it out.

My first few attempts dealt with floating s and
s, but apparently I was on the right track but had the wrong element.

I think what you want to do is to float the
. The
 will still be 100% width, so it will stretch the whole width of the page, but the
 inside of it will act as a container for everything else, and floating it will release it from the shackles of the size of its
 container width.

The downside of this is that you won't be able to use
 or
 elements, because you will no longer have any way to align them with the
 content.

Try this out:

```<code>table {
  width: 100%;
  border: 1px #000 solid;
}

tbody {
  float: left;
}

td {
  border: 1px #000 solid;
}
</code>```

Body:
I finally figured it out.

My first few attempts dealt with floating <td>s and <tr>s, but apparently I was on the right track but had the wrong element.

I think what you want to do is to float the <tbody>. The <table> will still be 100% width, so it will stretch the whole width of the page, but the <tbody> inside of it will act as a container for everything else, and floating it will release it from the shackles of the size of its <table> container width.

The downside of this is that you won't be able to use <thead> or <tfoot> elements, because you will no longer have any way to align them with the <tbody> content.

Try this out:

table {
  width: 100%;
  border: 1px #000 solid;
}

tbody {
  float: left;
}

td {
  border: 1px #000 solid;
}


答: As long as any references exist pointing to these objects, they won't be garbage collected. In your case you have static variable connectionPool pointing to map, holding these objects. If you remove these objects from the above mentioned map or assign another map to connectionPool without these objects and will not have any other references to these objects, than yes, they will be collected.

Title: Is Method local variable will garbage collected if stored in static storage?


问:
pct_change method not working in pandas dataframe
Using below code I'm attempting to check the percent change of the numeric columns :

```<code>import pandas as pd

df = pd.read_csv('./data.txt')
df.pct_change(1)
</code>```

data.txt :

```<code>,AAPL,MSFT,^GSPC
2000-01-03,3.625643,39.33463,1455.219971
2000-01-04,3.319964,38.0059,1399.420044
2000-01-05,3.3685480000000005,38.406628000000005,1402.109985
2000-01-06,3.077039,37.12008,1403.449951
</code>```

But above code returns error :

```<code>/opt/conda/lib/python3.5/site-packages/pandas/core/ops.py in na_op(x, y)
   1187                 if np.prod(xrav.shape) and np.prod(yrav.shape):
   1188                     with np.errstate(all='ignore'):
-> 1189                         result[mask] = op(xrav, yrav)
   1190             elif hasattr(x, 'size'):
   1191                 result = np.empty(x.size, dtype=x.dtype)

TypeError: unsupported operand type(s) for /: 'str' and 'str'
</code>```

How to utilize the pct_change method? Remove the non numeric column (in this case the date column) re-run pct_change and then re-combine the data column ?

答:
The first column of dates are strings. df.pct_change(1) raises a TypeError when it tries to perform division on these strings.

One way to avoid the error is to make the dates the index when parsing the CSV:

```<code>import pandas as pd

df = pd.read_csv('./data.txt', index_col=[0])
print(df.pct_change(1))
</code>```

yields

```<code>                AAPL      MSFT     ^GSPC
2000-01-03       NaN       NaN       NaN
2000-01-04 -0.084310 -0.033780 -0.038345
2000-01-05  0.014634  0.010544  0.001922
2000-01-06 -0.086538 -0.033498  0.000956
</code>```

You might also want to parse the date strings as dates:

```<code>df = pd.read_csv('./data.txt', index_col=[0], parse_dates=[0])
</code>```

Then the index will be a DatetimeIndex instead of a plain Index (of strings).
This will allow you to do datetime arithmetic on the index, and interpolate values
based on time.

Body:
Using below code I'm attempting to check the percent change of the numeric columns :

import pandas as pd

df = pd.read_csv('./data.txt')
df.pct_change(1)

data.txt :

,AAPL,MSFT,^GSPC
2000-01-03,3.625643,39.33463,1455.219971
2000-01-04,3.319964,38.0059,1399.420044
2000-01-05,3.3685480000000005,38.406628000000005,1402.109985
2000-01-06,3.077039,37.12008,1403.449951

But above code returns error :

/opt/conda/lib/python3.5/site-packages/pandas/core/ops.py in na_op(x, y)
   1187                 if np.prod(xrav.shape) and np.prod(yrav.shape):
   1188                     with np.errstate(all='ignore'):
-> 1189                         result[mask] = op(xrav, yrav)
   1190             elif hasattr(x, 'size'):
   1191                 result = np.empty(x.size, dtype=x.dtype)

TypeError: unsupported operand type(s) for /: 'str' and 'str'

How to utilize the pct_change method? Remove the non numeric column (in this case the date column) re-run pct_change and then re-combine the data column ?

Body:
The first column of dates are strings. df.pct_change(1) raises a TypeError when it tries to perform division on these strings.

One way to avoid the error is to make the dates the index when parsing the CSV:

import pandas as pd

df = pd.read_csv('./data.txt', index_col=[0])
print(df.pct_change(1))

yields

                AAPL      MSFT     ^GSPC
2000-01-03       NaN       NaN       NaN
2000-01-04 -0.084310 -0.033780 -0.038345
2000-01-05  0.014634  0.010544  0.001922
2000-01-06 -0.086538 -0.033498  0.000956

You might also want to parse the date strings as dates:

df = pd.read_csv('./data.txt', index_col=[0], parse_dates=[0])

Then the index will be a DatetimeIndex instead of a plain Index (of strings).
This will allow you to do datetime arithmetic on the index, and interpolate values
based on time.