问:
How can I pause a C# Console application (only when being run by a user)
How can I pause a C# console application only while being run by a user?

I've searched similar issues on stack overflow which recommend learning to debug properly, using readline, etc, but none of them cover the instance where your process might be being run by an automated system that needs to continue straight past (i.e. not pause, to let user read screen).

How can I determine whether the console is being run interactively or by a script?

If this were bash on a linux system, I could do something like

https://www.gnu.org/software/bash/manual/html_node/Is-this-Shell-Interactive_003f.html

答:
Console.OpenStandardInput(1) will return Stream.Null if the console Application is not being ran interactively.

```<code>    private static void pause()
    {
        if (Console.OpenStandardInput(1) != Stream.Null)
        {
            Console.Out.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
    }
</code>```

Body:
Console.OpenStandardInput(1) will return Stream.Null if the console Application is not being ran interactively.

    private static void pause()
    {
        if (Console.OpenStandardInput(1) != Stream.Null)
        {
            Console.Out.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
    }


来源: stackexchange

问:
How to print the return value of a function using printf()?

Update:

The original code looked a lot like this:

```<code>// printf(printf(););

#include <string>

int main()
{
   printf(printf("Hello, WORLD!"););
}
</code>```

However, in the original post, printf("Hello, WORLD!") was assigned to a variable, x.

Intended questions:

How do I call the return value of a function within a function?  As a beginner, learning to reference a string variable using %s, I wondered how to reference a the return value of a function (for example, if the return value were a string, would I still use %s).

What does "called to print" mean?  I think a simplistic explanation is: the string is put into memory and assigned an address, and the class definition tells the compiler to look up the location in memory based on the class's input-argument definition; so, the address in memory is called to print by the compiler.

Is the first argument of printf() also the return value of printf() such that x == "Hello, World!" is true in x = printf("Hello, World!")?

Original post:

I'm looking at http://www.cplusplus.com/reference/cstdio/printf/

it says: int printf ( const char * format, ... );, but it doesn't define ....  So, I don't know what ... is referencing.  I wrongly assumed that meant ( const char * format, const char * format, const char * format, ~.  But in fact, I can't decipher the meaning based on guessing and reading.

Using this program:

```<code>#include <stdio.h>
int main(int argc, char ** argv)
{
    str x = printf("Hello, World!\n");
    printf("x has %d characters.\n", x);
    //"x has %d characters.\n" appears first, x appears second.

    return 0;
}
</code>```

We see the result:

```<code>Hello, World!
x has 14 characters.
</code>```

When I expected:

```<code>x has 14 characters.  //because this appears first.
Hello, World!         //because this appear second.
</code>```

Because x comes after x has 14 characters..

Someone please explain why ./a.out is giving me the results in backwards order (using gcc and shell in Ubuntu); furthermore, eclipse is shown to give the results in this same backward order.

Perhaps another way to rephrase the question would be: where is "Hello, World!\n" being called to print?

答:
Hello, World! appears first because you printed it first.

First (on line 4), you call printf as follows: printf("Hello, World!\n"). It prints Hello, World! and a line feed. You save the value returned by the call (14, the number of characters printed) in x.

Then (on line 5), you call printf as follows: printf("x has %d characters.\n", x). It prints x has 14 characters. and a line feed. The returned value is discarded.

Note that x has no characters; it has a number. Specifically, it has the number returned by the first call to printf, which is the number of characters it printed.

The following gives the output you desire:

```<code>const char* msg = "Hello, World!";
size_t len = strlen(msg);
printf("msg has %zu characters.\n", len);
printf("%s\n", msg);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Update:

The original code looked a lot like this:

// printf(printf(););

#include <string>

int main()
{
   printf(printf("Hello, WORLD!"););
}

However, in the original post, printf("Hello, WORLD!") was assigned to a variable, x.

Intended questions:

How do I call the return value of a function within a function?  As a beginner, learning to reference a string variable using %s, I wondered how to reference a the return value of a function (for example, if the return value were a string, would I still use %s).

What does "called to print" mean?  I think a simplistic explanation is: the string is put into memory and assigned an address, and the class definition tells the compiler to look up the location in memory based on the class's input-argument definition; so, the address in memory is called to print by the compiler.

Is the first argument of printf() also the return value of printf() such that x == "Hello, World!" is true in x = printf("Hello, World!")?

Original post:

I'm looking at http://www.cplusplus.com/reference/cstdio/printf/

it says: int printf ( const char * format, ... );, but it doesn't define ....  So, I don't know what ... is referencing.  I wrongly assumed that meant ( const char * format, const char * format, const char * format, ~.  But in fact, I can't decipher the meaning based on guessing and reading.

Using this program:

#include <stdio.h>
int main(int argc, char ** argv)
{
    str x = printf("Hello, World!\n");
    printf("x has %d characters.\n", x);
    //"x has %d characters.\n" appears first, x appears second.

    return 0;
}

We see the result:

Hello, World!
x has 14 characters.

When I expected:

x has 14 characters.  //because this appears first.
Hello, World!         //because this appear second.

Because x comes after x has 14 characters..

Someone please explain why ./a.out is giving me the results in backwards order (using gcc and shell in Ubuntu); furthermore, eclipse is shown to give the results in this same backward order.

Perhaps another way to rephrase the question would be: where is "Hello, World!\n" being called to print?

Body:
Hello, World! appears first because you printed it first.

First (on line 4), you call printf as follows: printf("Hello, World!\n"). It prints Hello, World! and a line feed. You save the value returned by the call (14, the number of characters printed) in x.

Then (on line 5), you call printf as follows: printf("x has %d characters.\n", x). It prints x has 14 characters. and a line feed. The returned value is discarded.

Note that x has no characters; it has a number. Specifically, it has the number returned by the first call to printf, which is the number of characters it printed.

The following gives the output you desire:

const char* msg = "Hello, World!";
size_t len = strlen(msg);
printf("msg has %zu characters.\n", len);
printf("%s\n", msg);

ContentLicense: CC BY-SA 3.0


问:
Result of the sum of random-ordered IEEE 754 double precision floats
Here is a pseudocode of my problem.

I have an array of IEEE 754 double precision positive numbers.

The array can come in a random order but numbers are always the same, just scrambled in their positions. Also these numbers can vary in a very wide range in the valid IEEE range of the double representation.

Once I have the list, I initialize a variable:

```<code>double sum_result = 0.0;
</code>```

And I accumulate the sum on sum_result, in a loop over the whole array. At each step I do:

```<code>sum_result += my_double_array[i]
</code>```

Is it guaranteed that, whatever the order of the initial array of double, if the numbers are the same, the printed out sum result will be always the same?

答:
Is it guaranteed that, whatever the order of the initial array of double, if the numbers are the same, the printed out sum result will be always the same?

No, FP addition is not associative.  Remember it is called floating point - the absolute precision "floats" about relative to 1.0.  Any given operation like addition (+) is subject to round-off error.

Yet if the sum is done and the inexact flag is clear, then yes, the order was not relevant.**

Simple counter example.

```<code>#include <math.h>
#include <float.h>
#include <fenv.h>
#include <stdio.h>

int main(void) {
  double a[3] = { DBL_MAX, -DBL_MAX, 1.0 };
  fexcept_t flag;

  feclearexcept(FE_ALL_EXCEPT);
  printf("%e\n", (a[0] + a[1]) + a[2]);
  fegetexceptflag(&flag, FE_INEXACT);
  printf("Inexact %d\n", !!(flag & FE_INEXACT));

  feclearexcept(FE_ALL_EXCEPT);
  printf("%e\n", a[0] + (a[1] + a[2]));
  fegetexceptflag(&flag, FE_INEXACT);
  printf("Inexact %d\n", !!(flag & FE_INEXACT));

  printf("%d\n", FLT_EVAL_METHOD);
  return (EXIT_SUCCESS);
}
</code>```

Output

```<code>1.000000e+00  // Sum is exact
Inexact 0

0.000000e+00  // Sum is inexact
Inexact 1

0    // evaluate all operations ... just to the range and precision of the type;
</code>```

Depending on FLT_EVAL_METHOD, FP math may use wider precession and range, yet the above extreme example sums will still differ.

**  aside from maybe a result of 0.0 vs -0.0

To see why, try a based 10 text example with 4 digits of precision.  The same principle applies to double with its usual 53 binary digits of precision.

```<code>a[3] = +1.000e99, -1.000e99, 1.000
sum = a[0] + a[1]   // sum now exactly 0.0
sum += a[2]         // sum now exactly 1.0
// vs.
sum = a[1] + a[2]   // sum now inexactly -1.000e99
sum += a[0]         // sum now inexactly 0.0
</code>```

Re: "printed out sum result will be always the same" : Unless code prints with "%a" or  "%.*e" with higher enough precision, the text printed may lack significance and two different sums may look the same.  See Printf width specifier to maintain precision of floating-point value

Body:
Here is a pseudocode of my problem.

I have an array of IEEE 754 double precision positive numbers.

The array can come in a random order but numbers are always the same, just scrambled in their positions. Also these numbers can vary in a very wide range in the valid IEEE range of the double representation.

Once I have the list, I initialize a variable:

double sum_result = 0.0;

And I accumulate the sum on sum_result, in a loop over the whole array. At each step I do:

sum_result += my_double_array[i]

Is it guaranteed that, whatever the order of the initial array of double, if the numbers are the same, the printed out sum result will be always the same?

Body:
Is it guaranteed that, whatever the order of the initial array of double, if the numbers are the same, the printed out sum result will be always the same?

No, FP addition is not associative.  Remember it is called floating point - the absolute precision "floats" about relative to 1.0.  Any given operation like addition (+) is subject to round-off error.

Yet if the sum is done and the inexact flag is clear, then yes, the order was not relevant.**

Simple counter example.

#include <math.h>
#include <float.h>
#include <fenv.h>
#include <stdio.h>

int main(void) {
  double a[3] = { DBL_MAX, -DBL_MAX, 1.0 };
  fexcept_t flag;

  feclearexcept(FE_ALL_EXCEPT);
  printf("%e\n", (a[0] + a[1]) + a[2]);
  fegetexceptflag(&flag, FE_INEXACT);
  printf("Inexact %d\n", !!(flag & FE_INEXACT));

  feclearexcept(FE_ALL_EXCEPT);
  printf("%e\n", a[0] + (a[1] + a[2]));
  fegetexceptflag(&flag, FE_INEXACT);
  printf("Inexact %d\n", !!(flag & FE_INEXACT));

  printf("%d\n", FLT_EVAL_METHOD);
  return (EXIT_SUCCESS);
}

Output

1.000000e+00  // Sum is exact
Inexact 0

0.000000e+00  // Sum is inexact
Inexact 1

0    // evaluate all operations ... just to the range and precision of the type;

Depending on FLT_EVAL_METHOD, FP math may use wider precession and range, yet the above extreme example sums will still differ.

**  aside from maybe a result of 0.0 vs -0.0

To see why, try a based 10 text example with 4 digits of precision.  The same principle applies to double with its usual 53 binary digits of precision.

a[3] = +1.000e99, -1.000e99, 1.000
sum = a[0] + a[1]   // sum now exactly 0.0
sum += a[2]         // sum now exactly 1.0
// vs.
sum = a[1] + a[2]   // sum now inexactly -1.000e99
sum += a[0]         // sum now inexactly 0.0

Re: "printed out sum result will be always the same" : Unless code prints with "%a" or  "%.*e" with higher enough precision, the text printed may lack significance and two different sums may look the same.  See Printf width specifier to maintain precision of floating-point value


问:
Printing Even and Odd using two Threads in Java
I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result.

This is mainly to print even and odd values in sequence.

```<code>public class PrintEvenOddTester {

    public static void main(String ... args){
        Printer print = new Printer(false);
        Thread t1 = new Thread(new TaskEvenOdd(print));
        Thread t2 = new Thread(new TaskEvenOdd(print));
        t1.start();
        t2.start();
    }

}

class TaskEvenOdd implements Runnable {

    int number=1;
    Printer print;

    TaskEvenOdd(Printer print){
        this.print = print;
    }

    @Override
    public void run() {

        System.out.println("Run method");
        while(number<10){

            if(number%2 == 0){
                System.out.println("Number is :"+ number);
                print.printEven(number);
                number+=2;
            }
            else {
                System.out.println("Number is :"+ number);
                print.printOdd(number);
                number+=2;
            }
        }

      }

    }

class Printer {

    boolean isOdd;

    Printer(boolean isOdd){
        this.isOdd = isOdd;
    }

    synchronized void printEven(int number) {

        while(isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:"+number);
        isOdd = true;
        notifyAll();
    }

    synchronized void printOdd(int number) {
        while(!isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:"+number);
        isOdd = false;
        notifyAll();
    }

}
</code>```

Can someone help me in fixing this?

EDIT
Expected result:
Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9

答:
Simple solution :)</p>

```<code>package com.code.threads;

public class PrintOddEven extends Thread {

    private Object lock;
    static volatile int count = 1;

    PrintOddEven(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run () {
        while(count <= 10) {
            if (count % 2 == 0) {
                synchronized(lock){
                    System.out.println("Even - " + count);
                    ++count;
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                synchronized(lock){
                    System.out.println("Odd - " + count);
                    ++count;
                    lock.notify();
                }
            }
        }
    }

    public static void main(String[] args) {
        Object obj = new Object();
        PrintOddEven even = new PrintOddEven(obj);
        PrintOddEven odd = new PrintOddEven(obj);

        even.start();
        odd.start();
    }
}
</code>```

Body:
I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result.

This is mainly to print even and odd values in sequence.

public class PrintEvenOddTester {

    public static void main(String ... args){
        Printer print = new Printer(false);
        Thread t1 = new Thread(new TaskEvenOdd(print));
        Thread t2 = new Thread(new TaskEvenOdd(print));
        t1.start();
        t2.start();
    }

}

class TaskEvenOdd implements Runnable {

    int number=1;
    Printer print;

    TaskEvenOdd(Printer print){
        this.print = print;
    }

    @Override
    public void run() {

        System.out.println("Run method");
        while(number<10){

            if(number%2 == 0){
                System.out.println("Number is :"+ number);
                print.printEven(number);
                number+=2;
            }
            else {
                System.out.println("Number is :"+ number);
                print.printOdd(number);
                number+=2;
            }
        }

      }

    }

class Printer {

    boolean isOdd;

    Printer(boolean isOdd){
        this.isOdd = isOdd;
    }

    synchronized void printEven(int number) {

        while(isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:"+number);
        isOdd = true;
        notifyAll();
    }

    synchronized void printOdd(int number) {
        while(!isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:"+number);
        isOdd = false;
        notifyAll();
    }

}

Can someone help me in fixing this?

EDIT
Expected result:
Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9

Body:
Simple solution :)

package com.code.threads;

public class PrintOddEven extends Thread {

    private Object lock;
    static volatile int count = 1;

    PrintOddEven(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run () {
        while(count <= 10) {
            if (count % 2 == 0) {
                synchronized(lock){
                    System.out.println("Even - " + count);
                    ++count;
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                synchronized(lock){
                    System.out.println("Odd - " + count);
                    ++count;
                    lock.notify();
                }
            }
        }
    }

    public static void main(String[] args) {
        Object obj = new Object();
        PrintOddEven even = new PrintOddEven(obj);
        PrintOddEven odd = new PrintOddEven(obj);

        even.start();
        odd.start();
    }
}


问:
Equivalent function to C's "_getch()" in Java?
I use Google Wave, and I want to emulate the ability to send messages before you actually hit the enter key.

Is there a Java equivalent to the C function _getch()?

答:
This will Do the trick but i works only from command line . Not from IDE </p>

```<code> Console c =System.console();
Reader r = c.reader();
try {
    num=    r.read();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
</code>```

Body:
This will Do the trick but i works only from command line . Not from IDE

 Console c =System.console();
Reader r = c.reader();
try {
    num=    r.read();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


问:
Iterate multiple Enumerations and return a value in Elixir
I have the following set of Enum's as key value pairs

```<code>list_of_vehicles = [{"Toyota" => "Corolla"},{"Honda"=> "Insight"}]
list_of_colors = [{"C01"=> "Green"},{"C02"=> "White"}]
list_of_capacity = [{"S01"=> "4"},{"S02"=> "2"}]
</code>```

I need to iterate through each list and generate a single string with all possibilities.

So far i have done following :

```<code>defp process_output(list_of_vehicles,list_of_colors,list_of_capacity)
    Enum.each(list_of_vehicles, fn{k,v}->
          final_output = "#{k}"
          if(Enum.any?(list_of_colors)) do
            Enum.each(list_of_colors, fn{k,v}->
              final_output = final_output<>"#{k}"
              if(Enum.any?(list_of_capacity)) do
                Enum.each(list_of_capacity, fn{k,v}->
                  final_output = final_output <>"#{k}"
                end)
              else
                final_output
              end
            end)
          else
            if(Enum.any?(list_of_capacity))do
              Enum.each(list_of_capacity, fn{k,v}->
                final_output = final_output<>"#{k}"
              end)
            else
              final_output
            end
          end
        end)
end
</code>```

I need to return this final output to another method.

```<code>list_of_outputs = process_output(vehicle_list,color_list_capacity_list)
</code>```

But could not find a way to generate the final output list

Desired O/P

```<code>["ToyotaC01S01","ToyotaC01S02","ToyotaC02S01","ToyotaC02S02",
 "HondaC01S01","HondaC01S02","HondaC02S01","HondaC02S02",...etc]
</code>```

答:
Scoping. Scoping matters in Elixir very much. One can not bind a variable inside a do block and expect it would be visible from outside. Your rebound final_output would be discarded as the scope of each is exited.

Redundancy.

if Enum.any?(list), do: Enum.each(...)
```

<p><code>if</code> here is redundant, since <code>Enum.each([])</code> is a noop.</p>

<p><strong>Elixir warnings.</strong> Read what Elixir says during the compilation process and follow advices. If the variable is unused, prepend it with an underscore.</p>

<p><strong>Control flow.</strong> In functional programming one mainly uses <code>map</code>-<code>reduce</code> rather than plain loops. As you might notice, there is neither <code>for</code> nor <code>while</code> loops available in Elixir. That is on purpose and one should not try to simulate their behavior with <code>Enum.each</code>. It won’t work.</p>

<p><strong>The summing up:</strong></p>

<pre class="lang-rb prettyprint-override"><code>list_of_vehicles = [{"Toyota", "Corolla"}, {"Honda", "Insight"}]
list_of_colors = [{"C01", "Green"}, {"C02", "White"}]
list_of_capacities = [{"S01", "4"}, {"S02", "2"}]

for {vehicle, _} <- list_of_vehicles,
    {color, _} <- list_of_colors,
    {capacity, _}  <- list_of_capacities,
do: vehicle <> color <> capacity

#⇒ ["ToyotaC01S01", "ToyotaC01S02", "ToyotaC02S01", "ToyotaC02S02",
#   "HondaC01S01", "HondaC01S02", "HondaC02S01", "HondaC02S02"]
</code>```

Here we use Kernel.SpecialForms.for/1 comprehension.

Please note, I have corrected the input to be Elixir-valid tuples.

Body:
I have the following set of Enum's as key value pairs

list_of_vehicles = [{"Toyota" => "Corolla"},{"Honda"=> "Insight"}]
list_of_colors = [{"C01"=> "Green"},{"C02"=> "White"}]
list_of_capacity = [{"S01"=> "4"},{"S02"=> "2"}]

I need to iterate through each list and generate a single string with all possibilities.

So far i have done following :

defp process_output(list_of_vehicles,list_of_colors,list_of_capacity)
    Enum.each(list_of_vehicles, fn{k,v}->
          final_output = "#{k}"
          if(Enum.any?(list_of_colors)) do
            Enum.each(list_of_colors, fn{k,v}->
              final_output = final_output<>"#{k}"
              if(Enum.any?(list_of_capacity)) do
                Enum.each(list_of_capacity, fn{k,v}->
                  final_output = final_output <>"#{k}"
                end)
              else
                final_output
              end
            end)
          else
            if(Enum.any?(list_of_capacity))do
              Enum.each(list_of_capacity, fn{k,v}->
                final_output = final_output<>"#{k}"
              end)
            else
              final_output
            end
          end
        end)
end

I need to return this final output to another method.

list_of_outputs = process_output(vehicle_list,color_list_capacity_list)

But could not find a way to generate the final output list

Desired O/P

["ToyotaC01S01","ToyotaC01S02","ToyotaC02S01","ToyotaC02S02",
 "HondaC01S01","HondaC01S02","HondaC02S01","HondaC02S02",...etc]

Body:
Scoping. Scoping matters in Elixir very much. One can not bind a variable inside a do block and expect it would be visible from outside. Your rebound final_output would be discarded as the scope of each is exited.

Redundancy.

if Enum.any?(list), do: Enum.each(...)

if here is redundant, since Enum.each([]) is a noop.

Elixir warnings. Read what Elixir says during the compilation process and follow advices. If the variable is unused, prepend it with an underscore.

Control flow. In functional programming one mainly uses map-reduce rather than plain loops. As you might notice, there is neither for nor while loops available in Elixir. That is on purpose and one should not try to simulate their behavior with Enum.each. It won’t work.

The summing up:

list_of_vehicles = [{"Toyota", "Corolla"}, {"Honda", "Insight"}]
list_of_colors = [{"C01", "Green"}, {"C02", "White"}]
list_of_capacities = [{"S01", "4"}, {"S02", "2"}]

for {vehicle, _} <- list_of_vehicles,
    {color, _} <- list_of_colors,
    {capacity, _}  <- list_of_capacities,
do: vehicle <> color <> capacity

#⇒ ["ToyotaC01S01", "ToyotaC01S02", "ToyotaC02S01", "ToyotaC02S02",
#   "HondaC01S01", "HondaC01S02", "HondaC02S01", "HondaC02S02"]

Here we use Kernel.SpecialForms.for/1 comprehension.

Please note, I have corrected the input to be Elixir-valid tuples.


问:
C# compiler bug, Returning a different value then expected, show correct in debugging but return wrong value
In my C# function I take the dynamic parameter. Look for ID property otherwise take postid property. In this code you can see it's showing 1567 value but it's returning 1614.

Am I missing something, or I am doing it some wrong way. please someone help.

```<code> public static string URL(dynamic post)
        {
            string link = "";
            int Id = 0;
            if (post?.link != null)
                link = post.link;
            else if (post?.Slug != null)
                link = post.Slug;
            if (post.ID != null)
                Id = post.ID;
            else if (post.postid != null)
                Id = Convert.ToInt32(post.postid);

            return '/' + Id + "-" + link + ".html";
        }
</code>```

答:
'/' is 47 decimal.
1567 + 47 = 1614. Try using "/" instead. (note double quotes)

Body:
In my C# function I take the dynamic parameter. Look for ID property otherwise take postid property. In this code you can see it's showing 1567 value but it's returning 1614.

Am I missing something, or I am doing it some wrong way. please someone help.

 public static string URL(dynamic post)
        {
            string link = "";
            int Id = 0;
            if (post?.link != null)
                link = post.link;
            else if (post?.Slug != null)
                link = post.Slug;
            if (post.ID != null)
                Id = post.ID;
            else if (post.postid != null)
                Id = Convert.ToInt32(post.postid);

            return '/' + Id + "-" + link + ".html";
        }


答:
You are trying to get the length of the string with printf but it also print's out the given string while returning printed characters length. It's not what you want.

You can use strlen instead of printf to get the length of a string without printing it to the output.

```<code>char *str = "Hello, World!\n";
int x = strlen(str);
printf("x has %d characters.\n", x);
printf(str);
return 0;
</code>```

Title: How to print the return value of a function using printf()?

Body:
You are trying to get the length of the string with printf but it also print's out the given string while returning printed characters length. It's not what you want.

You can use strlen instead of printf to get the length of a string without printing it to the output.

char *str = "Hello, World!\n";
int x = strlen(str);
printf("x has %d characters.\n", x);
printf(str);
return 0;


问:
Algorithm for detecting peaks from recorded, noisy data. Graphs inside
So I've recorded some data from an Android GPS, and I'm trying to find the peaks of these graphs, but I haven't been able to find anything specific, perhaps because I'm not too sure what I'm looking for.  I have found some MatLab functions, but I can't find the actual algorithms that do it.  I need to do this in Java, but I should be able to translate code from other languages.

As you can see, there are lots of 'mini-peaks', but I just want the main ones.

答: I've done some looking into peak detection and I can tell you that if your data doesn't behave, it could mess up your algorithm.  Off the top of my head, you could try: Pick a threshold, i.e threshold = 250.  If data is above threshold, find the max at that period.  This is assuming that the data you have has a mean about 230.  Not sure how fancy you want to get.  Hope that helps.</p>

ContentLicense: CC BY-SA 2.5


问:
How to Get Id in javascript?
How to Get id form this codein javascript/Jquery

```<code><div class="star-rating" id="star1">
 <span class="fa fa-star" data-rating="1"></span>
 <span class="fa fa-star" data-rating="2"></span>
 <span class="fa fa-star" data-rating="3"></span>
 <span class="fa fa-star" data-rating="4"></span>
 <span class="fa fa-star-o" data-rating="5"></span>
 <input name="whatever1" id="publicfeedbackvaluestar1"  class="rating-value"
  value="4" type="hidden">
 </div>
 <div class="star-rating" id="star2">
 <span class="fa fa-star" data-rating="1"></span>
 <span class="fa fa-star" data-rating="2"></span>
 <span class="fa fa-star" data-rating="3"></span>
 <span class="fa fa-star" data-rating="4"></span>
 <span class="fa fa-star-o" data-rating="5"></span>
 <input name="whatever2" id="publicfeedbackvaluestar2"  class="rating-value"
  value="4" type="hidden">
 </div>
 <div class="star-rating" id="star3">
 <span class="fa fa-star" data-rating="1"></span>
 <span class="fa fa-star" data-rating="2"></span>
 <span class="fa fa-star" data-rating="3"></span>
 <span class="fa fa-star" data-rating="4"></span>
 <span class="fa fa-star-o" data-rating="5"></span>
 <input name="whatever3" id="publicfeedbackvaluestar3"  class="rating-value"
  value="4" type="hidden">
 </div>
</code>```

How to store clicking rating value in text box ..
my jquery code

```<code>  $(".star-rating .fa").on('click', function() {
 id=$(this).attr("id");
 $('#publicfeedbackvalue'+id).val($(this).data('rating'));
 return SetRatingStar(id);
 });
</code>```

get id star3 How ?

Please Help me..

答:
You need to use id = $(this).parent().attr("id");

$(".star-rating .fa").on('click', function() {
  var id = $(this).parent().attr("id");
  var ratingClicked = $(this).data('rating');
  console.log('id: ' + id);
  console.log('rating: ' + ratingClicked);
});```
<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>
<div class="star-rating" id="star1">
  <span class="fa fa-star" data-rating="1">1</span>
  <span class="fa fa-star" data-rating="2">2</span>
  <span class="fa fa-star" data-rating="3">3</span>
  <span class="fa fa-star" data-rating="4">4</span>
  <span class="fa fa-star-o" data-rating="5">5</span>
  <input name="whatever1" id="publicfeedbackvaluestar1" class="rating-value" value="4" type="hidden">
</div>
<div class="star-rating" id="star2">
  <span class="fa fa-star" data-rating="1">1</span>
  <span class="fa fa-star" data-rating="2">2</span>
  <span class="fa fa-star" data-rating="3">3</span>
  <span class="fa fa-star" data-rating="4">4</span>
  <span class="fa fa-star-o" data-rating="5">5</span>
  <input name="whatever2" id="publicfeedbackvaluestar2" class="rating-value" value="4" type="hidden">
</div>
<div class="star-rating" id="star3">
  <span class="fa fa-star" data-rating="1">1</span>
  <span class="fa fa-star" data-rating="2">2</span>
  <span class="fa fa-star" data-rating="3">3</span>
  <span class="fa fa-star" data-rating="4">4</span>
  <span class="fa fa-star-o" data-rating="5">5</span>
  <input name="whatever3" id="publicfeedbackvaluestar3" class="rating-value" value="4" type="hidden">
</div></code>```

Title: How to Get Id in javascript?

Body:
How to Get id form this codein javascript/Jquery

 <input name="whatever1" id="publicfeedbackvaluestar1"  class="rating-value"
  value="4" type="hidden">

 <input name="whatever2" id="publicfeedbackvaluestar2"  class="rating-value"
  value="4" type="hidden">

 <input name="whatever3" id="publicfeedbackvaluestar3"  class="rating-value"
  value="4" type="hidden">

How to store clicking rating value in text box ..
my jquery code

  $(".star-rating .fa").on('click', function() {
 id=$(this).attr("id");
 $('#publicfeedbackvalue'+id).val($(this).data('rating'));
 return SetRatingStar(id);
 });

get id star3 How ?

Please Help me..

Body:
You need to use id = $(this).parent().attr("id");

$(".star-rating .fa").on('click', function() {
  var id = $(this).parent().attr("id");
  var ratingClicked = $(this).data('rating');
  console.log('id: ' + id);
  console.log('rating: ' + ratingClicked);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="star-rating" id="star1">
  <span class="fa fa-star" data-rating="1">1</span>
  <span class="fa fa-star" data-rating="2">2</span>
  <span class="fa fa-star" data-rating="3">3</span>
  <span class="fa fa-star" data-rating="4">4</span>
  <span class="fa fa-star-o" data-rating="5">5</span>
  <input name="whatever1" id="publicfeedbackvaluestar1" class="rating-value" value="4" type="hidden">
</div>
<div class="star-rating" id="star2">
  <span class="fa fa-star" data-rating="1">1</span>
  <span class="fa fa-star" data-rating="2">2</span>
  <span class="fa fa-star" data-rating="3">3</span>
  <span class="fa fa-star" data-rating="4">4</span>
  <span class="fa fa-star-o" data-rating="5">5</span>
  <input name="whatever2" id="publicfeedbackvaluestar2" class="rating-value" value="4" type="hidden">
</div>
<div class="star-rating" id="star3">
  <span class="fa fa-star" data-rating="1">1</span>
  <span class="fa fa-star" data-rating="2">2</span>
  <span class="fa fa-star" data-rating="3">3</span>
  <span class="fa fa-star" data-rating="4">4</span>
  <span class="fa fa-star-o" data-rating="5">5</span>
  <input name="whatever3" id="publicfeedbackvaluestar3" class="rating-value" value="4" type="hidden">
</div>


问:
How to Align smaller text on top of larger text
I have three text items in a container. The middle text has the larger font. I would like to align the top the first item to the top of the second item.

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
}

.large {
  font-size: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <p class="first">One</p>
    <p class="large">Two</p>
    <p>Three</p>
  </div>
</body></code>```

https://jsfiddle.net/7ofrravh/2/

The only way I can think of to do this is to use absolute position but this gets out of line when I change the screen size. I want to be able to change the size of the screen and have everything stay in place. Does anyone know a way to do this?

答:
Change CSS:

```<code>.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
  vertical-align:top;
  margin:0;
}

.large {
  font-size: 50px;
  line-height:1;
}
</code>```

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
  vertical-align:top;
  margin:0;
}

.large {
  font-size: 50px;
  line-height:1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <p class="first">One</p>
    <p class="large">Two</p>
    <p>Three</p>
  </div>
</body></code>```

Body:
I have three text items in a container. The middle text has the larger font. I would like to align the top the first item to the top of the second item.

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
}

.large {
  font-size: 50px;
}

One

Two

Three

https://jsfiddle.net/7ofrravh/2/

The only way I can think of to do this is to use absolute position but this gets out of line when I change the screen size. I want to be able to change the size of the screen and have everything stay in place. Does anyone know a way to do this?

Body:
Change CSS:

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
  vertical-align:top;
  margin:0;
}

.large {
  font-size: 50px;
  line-height:1;
}

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
  vertical-align:top;
  margin:0;
}

.large {
  font-size: 50px;
  line-height:1;
}

<body>
  <div class="container">
    <p class="first">One</p>
    <p class="large">Two</p>
    <p>Three</p>
  </div>
</body>


问:
Nullpointerexception in accessing interface method in retrofit calling
Nullpointerexception in accessing interface method in retrofit calling

Userservice.class

```<code>public interface UserService {

    @POST("login")
    Call<ResUser> login(@Body login login);
}
</code>```

RetrofitClient.class

```<code>public class RetrofitClient {

    private static Retrofit retrofit=null;

    public static Retrofit getClient(String url){

        if(retrofit==null){
            retrofit=new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
}
</code>```

login.class

```<code>    private void doLogin(String username,String password){
    Call<ResUser> call=userService.login(new login(username,password));
    call.enqueue(new Callback<ResUser>() {
        @Override
        public void onResponse(Call<ResUser> call, Response<ResUser> response) {
            if(response.isSuccessful()){
             Log.e("succes");
            }
        }

        @Override
        public void onFailure(Call<ResUser> call, Throwable t) {

        }
    });

}
</code>```

ApiUtils.class

```<code>public class ApiUtils {

    public static final String BASE_URL="";

    public static UserService getUserService(){
        return RetrofitClient.getClient(BASE_URL).create(UserService.class);
    }
}
</code>```

i have nullpointerexception in this line

```<code>  Call<ResUser> call=userService.login(new login(username,password));
</code>```

答:
add this  UserService userService = ApiUtils.getUserService(); line of code before you make call to login service Call<ResUser> call=userService.login(new login(username,password));

```<code>UserService userService = ApiUtils.getUserService();
Call<ResUser> call=userService.login(new login(username,password));
</code>```

you should have an instance of UserService interface named userService to call the method login()

Body:
Nullpointerexception in accessing interface method in retrofit calling

Userservice.class

public interface UserService {

    @POST("login")
    Call<ResUser> login(@Body login login);
}

RetrofitClient.class

public class RetrofitClient {

    private static Retrofit retrofit=null;

    public static Retrofit getClient(String url){

        if(retrofit==null){
            retrofit=new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
}

login.class

    private void doLogin(String username,String password){
    Call<ResUser> call=userService.login(new login(username,password));
    call.enqueue(new Callback<ResUser>() {
        @Override
        public void onResponse(Call<ResUser> call, Response<ResUser> response) {
            if(response.isSuccessful()){
             Log.e("succes");
            }
        }

        @Override
        public void onFailure(Call<ResUser> call, Throwable t) {

        }
    });

}

ApiUtils.class

public class ApiUtils {

    public static final String BASE_URL="";

    public static UserService getUserService(){
        return RetrofitClient.getClient(BASE_URL).create(UserService.class);
    }
}

i have nullpointerexception in this line

  Call<ResUser> call=userService.login(new login(username,password));

Body:
add this  UserService userService = ApiUtils.getUserService(); line of code before you make call to login service Call<ResUser> call=userService.login(new login(username,password));

UserService userService = ApiUtils.getUserService();
Call<ResUser> call=userService.login(new login(username,password));

you should have an instance of UserService interface named userService to call the method login()


问:
Stopping JUnit suite if particular test fails
I have a JUnit test suite in the form:

```<code>@RunWith(Suite.class)
@Suite.SuiteClasses( { xx.class, yy.cass })

public class AllTests {

public static Test suite() {
    TestSuite suite = new TestSuite(AllTests.class.getName());
    //$JUnit-BEGIN$

    //$JUnit-END$
    return suite;
}
}
</code>```

This then calls vanilla tests like this:

```<code>public class xxx {

@Test
public void test () throws {
    ...
</code>```

I have a situation where I'd like to stop the rest of the test suite running if there's an error or fail in the first test. But errors / fails in the others are ok and the suite should complete as many other tests as it can. Basically the first test failing would indicate it isn't safe to run the rest.

Is this possible?

答:
Firstly you should catch an error and check the same before you run the 2nd test.

```<code>@Rule
public ErrorCollector collector = new ErrorCollector();
</code>```

1. Add Error.

```<code>collector.addError(new Throwable("first thing went wrong"));
</code>```

2. Check before the dependent run.

```<code>collector.checkThat(getResult(), not(containsString("ERROR!")));
</code>```

Reference - ErrorCollector

Body:
I have a JUnit test suite in the form:

@RunWith(Suite.class)
@Suite.SuiteClasses( { xx.class, yy.cass })

public class AllTests {

public static Test suite() {
    TestSuite suite = new TestSuite(AllTests.class.getName());
    //$JUnit-BEGIN$

    //$JUnit-END$
    return suite;
}
}

This then calls vanilla tests like this:

public class xxx {

@Test
public void test () throws {
    ...

I have a situation where I'd like to stop the rest of the test suite running if there's an error or fail in the first test. But errors / fails in the others are ok and the suite should complete as many other tests as it can. Basically the first test failing would indicate it isn't safe to run the rest.

Is this possible?

Body:
Firstly you should catch an error and check the same before you run the 2nd test.

@Rule
public ErrorCollector collector = new ErrorCollector();

1. Add Error.

collector.addError(new Throwable("first thing went wrong"));

2. Check before the dependent run.

collector.checkThat(getResult(), not(containsString("ERROR!")));

Reference - ErrorCollector


问:
How to implement endless list with RecyclerView?
I would like to change ListView to RecyclerView. I want to use the onScroll of the OnScrollListener in RecyclerView to determine if a user scrolled to the end of the list.

How do I know if a user scrolls to the end of the list so that I can fetch new data from a REST service?

答:
```<code>if (layoutManager.findLastCompletelyVisibleItemPosition() ==
 recyclerAdapter.getItemCount() - 1) {
    //load more items.
 }
</code>```

Fair and simple.
This will work.

Body:
if (layoutManager.findLastCompletelyVisibleItemPosition() ==
 recyclerAdapter.getItemCount() - 1) {
    //load more items.
 }

Fair and simple.
This will work.


问:
How to avoid use of Thread.Sleep
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans.  Netbeans now warns you not to use Thread.Sleep.  So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.

So my question is how can I keep from using Thread.Sleep in the following situation.

I have written a server application that interfaces with another application.  The server has two threads:

Handles the data coming over the socket and sends back other information or just plain acknoledgements.

This is the main thread.  After kicking off the socket thread it going into an indefinite while loop.  Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface.  Then I sleep and continue this while loop.

With this application, the TrayIcon is the only UI.

Here is the snippet I'm referencing:

```<code>// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.

while(doNotExit())
{

    if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
        resetsThreadAndSocket();

    try
    {
        // check to see if the socket threads are still active, if not create new ones.
        if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
            createSocketThread();

        // check right before sleeping that the user does not want to exit.
        if(getTrayIcon().isExiting())
            break;

        // puts the main Thread to sleep for 3 seconds
           Thread.sleep(3000);
    }
    catch(SQLException ex)
    {
        _log.error(ex.getMessage(), ex);
        restartDatabase();
    }
}
</code>```

答:
The 'preferred' method in most cases would be to use the ScheduledExecutorService built into JavaSE for performing a periodic task, rather than reimplementing it yourself every time using a while loop and Thread.Sleep().

There's nothing wrong per-se with your example.  The language just now has a much more robust support for doing that built into it as of Java 5.

Title: How to avoid use of Thread.Sleep

Body:
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans.  Netbeans now warns you not to use Thread.Sleep.  So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.

So my question is how can I keep from using Thread.Sleep in the following situation.

I have written a server application that interfaces with another application.  The server has two threads:

Handles the data coming over the socket and sends back other information or just plain acknoledgements.

This is the main thread.  After kicking off the socket thread it going into an indefinite while loop.  Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface.  Then I sleep and continue this while loop.

With this application, the TrayIcon is the only UI.

Here is the snippet I'm referencing:

// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.

while(doNotExit())
{

    if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
        resetsThreadAndSocket();

    try
    {
        // check to see if the socket threads are still active, if not create new ones.
        if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
            createSocketThread();

        // check right before sleeping that the user does not want to exit.
        if(getTrayIcon().isExiting())
            break;

        // puts the main Thread to sleep for 3 seconds
           Thread.sleep(3000);
    }
    catch(SQLException ex)
    {
        _log.error(ex.getMessage(), ex);
        restartDatabase();
    }
}


问:
Using Bootstrap DatetimePicker with Sweet Alert 2 - Display calendar over alert
I am using the SweetAlert2 dialog with a form inside. I want to use the Bootstrap DateTimePicker widget.

The calendar widget popup is displayed within the SweetAlert window instead of over top of it. This makes the alert expand and contract - and you must scroll inside the alert to see the calendar. The desired behavior is for the calendar to display as a child of the primary page and display over top of the alert.

https://jsfiddle.net/ghr2bwoc/13/

```<code>  swal({
    title: 'Date picker',
    html: '<input id="datepicker">',
    showConfirmButton: false,
    onOpen: function() {
        $('#datepicker').datetimepicker({});
    },

  }).then(function(result) {

  });
</code>```

答:
If your are like me and don't want the sweetalert's height to automatically resize when the datetime picker appears. Add a max height and max width (max-height: 550px !important;min-height:550px !important;) to @taekwondoalex's answer.

So still add the custom class to the sweetalert  like so;

```<code>swal({
  title: 'Date picker',
  html: '<input id="datepicker">',
  showConfirmButton: false,
  customClass: 'custom-swal-class',
  onOpen: function() {
      $('#datepicker').datetimepicker({});
  },

}).then(function(result) {

});
</code>```

Then add to your css and change the pixel height to match the height you want for example 550px

```<code>.custom-swal-class {
    overflow-x: visible;
    overflow-y: visible;
    max-height: 550px !important;
    min-height: 550px !important;
}
</code>```

Body:
I am using the SweetAlert2 dialog with a form inside. I want to use the Bootstrap DateTimePicker widget.

The calendar widget popup is displayed within the SweetAlert window instead of over top of it. This makes the alert expand and contract - and you must scroll inside the alert to see the calendar. The desired behavior is for the calendar to display as a child of the primary page and display over top of the alert.

https://jsfiddle.net/ghr2bwoc/13/

  swal({
    title: 'Date picker',
    html: '<input id="datepicker">',
    showConfirmButton: false,
    onOpen: function() {
        $('#datepicker').datetimepicker({});
    },

  }).then(function(result) {

  });

Body:
If your are like me and don't want the sweetalert's height to automatically resize when the datetime picker appears. Add a max height and max width (max-height: 550px !important;min-height:550px !important;) to @taekwondoalex's answer.

So still add the custom class to the sweetalert  like so;

swal({
  title: 'Date picker',
  html: '<input id="datepicker">',
  showConfirmButton: false,
  customClass: 'custom-swal-class',
  onOpen: function() {
      $('#datepicker').datetimepicker({});
  },

}).then(function(result) {

});

Then add to your css and change the pixel height to match the height you want for example 550px

.custom-swal-class {
    overflow-x: visible;
    overflow-y: visible;
    max-height: 550px !important;
    min-height: 550px !important;
}


问:
Nodejs: Async request with a list of URL
I am working on a crawler. I have a list of URL need to be requested. There are several hundreds of request at the same time if I don't set it to be async. I am afraid that it would explode my bandwidth or produce to much network access to the target website. What should I do?

Here is what I am doing:

```<code>urlList.forEach((url, index) => {

    console.log('Fetching ' + url);
    request(url, function(error, response, body) {
        //do sth for body

    });
});
</code>```

I want one request is called after one request is completed.

答:
The things you need to watch for are:

Whether the target site has rate limiting and you may be blocked from access if you try to request too much too fast?

How many simultaneous requests the target site can handle without degrading its performance?

How much bandwidth your server has on its end of things?

How many simultaneous requests your own server can have in flight and process without causing excess memory usage or a pegged CPU.

In general, the scheme for managing all this is to create a way to tune how many requests you launch.  There are many different ways to control this by number of simultaneous requests, number of requests per second, amount of data used, etc...

The simplest way to start would be to just control how many simultaneous requests you make.  That can be done like this:

```<code>function runRequests(arrayOfData, maxInFlight, fn) {
    return new Promise((resolve, reject) => {
        let index = 0;
        let inFlight = 0;

        function next() {
            while (inFlight < maxInFlight && index < arrayOfData.length) {
                ++inFlight;
                fn(arrayOfData[index++]).then(result => {
                    --inFlight;
                    next();
                }).catch(err => {
                    --inFlight;
                    console.log(err);
                    // purposely eat the error and let the rest of the processing continue
                    // if you want to stop further processing, you can call reject() here
                    next();
                });
            }
            if (inFlight === 0) {
                // all done
                resolve();
            }
        }
        next();
    });
}
</code>```

And, then you would use that like this:

```<code>const rp = require('request-promise');

// run the whole urlList, no more than 10 at a time
runRequests(urlList, 10, function(url) {
    return rp(url).then(function(data) {
        // process fetched data here for one url
    }).catch(function(err) {
        console.log(url, err);
    });
}).then(function() {
    // all requests done here
});
</code>```

This can be made as sophisticated as you want by adding a time element to it (no more than N requests per second) or even a bandwidth element to it.

I want one request is called after one request is completed.

That's a very slow way to do things.  If you really want that, then you can just pass a 1 for the maxInFlight parameter to the above function, but typically, things would work a lot faster and not cause problems by allowing somewhere between 5 and 50 simultaneous requests.  Only testing would tell you where the sweet spot is for your particular target sites and your particular server infrastructure and amount of processing you need to do on the results.

Body:
I am working on a crawler. I have a list of URL need to be requested. There are several hundreds of request at the same time if I don't set it to be async. I am afraid that it would explode my bandwidth or produce to much network access to the target website. What should I do?

Here is what I am doing:

urlList.forEach((url, index) => {

    console.log('Fetching ' + url);
    request(url, function(error, response, body) {
        //do sth for body

    });
});

I want one request is called after one request is completed.

Body:
The things you need to watch for are:

Whether the target site has rate limiting and you may be blocked from access if you try to request too much too fast?

How many simultaneous requests the target site can handle without degrading its performance?

How much bandwidth your server has on its end of things?

How many simultaneous requests your own server can have in flight and process without causing excess memory usage or a pegged CPU.

In general, the scheme for managing all this is to create a way to tune how many requests you launch.  There are many different ways to control this by number of simultaneous requests, number of requests per second, amount of data used, etc...

The simplest way to start would be to just control how many simultaneous requests you make.  That can be done like this:

function runRequests(arrayOfData, maxInFlight, fn) {
    return new Promise((resolve, reject) => {
        let index = 0;
        let inFlight = 0;

        function next() {
            while (inFlight < maxInFlight && index < arrayOfData.length) {
                ++inFlight;
                fn(arrayOfData[index++]).then(result => {
                    --inFlight;
                    next();
                }).catch(err => {
                    --inFlight;
                    console.log(err);
                    // purposely eat the error and let the rest of the processing continue
                    // if you want to stop further processing, you can call reject() here
                    next();
                });
            }
            if (inFlight === 0) {
                // all done
                resolve();
            }
        }
        next();
    });
}

And, then you would use that like this:

const rp = require('request-promise');

// run the whole urlList, no more than 10 at a time
runRequests(urlList, 10, function(url) {
    return rp(url).then(function(data) {
        // process fetched data here for one url
    }).catch(function(err) {
        console.log(url, err);
    });
}).then(function() {
    // all requests done here
});

This can be made as sophisticated as you want by adding a time element to it (no more than N requests per second) or even a bandwidth element to it.

I want one request is called after one request is completed.

That's a very slow way to do things.  If you really want that, then you can just pass a 1 for the maxInFlight parameter to the above function, but typically, things would work a lot faster and not cause problems by allowing somewhere between 5 and 50 simultaneous requests.  Only testing would tell you where the sweet spot is for your particular target sites and your particular server infrastructure and amount of processing you need to do on the results.


问:
Python Regex: how to parse repeated groups in a string?
I want to match a pattern with a string including pure numbers, such as '2324235235980980' with a pattern like as described below:

The pattern is '2-6-8-7-4', in which the pattern starts with 2, transit to 6, either self-loop at 6 or transit to 8, then it could go back and forth between 6 and 8, could self-loop at 8, or could transit to 7. And the same thing for 7. One more thing for 7 is 7-8-6-8-7 could happen. Finally, 7 could reach 4, once it reaches 4, the pattern is done. During the process, if it reaches out to other points, then it has to start with 2 again to be counted.
I use

```<code>import re
re.findall(r'(2((6+8+)+)7)', test_string)
</code>```

the output includes '2666686888668887', but when I add 4, I don't know the syntax to compile this. Has anyone an idea? Thanks a lot!

答:
I don't know if I understand what you need, but maybe this can work for you:

```<code>string = "2666686888668887748926874"
index = [(m.start(0), m.end(0)) for m in re.finditer(r'2(6+8+)+7+\1?4', string)]
print(index)
</code>```

Prints: [(0, 18), (20, 25)].

Is a list of tuples with the start and end index for every occurrence.

Body:
I want to match a pattern with a string including pure numbers, such as '2324235235980980' with a pattern like as described below:

The pattern is '2-6-8-7-4', in which the pattern starts with 2, transit to 6, either self-loop at 6 or transit to 8, then it could go back and forth between 6 and 8, could self-loop at 8, or could transit to 7. And the same thing for 7. One more thing for 7 is 7-8-6-8-7 could happen. Finally, 7 could reach 4, once it reaches 4, the pattern is done. During the process, if it reaches out to other points, then it has to start with 2 again to be counted.
I use

import re
re.findall(r'(2((6+8+)+)7)', test_string)

the output includes '2666686888668887', but when I add 4, I don't know the syntax to compile this. Has anyone an idea? Thanks a lot!

Body:
I don't know if I understand what you need, but maybe this can work for you:

string = "2666686888668887748926874"
index = [(m.start(0), m.end(0)) for m in re.finditer(r'2(6+8+)+7+\1?4', string)]
print(index)

Prints: [(0, 18), (20, 25)].

Is a list of tuples with the start and end index for every occurrence.


问:
alternate optimized query of sub query
```<code>select * from solar_park where solar_park_uid
in
(select distinct solar_park from solar_park_pooling_station where pooling_station
in
(select distinct pooling_station_uid FROM solar_inverter where solar_generator_uid in (:solarGeneratorUid));
</code>```

I am using this query but for certain reasons i want alter query of this plz help

答:
An alternative can be to re-write the query as correlated sub-query as below.

```<code>select *
from solar_park sp
where exists (
                select 1 -- * can also be used
                from solar_park_pooling_station spps
                where exists (
                            select 1 -- * can also be used
                            from solar_inverter si
                            where spps.pooling_station = si.pooling_station_uid
                            and sp.solar_park_uid = spps.solar_park
                            and solar_generator_uid IN (:solarGeneratorUid)
                            )
              );
</code>```

You can check tutorial: Exists and Not Exists sub-queries in MySQL

Hope this will help.

Title: alternate optimized query of sub query

Body:
select * from solar_park where solar_park_uid
in
(select distinct solar_park from solar_park_pooling_station where pooling_station
in
(select distinct pooling_station_uid FROM solar_inverter where solar_generator_uid in (:solarGeneratorUid));

I am using this query but for certain reasons i want alter query of this plz help

Body:
An alternative can be to re-write the query as correlated sub-query as below.

select *
from solar_park sp
where exists (
                select 1 -- * can also be used
                from solar_park_pooling_station spps
                where exists (
                            select 1 -- * can also be used
                            from solar_inverter si
                            where spps.pooling_station = si.pooling_station_uid
                            and sp.solar_park_uid = spps.solar_park
                            and solar_generator_uid IN (:solarGeneratorUid)
                            )
              );

You can check tutorial: Exists and Not Exists sub-queries in MySQL

Hope this will help.


问:
how to use option selected by user from JOptionPane in if statement?
I want users to select one of the option from JOptionPane. Then I want to use that option in an if statement. But I am not sure how to do that?
Here is my code:

```<code>import javax.swing.JOptionPane;
public class MortgageCalculator {

    public static void main(String[]args)
    {
        JOptionPane.showMessageDialog(null, "Lets calculate your mortgage",null, JOptionPane.PLAIN_MESSAGE);

        double principle = Double.parseDouble(JOptionPane.showInputDialog(null, "What is your loan amount?"));

        int years = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the lenght of your loan"));
        int n = years * 12;

        double rate = Double.parseDouble(JOptionPane.showInputDialog(null, "What is your interest rate?"));

        String[] options = new String[] {"Compound", "Simple"};

        int response = JOptionPane.showOptionDialog(null, null, "Choose your interest type", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,null, options, options[0]);

        //I want to use my selected option here.
        if(options ==compound)
        {
            double payment = (compound(principle,years,rate))/n;

        }
        else
        {
            double payment = (simple(principle, years, rate))/n;
        }
    }

    public static double simple(double principle, int n , double interestRate)
    {
        double interest = principle * n * (interestRate/100);
        double totalLoan = principle + interest;
        return totalLoan;
    }

    public static double compound(double principle, int years, double interestRate)
    {
        int n = years * 12;
        double base = (principle* (1+ (interestRate/100)*1/n));
        double amount = Math.pow(base, n);
        return amount;
    }
</code>```

Btw, this is not a complete code. There are syntax missing.
Thanks for the help.

答:
When your buttons are provided to the dialog in a String array then when that button is selected it is the index value to where that button name resides within the array that is returned.

Compound would return a index value of 0 from the dialog and Simple would return a index value of 1.

```<code>// Compound (0)
if(response == 0) {
    double payment = (compound(principle,years,rate))/n;

}
// Simple (1)
else {
    double payment = (simple(principle, years, rate))/n;
}
</code>```

Check the value in the response variable.... Not options.

Body:
I want users to select one of the option from JOptionPane. Then I want to use that option in an if statement. But I am not sure how to do that?
Here is my code:

import javax.swing.JOptionPane;
public class MortgageCalculator {

    public static void main(String[]args)
    {
        JOptionPane.showMessageDialog(null, "Lets calculate your mortgage",null, JOptionPane.PLAIN_MESSAGE);

        double principle = Double.parseDouble(JOptionPane.showInputDialog(null, "What is your loan amount?"));

        int years = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the lenght of your loan"));
        int n = years * 12;

        double rate = Double.parseDouble(JOptionPane.showInputDialog(null, "What is your interest rate?"));

        String[] options = new String[] {"Compound", "Simple"};

        int response = JOptionPane.showOptionDialog(null, null, "Choose your interest type", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,null, options, options[0]);

        //I want to use my selected option here.
        if(options ==compound)
        {
            double payment = (compound(principle,years,rate))/n;

        }
        else
        {
            double payment = (simple(principle, years, rate))/n;
        }
    }

    public static double simple(double principle, int n , double interestRate)
    {
        double interest = principle * n * (interestRate/100);
        double totalLoan = principle + interest;
        return totalLoan;
    }

    public static double compound(double principle, int years, double interestRate)
    {
        int n = years * 12;
        double base = (principle* (1+ (interestRate/100)*1/n));
        double amount = Math.pow(base, n);
        return amount;
    }

Btw, this is not a complete code. There are syntax missing.
Thanks for the help.

Body:
When your buttons are provided to the dialog in a String array then when that button is selected it is the index value to where that button name resides within the array that is returned.

Compound would return a index value of 0 from the dialog and Simple would return a index value of 1.

// Compound (0)
if(response == 0) {
    double payment = (compound(principle,years,rate))/n;

}
// Simple (1)
else {
    double payment = (simple(principle, years, rate))/n;
}

Check the value in the response variable.... Not options.


问:
Iterate over a column in PL/SQL
I have a table Emp with EmpID, Empname, Salary and I am trying to do a calculation for each employee. But I am having problems trying to iterate over each emp to do the calculation. I cant use explicit cursors though.

So right now I am just trying to create the list of empIDs:

```<code>Declare
    aRows Number;
    eid emp_ID%TYPE;
Begin
    Select Count(*)
    Into aRows
    from emp;

    Select emp_ID
    Into eid
    From emp;

    FOR days IN 1..Tot_Rows
    Loop
        Dbms_Output.Put_Line(eid);
        eid := eid + 1;
    End Loop;
END;
</code>```

But I get the error:
PLS-00320: the declaration of the type of this expression is incomplete or malformed

答:
Justin Cave has explained how to do it, but to specifically look at the error you got, that was because of this:

```<code>eid emp_ID%TYPE;
</code>```

When using the %TYPE you have to specify the table name as well as the column name:

```<code>eid emp.emp_ID%TYPE;
</code>```

If you were selecting all the columns in the row you could also look at %ROWTYPE.

Your approach was also making two assumptions: that the initial select into eid found the lowest ID, which is by no means guaranteed; and that all the subsequent ID values are sequential. And you're declaring and populating aRows but referring to Tot_Rows.

Title: Iterate over a column in PL/SQL

Body:
I have a table Emp with EmpID, Empname, Salary and I am trying to do a calculation for each employee. But I am having problems trying to iterate over each emp to do the calculation. I cant use explicit cursors though.

So right now I am just trying to create the list of empIDs:

Declare
    aRows Number;
    eid emp_ID%TYPE;
Begin
    Select Count(*)
    Into aRows
    from emp;

    Select emp_ID
    Into eid
    From emp;

    FOR days IN 1..Tot_Rows
    Loop
        Dbms_Output.Put_Line(eid);
        eid := eid + 1;
    End Loop;
END;

But I get the error:
PLS-00320: the declaration of the type of this expression is incomplete or malformed

Body:
Justin Cave has explained how to do it, but to specifically look at the error you got, that was because of this:

eid emp_ID%TYPE;

When using the %TYPE you have to specify the table name as well as the column name:

eid emp.emp_ID%TYPE;

If you were selecting all the columns in the row you could also look at %ROWTYPE.

Your approach was also making two assumptions: that the initial select into eid found the lowest ID, which is by no means guaranteed; and that all the subsequent ID values are sequential. And you're declaring and populating aRows but referring to Tot_Rows.


问:
How to turn off autocorrect when using on mobile
I have issue when using react-bootstrap-typeahead on mobile. I want to turn off autocorrect of input but i don't know how to do it.

please help me.
thank all so much.

答:
In general, you can use the spellcheck attribute (as well as autocorrect in Safari) on inputs to disable these features. In react-bootstrap-typeahead, you can set these values using the inputProps prop:

```<code><Typeahead
  inputProps={{
    autoCorrect: 'off', // Safari-only
    spellCheck: false,
  }}
/>
</code>```

However, note that according to caniuse:

The partial support in mobile browsers results from their OS generally having built-in spell checking instead of using the wavy underline to indicate misspelled words. spellcheck="false" does not seem to have any effect in these browsers.

So, it may not be possible to fully disable autocorrect in mobile browsers since that can be up to the individual's OS-level settings.

Body:
In general, you can use the spellcheck attribute (as well as autocorrect in Safari) on inputs to disable these features. In react-bootstrap-typeahead, you can set these values using the inputProps prop:

<Typeahead
  inputProps={{
    autoCorrect: 'off', // Safari-only
    spellCheck: false,
  }}
/>

However, note that according to caniuse:

The partial support in mobile browsers results from their OS generally having built-in spell checking instead of using the wavy underline to indicate misspelled words. spellcheck="false" does not seem to have any effect in these browsers.

So, it may not be possible to fully disable autocorrect in mobile browsers since that can be up to the individual's OS-level settings.


问:
alert() in AJAX callback shows [Object object]
I am calling the following function to do stuff in the Spring Controller. The problem is that the alert message is not containing the message that I am sending, but prints [Object object]. Is there a way to send the particular message, according to the result, print it and also send the Status code?

function saveButton(button) {
  var data = gatherData(button);
  $.ajax({
    type: "POST",
    url: '/editRecord',
    data: data,
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function(response) {
      alert(response);
    },
    error: function(error) {
      alert(getData().done(error));
    }
  });
}
```

<pre class="lang-java prettyprint-override"><code>@RequestMapping(value = "/editRecord", method = RequestMethod.POST)
public @ResponseBody
String editRecord(HttpServletRequest httpRequest)
{
  Map<String, String[]> map = httpRequest.getParameterMap();

  // do stuff

  String messageToReturn = "";
  if (userService.updateTable(pr.getUpdateQuery(fileMap)))
  {
    messageToReturn = "Operation was successful";
  }
  else
    messageToReturn = "Operation failed";

  return messageToReturn;
}
</code>```

答:
```<code>success: function(response) {
  alert(response.responseText);
},
</code>```

Body:
I am calling the following function to do stuff in the Spring Controller. The problem is that the alert message is not containing the message that I am sending, but prints [Object object]. Is there a way to send the particular message, according to the result, print it and also send the Status code?

function saveButton(button) {
  var data = gatherData(button);
  $.ajax({
    type: "POST",
    url: '/editRecord',
    data: data,
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function(response) {
      alert(response);
    },
    error: function(error) {
      alert(getData().done(error));
    }
  });
}

@RequestMapping(value = "/editRecord", method = RequestMethod.POST)
public @ResponseBody
String editRecord(HttpServletRequest httpRequest)
{
  Map<String, String[]> map = httpRequest.getParameterMap();

  // do stuff

  String messageToReturn = "";
  if (userService.updateTable(pr.getUpdateQuery(fileMap)))
  {
    messageToReturn = "Operation was successful";
  }
  else
    messageToReturn = "Operation failed";

  return messageToReturn;
}


问:
Typing Casting in Python Question
Im a AS3 developer, currently learning Python

In AS3 Id quite often do this:

```<code>for ( var foo in fooArray ) {
   trace(FooObject(foo).name);
}
</code>```

Typing casting the objects in the array, so that I get code hinting in my IDE

How would I do this in Python?

答: There is no type casting in Python, as types are dynamic, so casting is completely pointless. Your IDE will give hints if it can figure out what type it is, which it often can't.</p>

Title: Typing Casting in Python Question

Body:
Im a AS3 developer, currently learning Python

In AS3 Id quite often do this:

for ( var foo in fooArray ) {
   trace(FooObject(foo).name);
}

Typing casting the objects in the array, so that I get code hinting in my IDE

How would I do this in Python?


问:
Getting permission denied error with docker remove
I'm following a tutorial and in the current step, i'm supposed to remove any preexisting docker containers with this

```<code>docker rm -f $(docker ps -aq)
</code>```

I usually have to use sudo to use docker commands, so I tried

```<code>sudo docker rm -f $(docker ps -aq)
</code>```

But I get this

```<code>Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.32/containers/json?all=1: dial unix /var/run/docker.sock: connect: permission denied
"docker rm" requires at least 1 argument.
See 'docker rm --help'.

Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers
</code>```

Usually I get permission errors when I forget to use sudo, but in this case I have it.

Does anyone know what's wrong?

Thanks

EDIT

I tried this

```<code>sudo docker rm -f $(sudo docker ps -aq)
</code>```

but get

```<code>"docker rm" requires at least 1 argument.
See 'docker rm --help'.

Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers
</code>```

答: I think you don't have any preexisting containers, Result of this command sudo docker ps -aq seems to be empty, which will result in total command as sudo docker rm -f without any container ID's. You can skip this command as there were no preexisting containers.

Body:
I'm following a tutorial and in the current step, i'm supposed to remove any preexisting docker containers with this

docker rm -f $(docker ps -aq)

I usually have to use sudo to use docker commands, so I tried

sudo docker rm -f $(docker ps -aq)

But I get this

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.32/containers/json?all=1: dial unix /var/run/docker.sock: connect: permission denied
"docker rm" requires at least 1 argument.
See 'docker rm --help'.

Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers

Usually I get permission errors when I forget to use sudo, but in this case I have it.

Does anyone know what's wrong?

Thanks

EDIT

I tried this

sudo docker rm -f $(sudo docker ps -aq)

but get

"docker rm" requires at least 1 argument.
See 'docker rm --help'.

Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers


问:
React/JSX attrs w/strings vs braces
The docs say that a JSX attributes with strings are the same as attributes with braces...

<Thing attr='val' /> === <Thing attr={'val'} />

I thought I read something that said only use braces when needed because strings are more performant, but I can't find the reference now. Is there an evaluation cost for braces?

答:
No there is no performance difference. Look at the code that's generated by each style:

```<code><div first="abc" second={"def"}/>

// Compiles to:
React.createElement("div", { first: "abc", second: "def" });
</code>```

Nicer to avoid unneeded braces though.

Title: React/JSX attrs w/strings vs braces

Body:
No there is no performance difference. Look at the code that's generated by each style:

<div first="abc" second={"def"}/>

// Compiles to:
React.createElement("div", { first: "abc", second: "def" });

Nicer to avoid unneeded braces though.


问:
Uncaught TypeError: Cannot read property 'get' of undefined in VueJs
I have following code

```<code><div id="vue-instance">

</div>
</code>```

JS

```<code>var vm = new Vue({
  el: '#vue-instance',
  data: {
  },
  ready:function(){
    this.loadCountries();
  },
  methods:{
        loadCountries(){
            this.$http.get('https://restcountries.eu/rest/v1/all',function(data){
                console.log(data);
          })
      }
  }
});
</code>```

When I run the above code it gives me following error

Uncaught TypeError: Cannot read property 'get' of undefined

I have a fiddle

JsFiddle

Help would be much appreciated

答:
I fixed this issue of the following mode:

```<code>npm install bootstrap-vue --save
npm install vue-resource --save
</code>```

in main.js

```<code>import Vue from './bootstrap'
import BootstrapVue from 'bootstrap-vue'

Vue.use(BootstrapVue)
</code>```

create bootstrap.js

```<code>import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource)

export { Vue }
</code>```

In App.vue

```<code>this.$http.get('/api/module/all').then(...
</code>```

Body:
I have following code

JS

var vm = new Vue({
  el: '#vue-instance',
  data: {
  },
  ready:function(){
    this.loadCountries();
  },
  methods:{
        loadCountries(){
            this.$http.get('https://restcountries.eu/rest/v1/all',function(data){
                console.log(data);
          })
      }
  }
});

When I run the above code it gives me following error

Uncaught TypeError: Cannot read property 'get' of undefined

I have a fiddle

JsFiddle

Help would be much appreciated

Body:
I fixed this issue of the following mode:

npm install bootstrap-vue --save
npm install vue-resource --save

in main.js

import Vue from './bootstrap'
import BootstrapVue from 'bootstrap-vue'

Vue.use(BootstrapVue)

create bootstrap.js

import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource)

export { Vue }

In App.vue

this.$http.get('/api/module/all').then(...


问:
How to center two letters inside this css drawn circle?
Using this Codepen example and additional CSS, how would I center the letters "AB" within the circle?
https://codepen.io/joseph-mueller/pen/bNEeGw
This is what I want:

.referral-credit-outer-circle {
  background: #fff;
  width: 92px;
  height: 92px;
  border-radius: 90px;
  box-shadow: 0 0 0 2px #fff, 0 0 0 6px #666;
  margin: 20px;
  position: absolute;
}

.mask-referral-credit-inner-circle {
  transform: rotate(180deg);
  width: 100%;
  height: 50%;
  overflow: hidden;
  position: absolute;
  bottom: 0;
}

.referral-credit-inner-circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  border: solid 6px #7aaeda;
  background: #95bee1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="referral-credit-outer-circle">
  <span class="referral-credit-inner-icon" data-icon="H" style="color:"></span>
  <div class="mask-referral-credit-inner-circle" style="height: 70%">
    <div class="referral-credit-inner-circle"></div>
  </div>
</div></code>```

答:
This can be acheived in multiple ways i reckon, here is one with flex and pseudo content and minimal changes

.referral-credit-outer-circle {
  background: #fff;
  width: 92px;
  height: 92px;
  border-radius: 90px;
  box-shadow: 0 0 0 2px #fff, 0 0 0 6px #666;
  margin: 20px;
  position: absolute;
}

.mask-referral-credit-inner-circle {
  transform: rotate(180deg);
  width: 100%;
  height: 50%;
  overflow: hidden;
  position: absolute;
  bottom: 0;
}

.referral-credit-inner-circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  display: flex;
  border: solid 6px #7aaeda;
  background: #95bee1;
  text-align: center;
  font-weight: bold;
  /*new code*/
  flex-direction: row;
  align-items: center;
  justify-content: center;
  font-family: sans-serif;
}
/*new code*/
.referral-credit-inner-circle::before {
  content: "ACB";
  transform: rotate(180deg);
  font-size: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="referral-credit-outer-circle">
  <span class="referral-credit-inner-icon" data-icon="H" style="color:"></span>
  <div class="mask-referral-credit-inner-circle" style="height: 70%">
    <div class="referral-credit-inner-circle"></div>
  </div>
</div></code>```

Body:
This can be acheived in multiple ways i reckon, here is one with flex and pseudo content and minimal changes

.referral-credit-outer-circle {
  background: #fff;
  width: 92px;
  height: 92px;
  border-radius: 90px;
  box-shadow: 0 0 0 2px #fff, 0 0 0 6px #666;
  margin: 20px;
  position: absolute;
}

.mask-referral-credit-inner-circle {
  transform: rotate(180deg);
  width: 100%;
  height: 50%;
  overflow: hidden;
  position: absolute;
  bottom: 0;
}

.referral-credit-inner-circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  display: flex;
  border: solid 6px #7aaeda;
  background: #95bee1;
  text-align: center;
  font-weight: bold;
  /*new code*/
  flex-direction: row;
  align-items: center;
  justify-content: center;
  font-family: sans-serif;
}
/*new code*/
.referral-credit-inner-circle::before {
  content: "ACB";
  transform: rotate(180deg);
  font-size: 1rem;
}

<div class="referral-credit-outer-circle">
  <span class="referral-credit-inner-icon" data-icon="H" style="color:"></span>
  <div class="mask-referral-credit-inner-circle" style="height: 70%">
    <div class="referral-credit-inner-circle"></div>
  </div>
</div>


问:
Error with multiple font-face declarations
CSS @font-face rules:

```<code>@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Light.ttf') format('truetype');
    font-weight: light;
    font-style: normal;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-HairlineItalic.ttf') format('truetype');
    font-weight: lighter;
    font-style: italic;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}
</code>```

And their uses:

```<code>.ingrijirea-main {
    margin-top: 100px;
    background-color: #2A2D4C;
    color: white;
    height: 500px;
}

.ingrijirea-title {
    font-size: 2em;
    text-align: center;
    margin-top: 45px;
    margin-bottom: 30px;
    p {
        margin-bottom: 0;
    }
    .ingrijirea-title-bottom {
        font-weight: lighter;
        font-style: italic;
    }
}

.ingrijirea-text {
    font-size: 1.28em;
    font-weight: light;
    text-align: justify;

    p{
        margin-bottom: 15px;
    }

    .ingrijirea-options {
        margin-top: 30px;
        p {
            margin-bottom: 7px;
        }
        p:hover {
            font-weight: bold;
        }
    }
}
</code>```

And this is my HTML:

```<code><div class="ingrijirea">
    <div class="container-fluid">
        <div class="row ingrijirea-main">
            <div class="col-md-4 col-md-offset-2">
                <div class="ingrijirea-title">
                    <p class="ingrijirea-title-top">Lorem ipsum</p>
                    <p class="ingrijirea-title-bottom">Lorem ipsum</p>
                </div>
                <div class="ingrijirea-text">
                    <p>Lorem ipsum</p>
                    <p>Lorem ipsum</p>
                    <p>Lorem ipsum</p>
                    <div class="ingrijirea-options">
                        <p class="ingrijirea-option">Lorem ipsum</p>
                        <p>Lorem ipsum</p>
                        <p>Lorem ipsum</p>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

The problem is that with this code not only this section, but the whole page is transforming to font-weight:light and I have no idea why.

Any help would be appreciated.

答:
The order of the declaration should change</p>

```<code>@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-HairlineItalic.ttf') format('truetype');
    font-weight: lighter;
    font-style: italic;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Light.ttf') format('truetype');
    font-weight: light;
    font-style: normal;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}
</code>```

Body:
CSS @font-face rules:

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Light.ttf') format('truetype');
    font-weight: light;
    font-style: normal;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-HairlineItalic.ttf') format('truetype');
    font-weight: lighter;
    font-style: italic;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}

And their uses:

.ingrijirea-main {
    margin-top: 100px;
    background-color: #2A2D4C;
    color: white;
    height: 500px;
}

.ingrijirea-title {
    font-size: 2em;
    text-align: center;
    margin-top: 45px;
    margin-bottom: 30px;
    p {
        margin-bottom: 0;
    }
    .ingrijirea-title-bottom {
        font-weight: lighter;
        font-style: italic;
    }
}

.ingrijirea-text {
    font-size: 1.28em;
    font-weight: light;
    text-align: justify;

    p{
        margin-bottom: 15px;
    }

    .ingrijirea-options {
        margin-top: 30px;
        p {
            margin-bottom: 7px;
        }
        p:hover {
            font-weight: bold;
        }
    }
}

And this is my HTML:

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

The problem is that with this code not only this section, but the whole page is transforming to font-weight:light and I have no idea why.

Any help would be appreciated.

Body:
The order of the declaration should change

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-HairlineItalic.ttf') format('truetype');
    font-weight: lighter;
    font-style: italic;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Light.ttf') format('truetype');
    font-weight: light;
    font-style: normal;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

@font-face {
    font-family: 'Lato';
    src: url('fonts/Lato-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}


问:
Why cant we use clone method in class without implementing clonable as even though base class object has "clone()" method?
I was trying to override clone method in my class "Employee", when super.clone() was called, it gave exception but same code worked when I implemented "clonable". What my question is, every class has base class "Object". But when we call  super.clone() it fails and on implementing clonable it works. why is it so?

Like shouldn't base class method can be accessible using "super" from subclass? why does it throws runtime exception?

```<code>public class Employee {
    //explicit Employee extends Object didn't worked.
    String name;
    Integer id;
    public Employee(String name, Integer id) {
       this.name = name;
       this.id = id;
     }
    @Override
    protected Object clone() throws CloneNotSupportedException {
      return super.clone();
    }
  }
</code>```

答:
To answer your question, just take a look at the Object class reference page, and you'll see this:

```<code>The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.
</code>```

So the behavior you described is exactly what Java is defined. Not sure what else is confusing here.

Body:
I was trying to override clone method in my class "Employee", when super.clone() was called, it gave exception but same code worked when I implemented "clonable". What my question is, every class has base class "Object". But when we call  super.clone() it fails and on implementing clonable it works. why is it so?

Like shouldn't base class method can be accessible using "super" from subclass? why does it throws runtime exception?

public class Employee {
    //explicit Employee extends Object didn't worked.
    String name;
    Integer id;
    public Employee(String name, Integer id) {
       this.name = name;
       this.id = id;
     }
    @Override
    protected Object clone() throws CloneNotSupportedException {
      return super.clone();
    }
  }

Body:
To answer your question, just take a look at the Object class reference page, and you'll see this:

The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.

So the behavior you described is exactly what Java is defined. Not sure what else is confusing here.


问:
How to Get Id in javascript?
How to Get id form this codein javascript/Jquery

```<code><div class="star-rating" id="star1">
 <span class="fa fa-star" data-rating="1"></span>
 <span class="fa fa-star" data-rating="2"></span>
 <span class="fa fa-star" data-rating="3"></span>
 <span class="fa fa-star" data-rating="4"></span>
 <span class="fa fa-star-o" data-rating="5"></span>
 <input name="whatever1" id="publicfeedbackvaluestar1"  class="rating-value"
  value="4" type="hidden">
 </div>
 <div class="star-rating" id="star2">
 <span class="fa fa-star" data-rating="1"></span>
 <span class="fa fa-star" data-rating="2"></span>
 <span class="fa fa-star" data-rating="3"></span>
 <span class="fa fa-star" data-rating="4"></span>
 <span class="fa fa-star-o" data-rating="5"></span>
 <input name="whatever2" id="publicfeedbackvaluestar2"  class="rating-value"
  value="4" type="hidden">
 </div>
 <div class="star-rating" id="star3">
 <span class="fa fa-star" data-rating="1"></span>
 <span class="fa fa-star" data-rating="2"></span>
 <span class="fa fa-star" data-rating="3"></span>
 <span class="fa fa-star" data-rating="4"></span>
 <span class="fa fa-star-o" data-rating="5"></span>
 <input name="whatever3" id="publicfeedbackvaluestar3"  class="rating-value"
  value="4" type="hidden">
 </div>
</code>```

How to store clicking rating value in text box ..
my jquery code

```<code>  $(".star-rating .fa").on('click', function() {
 id=$(this).attr("id");
 $('#publicfeedbackvalue'+id).val($(this).data('rating'));
 return SetRatingStar(id);
 });
</code>```

get id star3 How ?

Please Help me..

答:
use this code </p>

```<code>$(".star-rating .fa").on('click', function() {
    var parentId = $(this).parents('.star-rating').attr('id')

 });
</code>```

Title: How to Get Id in javascript?

Body:
How to Get id form this codein javascript/Jquery

 <input name="whatever1" id="publicfeedbackvaluestar1"  class="rating-value"
  value="4" type="hidden">

 <input name="whatever2" id="publicfeedbackvaluestar2"  class="rating-value"
  value="4" type="hidden">

 <input name="whatever3" id="publicfeedbackvaluestar3"  class="rating-value"
  value="4" type="hidden">

How to store clicking rating value in text box ..
my jquery code

  $(".star-rating .fa").on('click', function() {
 id=$(this).attr("id");
 $('#publicfeedbackvalue'+id).val($(this).data('rating'));
 return SetRatingStar(id);
 });

get id star3 How ?

Please Help me..

Body:
use this code

$(".star-rating .fa").on('click', function() {
    var parentId = $(this).parents('.star-rating').attr('id')

 });


答:
Check out stackoverflow answer:

The implementation of clone() in Object checks if the actual class
  implements Cloneable, and creates an instance of that actual class.

So if you want to make your class cloneable, you have to implement
  Cloneable and downcast the result of super.clone() to your class.
  Another burden is that the call to super.clone() can throw a
  CloneNotSupportedException that you have to catch, even though you
  know it won't happen (since your class implements Cloneable).

The Cloneable interface and the clone method on the Object class are
  an obvious case of object-oriented design gone wrong.

Title: Why cant we use clone method in class without implementing clonable as even though base class object has "clone()" method?