问:
How to do while loop/Do while loop with sentinel value with switch
Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.</p>
```<code>    // declare variables

    char deptCode = ' ';
    int count = 0;
    double markVal, sum = 0, average = 0.0;

    {
        Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
        deptCode = Convert.ToChar(Console.ReadLine());
        while (char.ToUpper(deptCode) != 'Q')

            do
            {
                Console.Write("Enter a mark between 0 and 100 => ");
                markVal = Convert.ToDouble(Console.ReadLine());

                {
            Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
            deptCode = Convert.ToChar(Console.ReadLine());
        } while (markVal >= 0 && markVal <= 100);

        count++;

        average = (double)sum / count;

        Console.WriteLine("***Error, Please Enter Valid Mark");

        Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
        Console.WriteLine("The Average mark for Biology Students is {0}", average);
        Console.WriteLine("The Average mark for Physics Students is {0}", average);

        Console.ReadLine();

        {

</code>```

答:
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.

One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.

An endless loop that lets the user enter any number of discipline marks.

An endless loop when we ask the user which discipline to use

And an endless loop when we ask the user for a Mark between 0 and 100

When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.

And finally when the user presses the ‘q’ character, then we can output the averages.

So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’…  and it may look something like…

```<code>private static char GetDisciplineFromUser() {
  string userInput;
  while (true) {
    Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
    userInput = Console.ReadLine().ToLower();
    if (userInput.Length > 0) {
      if (userInput[0] == 'c' || userInput[0] == 'b' ||
        userInput[0] == 'p' || userInput[0] == 'q') {
        return userInput[0];
      }
    }
    Console.WriteLine("Invalid discipline => " + userInput + " try again.");
  }
}
</code>```

Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.

Next is the endless loop to get the Mark from the user and may look something like…

```<code>private static double GetMarkFromUser() {
  string userInput;
  while (true) {
    Console.WriteLine("Enter a mark between 0 and 100 => ");
    userInput = Console.ReadLine().Trim();
    if (double.TryParse(userInput, out double mark)) {
      if (mark >= 0 && mark <= 100) {
        return mark;
      }
    }
    Console.WriteLine("Invalid Mark => " + userInput + " try again.");
  }
}
</code>```

Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.

These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…

```<code>int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
</code>```

Now you have something to store the users input in.

And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.

```<code>static void Main(string[] args) {
  //  you will need some kind of storage for each discipline.. see above...
  char currentDiscipline = 'x';
  double currentMark;
  while (currentDiscipline != 'q') {
    currentDiscipline = GetDisciplineFromUser();
    if (currentDiscipline != 'q') {
      currentMark = GetMarkFromUser();
      switch (currentDiscipline) {
        case 'c':
          // add 1 to total number of CS marks
          // add currentMarkValue to the total of CS marks
          break;
        case 'b':
          // add 1 to total number of Biology marks
          // add currentMarkValue to the total of Biology marks
          break;
        default: // <- we know for sure that only p could be left
          // add 1 to total number of Physics marks
          // add currentMarkValue to the total of Physics marks
          break;
      }
    }
  }
  Console.WriteLine("Averages ------");
  //Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
  //Console.WriteLine("The Average mark for Biology Students is {0}", ...);
  //Console.WriteLine("The Average mark for Physics Students is {0}", ...);
  Console.ReadLine();
}
</code>```

Body:
Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.

    // declare variables

    char deptCode = ' ';
    int count = 0;
    double markVal, sum = 0, average = 0.0;

    {
        Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
        deptCode = Convert.ToChar(Console.ReadLine());
        while (char.ToUpper(deptCode) != 'Q')

            do
            {
                Console.Write("Enter a mark between 0 and 100 => ");
                markVal = Convert.ToDouble(Console.ReadLine());

                {
            Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
            deptCode = Convert.ToChar(Console.ReadLine());
        } while (markVal >= 0 && markVal <= 100);

        count++;

        average = (double)sum / count;

        Console.WriteLine("***Error, Please Enter Valid Mark");

        Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
        Console.WriteLine("The Average mark for Biology Students is {0}", average);
        Console.WriteLine("The Average mark for Physics Students is {0}", average);

        Console.ReadLine();

        {

Body:
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.

One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.

An endless loop that lets the user enter any number of discipline marks.

An endless loop when we ask the user which discipline to use

And an endless loop when we ask the user for a Mark between 0 and 100

When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.

And finally when the user presses the ‘q’ character, then we can output the averages.

So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’…  and it may look something like…

private static char GetDisciplineFromUser() {
  string userInput;
  while (true) {
    Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
    userInput = Console.ReadLine().ToLower();
    if (userInput.Length > 0) {
      if (userInput[0] == 'c' || userInput[0] == 'b' ||
        userInput[0] == 'p' || userInput[0] == 'q') {
        return userInput[0];
      }
    }
    Console.WriteLine("Invalid discipline => " + userInput + " try again.");
  }
}

Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.

Next is the endless loop to get the Mark from the user and may look something like…

private static double GetMarkFromUser() {
  string userInput;
  while (true) {
    Console.WriteLine("Enter a mark between 0 and 100 => ");
    userInput = Console.ReadLine().Trim();
    if (double.TryParse(userInput, out double mark)) {
      if (mark >= 0 && mark <= 100) {
        return mark;
      }
    }
    Console.WriteLine("Invalid Mark => " + userInput + " try again.");
  }
}

Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.

These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…

int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;

Now you have something to store the users input in.

And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.

static void Main(string[] args) {
  //  you will need some kind of storage for each discipline.. see above...
  char currentDiscipline = 'x';
  double currentMark;
  while (currentDiscipline != 'q') {
    currentDiscipline = GetDisciplineFromUser();
    if (currentDiscipline != 'q') {
      currentMark = GetMarkFromUser();
      switch (currentDiscipline) {
        case 'c':
          // add 1 to total number of CS marks
          // add currentMarkValue to the total of CS marks
          break;
        case 'b':
          // add 1 to total number of Biology marks
          // add currentMarkValue to the total of Biology marks
          break;
        default: // <- we know for sure that only p could be left
          // add 1 to total number of Physics marks
          // add currentMarkValue to the total of Physics marks
          break;
      }
    }
  }
  Console.WriteLine("Averages ------");
  //Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
  //Console.WriteLine("The Average mark for Biology Students is {0}", ...);
  //Console.WriteLine("The Average mark for Physics Students is {0}", ...);
  Console.ReadLine();
}


来源: stackexchange

问:
Node.js event loop's phase speciality
I'm learning event loop of nodejs.

I have some of question after reading in document.

Each phase has a FIFO queue of callbacks to execute. While each
phase is special in its own way, generally, when the event loop
enters a given phase, it will perform any operations specific to that
phase, then execute callbacks in that phase's queue until the queue
has been exhausted or the maximum number of callbacks has executed.

What is meaning of "each phase is special in its own way"?

Is it means running mechanism, structure or resposibility?

答:
What is meaning of "each phase is special in its own way"?

Each phase has its own job to do and some work pretty differently than others.  For example:

The timers phase checks the head of a sorted linked list of pending timers and calls any callbacks for timers in that list whose time has arrived.

The poll phase calls the OS to get any pending operations such as incoming network activity.

The pending callbacks phase is a FIFO queue of certain types of system events that don't fit into other phases.

Each of these phases has a similar high-level function (retrieve and process a specific type of events who are ready to run), but all work completely differently inside (thus are special in its own way).

ContentLicense: CC BY-SA 4.0

Title: Node.js event loop's phase speciality


问:
What reason is there to use null instead of undefined in JavaScript?
I've been writing JavaScript for quite a long time now, and I have never had a reason to use null. It seems that undefined is always preferable and serves the same purpose programmatically. What are some practical reasons to use null instead of undefined?

答: To write simple code you need to keep complexity and variation down. When a variable or a property on an object does not have a value it is undefined , and for a value to be null you need to assign it a null value.</p>

ContentLicense: CC BY-SA 3.0


问:
Fatal error: Call to undefined method stdClass::My()
I am getting this error when I call for the function My() for the second time. The first time (when I'm calling for the user_id) everything seems to be fine.. Stripped down code:

```<code>class User {
    function My($field) {
        global $user;
        global $db;
        global $sessions;

        if ($sessions == 2) {
            $user = $db->Row("SELECT * FROM users WHERE username='".$_SESSION['username']."'");
            return $user->$field;
        }
    }
}

$user = new User;

class Index {
    function Startup() {
        global $user;

        $user_id = $user->My("user_id");
        $name = $user->My("firstname")." ".$user->My("surname");
    }
}
</code>```

Any suggestions would be greatly appreciated.

答:
Sorry my first answer was incorrect!

Because you define $user global in both My() and Startup() you are reffering to the same data in both contexts.

The frist time everything is fine because $user has been initialized to a user object somewhere in your code. But the $db->Row() method inside your My() function changes the global $user to an stdClass which has no My() opreation.

Solution: remove the word global before $user in My()

Body:
I am getting this error when I call for the function My() for the second time. The first time (when I'm calling for the user_id) everything seems to be fine.. Stripped down code:

class User {
    function My($field) {
        global $user;
        global $db;
        global $sessions;

        if ($sessions == 2) {
            $user = $db->Row("SELECT * FROM users WHERE username='".$_SESSION['username']."'");
            return $user->$field;
        }
    }
}

$user = new User;

class Index {
    function Startup() {
        global $user;

        $user_id = $user->My("user_id");
        $name = $user->My("firstname")." ".$user->My("surname");
    }
}

Any suggestions would be greatly appreciated.


问:
pyAgrum - printing and plotting
I'm just starting to learn pyAgrum. I am looking for functions to both plot a network and print the tables/potentials within a python session. I.e., I'm looking to do this without the need for any sort of HTML-based interpreter (pylab, etc.). I'm coming from the R-world, where I'm used to this kind of workflow using R's version of igraph e.g., and where tables can be printed as ordinary R-arrays. I know, that pyAgrum::Potential's are lower-level C++ classes but is there a way to achieve the above? I like to stay in my editor :)</p>

答:
I already answered you somewhere else :-) but for the sake of the other readers :

to print an ascii version of a table, you can just use the __str__() methods. Hence print(p) where pis a Potential will do the job.

to export an image of a BN,  you can use pyAgrum.lib.image :

import pyAgrum
import pyAgrum.lib.image as gimg

bn=gum.fastBN("A->B->C")

gimg.export(bn,"test.pdf")
gimg.exportInference(bn,"test.png",evs={"A":1})
```

will export test.pdf containing the graph and test.png containing the (graphical) result of an inference.

Title: pyAgrum - printing and plotting

Body:
I already answered you somewhere else :-) but for the sake of the other readers :

to print an ascii version of a table, you can just use the __str__() methods. Hence print(p) where pis a Potential will do the job.

to export an image of a BN,  you can use pyAgrum.lib.image :

import pyAgrum
import pyAgrum.lib.image as gimg

bn=gum.fastBN("A->B->C")

gimg.export(bn,"test.pdf")
gimg.exportInference(bn,"test.png",evs={"A":1})

will export test.pdf containing the graph and test.png containing the (graphical) result of an inference.


问:
PyArrow setting column types with Table.from_pydict (schema)
With a PyArrow table created as pyarrow.Table.from_pydict(d) all columns are string types.

Creating a schema object as below [1], and using it as pyarrow.Table.from_pydict(d, schema=s) results in errors such as:

```<code>pyarrow.lib.ArrowTypeError: object of type <class 'str'> cannot be converted to int
</code>```

Is there a means to set column types in tables created from dictionaries? Context is writing to Parquet files. A similar approach in Pandas is df.astype(schema).dtypes.

[1]

```<code>schema = pa.schema([
  ('id', pa.int32()),
  ('message_id', pa.string()),
  ('transaction_id', pa.string()),
])
</code>```

答: The correct approach seems to be pyarrow.Table.from_pydict(d).cast(schema)

Body:
With a PyArrow table created as pyarrow.Table.from_pydict(d) all columns are string types.

Creating a schema object as below [1], and using it as pyarrow.Table.from_pydict(d, schema=s) results in errors such as:

pyarrow.lib.ArrowTypeError: object of type <class 'str'> cannot be converted to int

Is there a means to set column types in tables created from dictionaries? Context is writing to Parquet files. A similar approach in Pandas is df.astype(schema).dtypes.

[1]

schema = pa.schema([
  ('id', pa.int32()),
  ('message_id', pa.string()),
  ('transaction_id', pa.string()),
])


问:
How can I get the initial communalities for an exploratory factor analysis in R?
I would like to obtain the initial communalities for an exploratory factor analysis in R
(that is, the R squared of each item when predicted by the other items included in the analysis).

Is there a way to do this with either jmv::efa or psych::fa  ?

I only see the uniqueness, which informs me of the communalities AFTER factor extraction (1-uniqueness)...

Thank you for your consideration : )

Body:
Dataset

Here is the dput for the data I am using, hereafter called hwk:

hwk <- structure(list(V1 = structure(c(4, 4, 2, 2, 2, 2, 2, 2, 4, 4,
2, 3, 2, 3, 4, 2, 2, 2, 3, 3, 2, 3, 1, 3, 3, 3, 3, 4, 1, 2, 4,
1, 2, 3, 2, 3, 1, 1, 2, 2, 4, 3, 2, 1, 2, 3, 3, 4, 3, 3, 2, 3,
1, 4, 3, 2, 3, 4, 1, 3, 3, 3, 2, 2, 1, 2, 3, 4, 4, 2, 4, 3, 2,
3, 3, 3, 3, 2, 4, 3, 3, 3, 2, 2, 3, 4, 2, 4, 4, 2, 2, 3, 3), format.spss = "F8.0"),
    V2 = structure(c(4, 4, 3, 4, 3, 4, 3, 2, 4, 1, 3, 3, 3, 4,
    3, 3, 2, 3, 4, 3, 1, 4, 2, 3, 4, 2, 4, 3, 3, 2, 3, 2, 3,
    3, 4, 3, 3, 3, 3, 3, 3, 2, 4, 2, 2, 2, 4, 3, 4, 4, 2, 4,
    2, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 4, 4, 4,
    3, 4, 3, 3, 3, 4, 2, 4, 3, 4, 3, 3, 2, 3, 3, 4, 3, 4, 3,
    4, 4, 3), format.spss = "F8.0"), V3 = structure(c(4, 4, 4,
    4, 4, 4, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4), format.spss = "F8.0"),
    V4 = structure(c(4, 4, 3, 4, 3, 4, 2, 1, 3, 2, 3, 1, 4, 4,
    2, 3, 2, 2, 2, 4, 1, 2, 2, 2, 3, 2, 3, 2, 2, 1, 3, 1, 1,
    2, 4, 1, 1, 2, 3, 2, 2, 1, 1, 1, 3, 2, 4, 3, 3, 3, 3, 3,
    3, 4, 3, 1, 4, 3, 4, 3, 2, 3, 2, 1, 4, 1, 4, 1, 2, 4, 4,
    4, 3, 3, 3, 2, 2, 1, 4, 3, 2, 3, 2, 1, 3, 4, 1, 2, 4, 3,
    4, 2, 2), format.spss = "F8.0"), V5 = structure(c(3, 3, 3,
    4, 3, 4, 3, 1, 1, 1, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, 2,
    2, 2, 2, 4, 2, 3, 2, 3, 4, 1, 4, 2, 3, 3, 2, 2, 3, 2, 2,
    3, 3, 2, 3, 3, 3, 2, 2, 2, 3, 2, 3, 3, 2, 2, 3, 3, 2, 3,
    2, 2, 3, 3, 3, 2, 3, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 3, 4,
    3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 4, 3, 3), format.spss = "F8.0"),
    V6 = structure(c(4, 4, 3, 4, 3, 4, 4, 1, 3, 3, 3, 3, 2, 3,
    4, 2, 4, 3, 3, 3, 3, 4, 4, 3, 3, 3, 4, 4, 4, 3, 4, 4, 3,
    3, 3, 4, 2, 2, 3, 3, 3, 4, 2, 4, 3, 4, 4, 4, 3, 4, 2, 4,
    3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 1, 4, 4, 4, 4, 4, 4,
    4, 3, 4, 4, 4, 4, 2, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 3,
    4, 4, 4), format.spss = "F8.0"), V7 = structure(c(4, 4, 2,
    4, 2, 4, 4, 3, 3, 3, 2, 2, 4, 4, 3, 3, 1, 4, 3, 3, 1, 2,
    4, 3, 4, 2, 4, 4, 3, 3, 2, 2, 3, 2, 4, 3, 3, 3, 3, 3, 3,
    1, 4, 3, 2, 2, 4, 3, 4, 4, 2, 4, 2, 3, 4, 3, 3, 3, 4, 3,
    4, 4, 3, 4, 4, 3, 4, 4, 4, 4, 3, 4, 4, 4, 3, 3, 4, 3, 4,
    3, 3, 3, 3, 2, 2, 4, 4, 4, 4, 2, 4, 4, 3), format.spss = "F8.0"),
    V8 = structure(c(4, 4, 2, 1, 2, 1, 1, 1, 3, 3, 2, 3, 2, 3,
    4, 2, 2, 2, 3, 3, 2, 3, 1, 3, 3, 3, 3, 4, 1, 2, 4, 1, 2,
    3, 2, 3, 1, 1, 2, 2, 3, 1, 1, 1, 2, 3, 3, 4, 3, 3, 2, 3,
    1, 3, 4, 2, 3, 4, 1, 3, 3, 3, 2, 2, 1, 2, 3, 4, 4, 2, 4,
    3, 4, 4, 4, 4, 3, 2, 4, 3, 3, 3, 2, 2, 3, 4, 2, 4, 4, 2,
    1, 3, 4), format.spss = "F8.0"), V9 = structure(c(4, 4, 4,
    4, 4, 4, 4, 4, 3, 3, 2, 3, 3, 3, 3, 2, 3, 3, 2, 3, 4, 4,
    4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 4, 3, 2, 4, 3, 4,
    4, 4, 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 4, 3, 4, 3, 2, 4,
    3, 3, 4, 4, 4, 3, 4, 4, 4, 4, 4, 3, 4, 3, 4, 3, 4, 4, 4,
    4, 3, 4, 4, 4, 4, 4, 3, 2, 4, 4, 4, 4, 4), format.spss = "F8.0"),
    V10 = structure(c(4, 4, 2, 4, 2, 4, 3, 2, 3, 3, 3, 2, 4,
    4, 2, 2, 1, 3, 4, 4, 1, 4, 2, 3, 3, 2, 4, 3, 2, 3, 3, 1,
    3, 2, 4, 3, 2, 3, 3, 3, 3, 1, 2, 4, 2, 3, 4, 4, 3, 3, 2,
    4, 2, 4, 3, 3, 4, 3, 4, 3, 4, 4, 4, 1, 4, 3, 3, 4, 3, 4,
    4, 3, 3, 3, 3, 3, 4, 1, 4, 3, 3, 3, 3, 2, 3, 4, 4, 2, 4,
    2, 4, 4, 3), format.spss = "F8.0"), V11 = structure(c(3,
    3, 1, 4, 1, 4, 1, 1, 1, 1, 2, 1, 1, 1, 3, 2, 2, 2, 2, 1,
    2, 3, 1, 2, 3, 3, 2, 1, 2, 2, 2, 3, 2, 2, 3, 2, 1, 2, 2,
    1, 1, 4, 3, 1, 3, 2, 3, 1, 2, 1, 2, 1, 2, 2, 1, 2, 2, 3,
    2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 4, 2, 1, 2, 2, 3, 3, 3,
    3, 4, 3, 2, 3, 3, 2, 2, 2, 2, 1, 3, 1, 4, 1, 3), format.spss = "F8.0"),
    V12 = structure(c(4, 4, 3, 2, 3, 2, 3, 1, 3, 3, 3, 3, 2,
    3, 3, 2, 4, 3, 3, 4, 4, 3, 3, 4, 4, 3, 3, 3, 4, 3, 4, 4,
    3, 3, 3, 4, 2, 2, 3, 3, 3, 4, 2, 4, 3, 4, 4, 4, 3, 4, 2,
    4, 3, 3, 3, 3, 4, 3, 3, 2, 2, 1, 1, 3, 1, 4, 4, 4, 4, 4,
    4, 4, 3, 3, 2, 2, 2, 2, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
    3, 2, 3, 4), format.spss = "F8.0")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -93L))

EFA

I did some research after my initial answer and it appears that there is a package for this called EFA Tools. There is a function called EFA that allows you to specify that you want the initial communalities. First, run the library and the EFA itself below:

# Load EFA Tools library:
library(EFAtools)

# Run EFA:
hwkfa <- EFA(hwk,
    n_factors = 3,
    start_method = "psych",
    method = "PAF",
    rotation = "promax",
    init_comm = "smc", # selected initial communalities
    type = "SPSS")

Obtaining initial communalities:

Then from there you can simply select the initial communalities by using the following code:

hwkfa$h2_init

Which gives you the following vector of output:

       V1        V2        V3        V4        V5        V6        V7
0.8034001 0.5583605 0.5487691 0.3255253 0.5685402 0.4643686 0.5227481
       V8        V9       V10       V11       V12
0.8050573 0.3474202 0.5564858 0.3496354 0.3783390

I ran the same thing in SPSS and got matching values:


问:
Over Clause getting syntax errors in sql
As got the answer from How to combine two sql queries to get a one table in mysql? here I have a database as follows and I need the output as below.

```<code>Time         Number  Updated
2/10/2022 10:12 12345     1
2/11/2022 10:12 234       0
2/12/2022 10:12 433       0
2/13/2022 10:12 556       0
2/14/2022 10:12 4357      0
2/15/2022 10:12 12345     0
</code>```

output:

```<code>Time            Number  Updated    Last Updated
2/10/2022 10:12 12345     1      2/15/2022 10:12
2/11/2022 10:12 234       0      2/11/2022 10:12
2/12/2022 10:12 433       0      2/12/2022 10:12
2/13/2022 10:12 556       0      2/13/2022 10:12
2/14/2022 10:12 4357      0      2/14/2022 10:12
2/15/2022 10:12 12345     0      2/15/2022 10:12
</code>```

We can get the output by using following query,

```<code>SELECT
    Time,
    Number,
    MAX(Time) OVER (PARTITION BY Number) AS LastUpdated
FROM yourTable
ORDER BY Time;
</code>```

This works fine when I have used it in my localhost with php file. But when I am using this same query in my remote server I am getting syntax error as,

```<code>ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(partition by....
</code>```

Seems my mysql version in remote server(mysql  Ver 14.14 Distrib 5.1.73) doesn't support that. Can someone provide alternative way to do this same?

答:
If your MySQL version didn't support window function, You can try to use subquery with MAX to make it.

Query #1

```<code>SELECT
    Time,
    Number,
    (SELECT MAX(Time) FROM yourTable tt WHERE t.Number = tt.Number) LastUpdated
FROM yourTable t
ORDER BY Time;
</code>```

or use ORDER BY with LIMIT to get the lastest each Number

```<code>SELECT
    Time,
    Number,
    (SELECT Time FROM yourTable tt WHERE t.Number = tt.Number ORDER BY Time DESC LIMIT 1) LastUpdated
FROM yourTable t
ORDER BY Time;
</code>```

Time
Number
LastUpdated

2022-02-10 10:12:00
12345
2022-02-15 10:12:00

2022-02-11 10:12:00
234
2022-02-11 10:12:00

2022-02-12 10:12:00
433
2022-02-12 10:12:00

2022-02-13 10:12:00
556
2022-02-13 10:12:00

2022-02-14 10:12:00
4357
2022-02-14 10:12:00

2022-02-15 10:12:00
12345
2022-02-15 10:12:00

Body:
As got the answer from How to combine two sql queries to get a one table in mysql? here I have a database as follows and I need the output as below.

Time         Number  Updated
2/10/2022 10:12 12345     1
2/11/2022 10:12 234       0
2/12/2022 10:12 433       0
2/13/2022 10:12 556       0
2/14/2022 10:12 4357      0
2/15/2022 10:12 12345     0

output:

Time            Number  Updated    Last Updated
2/10/2022 10:12 12345     1      2/15/2022 10:12
2/11/2022 10:12 234       0      2/11/2022 10:12
2/12/2022 10:12 433       0      2/12/2022 10:12
2/13/2022 10:12 556       0      2/13/2022 10:12
2/14/2022 10:12 4357      0      2/14/2022 10:12
2/15/2022 10:12 12345     0      2/15/2022 10:12

We can get the output by using following query,

SELECT
    Time,
    Number,
    MAX(Time) OVER (PARTITION BY Number) AS LastUpdated
FROM yourTable
ORDER BY Time;

This works fine when I have used it in my localhost with php file. But when I am using this same query in my remote server I am getting syntax error as,

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(partition by....

Seems my mysql version in remote server(mysql  Ver 14.14 Distrib 5.1.73) doesn't support that. Can someone provide alternative way to do this same?

Body:
If your MySQL version didn't support window function, You can try to use subquery with MAX to make it.

Query #1

SELECT
    Time,
    Number,
    (SELECT MAX(Time) FROM yourTable tt WHERE t.Number = tt.Number) LastUpdated
FROM yourTable t
ORDER BY Time;

or use ORDER BY with LIMIT to get the lastest each Number

SELECT
    Time,
    Number,
    (SELECT Time FROM yourTable tt WHERE t.Number = tt.Number ORDER BY Time DESC LIMIT 1) LastUpdated
FROM yourTable t
ORDER BY Time;

Time
Number
LastUpdated

2022-02-10 10:12:00
12345
2022-02-15 10:12:00

2022-02-11 10:12:00
234
2022-02-11 10:12:00

2022-02-12 10:12:00
433
2022-02-12 10:12:00

2022-02-13 10:12:00
556
2022-02-13 10:12:00

2022-02-14 10:12:00
4357
2022-02-14 10:12:00

2022-02-15 10:12:00
12345
2022-02-15 10:12:00


问:
INSERT INTO Datediff column based on conditions
I have a table in Hive with columns:

```<code>COL_NAME
patient_num       int
proc_start_date   string
proc_end_date     string
lab               string
lab_start_date    string
lab_val           double
units             string
</code>```

I want to add a Datediff column that returns days before in case of labs taken before the procedure (proc_start_date), and days after of labs taken after end of the procedure (proc_end_date).

```<code>INSERT INTO TABLE t2 SELECT t.*
datediff(lab_start_date, proc_start_date) WHERE lab_start_date < proc_start_date
datediff(lab_start_date, proc_end_date) WHERE lab_start_date > proc_start_date
FROM t2
</code>```

Could you advise on editing my syntax or using different functions? Thanks in advance

答:
You can use case when.

```<code>
SELECT t.*,
Case when lab_start_date < proc_start_date then datediff(lab_start_date, proc_start_date)
when lab_start_date > proc_start_date then
datediff(lab_start_date, proc_end_date)
End dadediff_col
FROM t2 t

</code>```

Body:
I have a table in Hive with columns:

COL_NAME
patient_num       int
proc_start_date   string
proc_end_date     string
lab               string
lab_start_date    string
lab_val           double
units             string

I want to add a Datediff column that returns days before in case of labs taken before the procedure (proc_start_date), and days after of labs taken after end of the procedure (proc_end_date).

INSERT INTO TABLE t2 SELECT t.*
datediff(lab_start_date, proc_start_date) WHERE lab_start_date < proc_start_date
datediff(lab_start_date, proc_end_date) WHERE lab_start_date > proc_start_date
FROM t2

Could you advise on editing my syntax or using different functions? Thanks in advance

Body:
You can use case when.

SELECT t.*,
Case when lab_start_date < proc_start_date then datediff(lab_start_date, proc_start_date)
when lab_start_date > proc_start_date then
datediff(lab_start_date, proc_end_date)
End dadediff_col
FROM t2 t


问:
Program skipping every second value for given integer
I am trying to create a program that when giving it an integer, it will display every second value going from 1 to the integer (i) and also from i to 1. I have it working for i to 1 but cannot seem to get it working for the forward direction</p>
```<code>def skip (i):
    for i in range(n, 0, -1):
        print(i, end = " ")
    return skip(n-2)
</code>```

答:
I think this is what you're asking for:

```<code> def skip(n):

     print("1 to n in steps of 2")
     for i in range(1, n+1, 2):
         print(i)

     print("n to 1 in steps of -2")
     for i in range(n, 0, -2):
         print(i)
</code>```

Which produces this output for inputs of 10 and 11

```<code>>>> skip(10)
1 to n in steps of 2
1
3
5
7
9
n to 1 in steps of -2
10
8
6
4
2

>>> skip(11)
1 to n in steps of 2
1
3
5
7
9
11
n to 1 in steps of -2
11
9
7
5
3
1
</code>```

Body:
I am trying to create a program that when giving it an integer, it will display every second value going from 1 to the integer (i) and also from i to 1. I have it working for i to 1 but cannot seem to get it working for the forward direction

def skip (i):
    for i in range(n, 0, -1):
        print(i, end = " ")
    return skip(n-2)

Body:
I think this is what you're asking for:

 def skip(n):

     print("1 to n in steps of 2")
     for i in range(1, n+1, 2):
         print(i)

     print("n to 1 in steps of -2")
     for i in range(n, 0, -2):
         print(i)

Which produces this output for inputs of 10 and 11

>>> skip(10)
1 to n in steps of 2
1
3
5
7
9
n to 1 in steps of -2
10
8
6
4
2

>>> skip(11)
1 to n in steps of 2
1
3
5
7
9
11
n to 1 in steps of -2
11
9
7
5
3
1


问:
variable decimal places in .Net string formatters?
Fixed decimal places is easy

```<code>String.Format("{0:F1}", 654.321);
</code>```

gives

```<code>654.3
</code>```

How do I feed the number of decimal places in as a parameter like you can in C?
So

```<code>String.Format("{0:F?}", 654.321, 2);
</code>```

gives

```<code>654.32
</code>```

I can't find what should replace the ?

答:
The string to format doesn't have to be a constant.</p>

```<code>int numberOfDecimalPlaces = 2;
string formatString = String.Concat("{0:F", numberOfDecimalPlaces, "}");
String.Format(formatString, 654.321);
</code>```

Body:
Fixed decimal places is easy

String.Format("{0:F1}", 654.321);

gives

654.3

How do I feed the number of decimal places in as a parameter like you can in C?
So

String.Format("{0:F?}", 654.321, 2);

gives

654.32

I can't find what should replace the ?

Body:
The string to format doesn't have to be a constant.

int numberOfDecimalPlaces = 2;
string formatString = String.Concat("{0:F", numberOfDecimalPlaces, "}");
String.Format(formatString, 654.321);


问:
How to declare const char* in .cpp file
There are many questions about declaring const string in .h files, this is not my case.

I need string (for serialization purposes if it is important) to use in

My current solution is

// file.cpp
static constexpr const char* const str = "some string key";

void MyClass::serialize()
{
    // using str
}

void MyClass::deserialize()
{
    // using str
}
```

Does it have any problems? (i.e. memory leaks, redefinitions, UB, side effects)?

P.S. is using #define KEY "key" could be better here (speed/memory/consistency)?

答: constexpr implies the latter const, which in turn implies the static (for a namespace-scope variable).  Aside from that redundancy, this is fine.

Title: How to declare const char* in .cpp file

Body:
There are many questions about declaring const string in .h files, this is not my case.

I need string (for serialization purposes if it is important) to use in

My current solution is

// file.cpp
static constexpr const char* const str = "some string key";

void MyClass::serialize()
{
    // using str
}

void MyClass::deserialize()
{
    // using str
}

Does it have any problems? (i.e. memory leaks, redefinitions, UB, side effects)?

P.S. is using #define KEY "key" could be better here (speed/memory/consistency)?


问:
Flutter const with const constructors
Up until today I haven't seen this dart code suggestions. I am happy to follow best practise, but to be honest, this makes no sense showing up in a stateful widget with no constructor. I thought it might be related to the @immutable annotation, but it doesn't seem to be and the dart documentation doesn't really help.

Dart Docs
https://dart-lang.github.io/linter/lints/prefer_const_constructors.html

Code Suggestions in VSCode

```<code>Prefer const literals as parameters of constructors on @immutable classes.dart. || Prefer const with constant constructors
</code>```

Question: Is this something I need to care about or has my plugin on
VSCode gone haywire?

Code sample where this shows for all widgets.

```<code>   Column(
            children: [
              Container(
                margin: EdgeInsets.only(left: 20, right: 20),
                height: 50,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(
                    Radius.circular(30),
                  ),
                  color: Colors.black,
                ),
                child: Center(
                  child: Text(
                    'Create Account',
                    style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                        fontSize: 19),
                  ),
                ),
              ),
              SizedBox(
                height: 20,
              )
</code>```

Screen for completeness

答:
To avoid the prefer const with constant constructors warning add this rule prefer_const_constructors : false to the analysis_options.yaml file.

```<code>linter:
rules:
prefer_const_constructors : false
# avoid_print: false  # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true  # Uncomment to enable the
</code>```

Title: Flutter const with const constructors

Body:
Up until today I haven't seen this dart code suggestions. I am happy to follow best practise, but to be honest, this makes no sense showing up in a stateful widget with no constructor. I thought it might be related to the @immutable annotation, but it doesn't seem to be and the dart documentation doesn't really help.

Dart Docs
https://dart-lang.github.io/linter/lints/prefer_const_constructors.html

Code Suggestions in VSCode

Prefer const literals as parameters of constructors on @immutable classes.dart. || Prefer const with constant constructors

Question: Is this something I need to care about or has my plugin on
VSCode gone haywire?

Code sample where this shows for all widgets.

   Column(
            children: [
              Container(
                margin: EdgeInsets.only(left: 20, right: 20),
                height: 50,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(
                    Radius.circular(30),
                  ),
                  color: Colors.black,
                ),
                child: Center(
                  child: Text(
                    'Create Account',
                    style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                        fontSize: 19),
                  ),
                ),
              ),
              SizedBox(
                height: 20,
              )

Screen for completeness

Body:
To avoid the prefer const with constant constructors warning add this rule prefer_const_constructors : false to the analysis_options.yaml file.

linter:
rules:
prefer_const_constructors : false
# avoid_print: false  # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true  # Uncomment to enable the


问:
Programatically enable Screen Sharing and Remote Login on macOS Big Sur?
I'm looking for a way to programatically enable Screen Sharing and Remote Login on macOS to help with automated provisioning of new machines.

I'm running the following code in a .sh script on the new machine:

```<code>    # Enable screensharing for remote management
    sudo defaults write /var/db/launchd.db/com.apple.launchd/overrides.plist com.apple.screensharing -dict Disabled -bool false
    sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.screensharing.plist
    # Enable remote login for remote management
    sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist
</code>```

Once run, the Screen Sharing and Remote Login Services are checked as On in the System Preferences > Sharing menu

However when I initiate a screen sharing session using Connect to Server (Cmd + K in Finder) and enter an administrator password, the screen sharing connects but the remote session only sees a black screen.

The screen is displayed through the Connect to Server screen sharing session when I go to the physical machine and uncheck/check "Screen Sharing". However I would like to avoid any manual set up steps if possible.

Has anyone had luck setting up Screen Sharing and Remote Login programatically using a different command/method?

答:
Once I can ssh, I use this snippet:

```<code>sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -users localadmin -access -on -privs -all
</code>```

I can't recall where I learned it.

Body:
I'm looking for a way to programatically enable Screen Sharing and Remote Login on macOS to help with automated provisioning of new machines.

I'm running the following code in a .sh script on the new machine:

    # Enable screensharing for remote management
    sudo defaults write /var/db/launchd.db/com.apple.launchd/overrides.plist com.apple.screensharing -dict Disabled -bool false
    sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.screensharing.plist
    # Enable remote login for remote management
    sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist

Once run, the Screen Sharing and Remote Login Services are checked as On in the System Preferences > Sharing menu

However when I initiate a screen sharing session using Connect to Server (Cmd + K in Finder) and enter an administrator password, the screen sharing connects but the remote session only sees a black screen.

The screen is displayed through the Connect to Server screen sharing session when I go to the physical machine and uncheck/check "Screen Sharing". However I would like to avoid any manual set up steps if possible.

Has anyone had luck setting up Screen Sharing and Remote Login programatically using a different command/method?

Body:
Once I can ssh, I use this snippet:

sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -users localadmin -access -on -privs -all

I can't recall where I learned it.


问:
What is the := operator?
In some programming languages, I see (ex.):

```<code>x := y
</code>```

What is this := operator generally called and what does it do?

答:
:= it means "set equal to"
An assignment with syntax

v := expr
sets the value of variable «v» to the value obtained from expression «expr».

Example:
X := B Sets the Definition of X to the value of B

Title: What is the := operator?

Body:
In some programming languages, I see (ex.):

x := y

What is this := operator generally called and what does it do?


问:
site looks good on "open with Live Server" (vs code) but no CSS loading in the browser
My website looks fine when viewed with "Open with Live Server" on VS Code but looks terrible in the browser (no CSS is loading). What is going on?

I have already:

1) cleared my cache

2) checked all the links to my CSS

3) checked my divs and classes and all that

IMPORTANT: I'm using Skeleton CSS cdn AND linking to my own small bit of custom css (style.css).

For the love of God please help me.

答: I have got a same mistake. I design my website using chrome and I reduced the screen size , so when I run through vs code live server the site looks fine but the screen size is 75% but when I open through the folder it looks bad  . Text and images are scrambled, but the screen size is 100% ( actual size ). So just configure the screen size before you make site.</p>


问:
what is the difference between these two usages of wrapper function?
These two usages below seem work fine:

wrapper function without return

document.querySelector(`button`).addEventListener(`click`, delayedClickButton);

const timeout = 1000;
function delayedClickButton(evt) {
  setTimeout(
      function (){clickButton(evt)},
      timeout
    );
}

function clickButton(evt) {
  evt.target.style.color = `red`;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Click</button></code>```

wrapper function with return

document.querySelector(`button`).addEventListener(`click`, delayedClickButton);

const timeout = 1000;
function delayedClickButton(evt) {
  setTimeout(
      function (){return clickButton(evt);},
      timeout
    );
}

function clickButton(evt) {
  evt.target.style.color = `red`;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Click</button></code>```

Which one is correct when I want a click event handling function that is delayed for 1 second, and I want to access the target element in that function by using evt.target.

答:
The return statement isn't needed so the first example is better, although they both work.
returns are useful for when we want to do something with a resulting value e.g.

const myFunc = ()=>{
  return 'I returned something'
}

console.log(myFunc())```

Body:
These two usages below seem work fine:

wrapper function without return

document.querySelector(`button`).addEventListener(`click`, delayedClickButton);

const timeout = 1000;
function delayedClickButton(evt) {
  setTimeout(
      function (){clickButton(evt)},
      timeout
    );
}

function clickButton(evt) {
  evt.target.style.color = `red`;
}

<button>Click</button>

wrapper function with return

document.querySelector(`button`).addEventListener(`click`, delayedClickButton);

const timeout = 1000;
function delayedClickButton(evt) {
  setTimeout(
      function (){return clickButton(evt);},
      timeout
    );
}

function clickButton(evt) {
  evt.target.style.color = `red`;
}

<button>Click</button>

Which one is correct when I want a click event handling function that is delayed for 1 second, and I want to access the target element in that function by using evt.target.


问:
Modifying an existing CodePen Galaxy affect (Zoom out to Zoom In)
so recently I have found this awesome galaxy effect on codepen:
https://codepen.io/zeztron/pen/MPNxxR

I tried to modify the JavaScript and couldn't figure out a way to change it so instead of it feeling like Zooming out, making it to feel like Zooming in.

Can anyone help? Thank you!!

Here are the codes:

```<code><body>
  <canvas id="canvas"></canvas>
</body>
</code>```
```<code>body {
    background: black;
    height: 100%;
    min-height: 100%;
}

#canvas {
    height: 100%;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    opacity: 0;
}
</code>```
```<code>var Space = {
  init: function(){
    var self = this;
    this.config = {
      perspective: 3,
      star_color: '255, 255, 255',
      speed: 1,
      stars_count: 2
    };
    this.canvas = document.getElementById('canvas');
    this.context = canvas.getContext('2d');
    this.start();
    window.onresize = function(){
      self.start();
    };
  },

  start: function(){
    var self = this;

    this.canvas.width  = this.canvas.offsetWidth;
    this.canvas.height = this.canvas.offsetHeight;
    this.canvas_center_x = this.canvas.width / 2;
    this.canvas_center_y = this.canvas.height / 2;

    this.stars_count = this.canvas.width / this.config.stars_count;
    this.focal_length = this.canvas.width / this.config.perspective;
    this.speed = this.config.speed * this.canvas.width / 2000;

    this.stars = [];

    for(i = 0; i < this.stars_count; i++){
      this.stars.push({
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        z: Math.random() * this.canvas.width,
      });
    }

    window.cancelAnimationFrame(this.animation_frame);
    this.canvas.style.opacity = 1;

    this.cow = new Image();
    this.cow.src = 'https://gallery.yopriceville.com/var/resizes/Free-Clipart-Pictures/Fast-Food-PNG-Clipart/Hamburger_PNG_Vector_Picture.png?m=1507172108';
    this.cow.onload = function(){
      self.render();
    }
  },

  render: function(){
    var self = this;
    this.animation_frame = window.requestAnimationFrame(function(){
      self.render();
    });
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    for(var i = 0, length = this.stars.length; i < length; i += 1){
      var star = this.stars[i];
      star.z -= this.speed;
      if(star.z <= 0) {
        this.stars[i] = {
          x: Math.random() * this.canvas.width,
          y: Math.random() * this.canvas.height,
          z: this.canvas.width,
        };
      }

      var star_x = (star.x - this.canvas_center_x) * (this.focal_length / star.z) + this.canvas_center_x;
      var star_y = (star.y - this.canvas_center_y) * (this.focal_length / star.z) + this.canvas_center_y;
      var star_radius  = Math.max(0, 1.4 * (this.focal_length / star.z) / 2);
      var star_opacity = 1.2 - star.z / this.canvas.width;
      var cow_width = Math.max(0.1, 100 * (this.focal_length / star.z) / 2);

      if(star.cow){
        this.context.save();
        this.context.translate((star_x-cow_width)+(cow_width/2), (star_y-cow_width)+(cow_width/2));
        this.context.rotate(star.z/star.rotation_speed);
        this.context.translate(-((star_x-cow_width)+(cow_width/2)), -((star_y-cow_width)+(cow_width/2)));
        this.context.globalAlpha = star_opacity;
        this.context.drawImage(this.cow, 0, 0, this.cow.width, this.cow.width, star_x-cow_width, star_y-cow_width, cow_width, cow_width);
        this.context.restore();
      } else {
        this.context.fillStyle = 'rgba(' + this.config.star_color + ',' + star_opacity + ')';
        this.context.beginPath();
        this.context.arc(star_x, star_y, star_radius, 0, Math.PI * 2);
        this.context.fill();
      }
    }
  }
};

window.onload = function(){
  Space.init();
};
</code>```

答:
The z-axis of each star is decreasing from a random point inside the canvas to 0 to create a zooming-out effect. To reverse it, simply increase the z-axis, not the speed.

This is the zooming-out:

var star = this.stars[i];
star.z -= this.speed; // decreasing
if(star.z <= 0) {
    this.stars[i] = {
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        z: this.canvas.width, // reset the z-axis
    };
}
```
<p>And this is the zooming-in:</p>
<pre class="lang-js prettyprint-override"><code>star.z += this.speed; // increasing
if(star.z > this.canvas.width){
    this.stars[i] = {
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        z: Math.random() * this.canvas.width, // reset to a random point
    };
}
</code>```

You need to reset the z-axis when it reaches a certain point so that it could run infinitely.

var Space = {
  init: function(){
    var self = this;
    this.config = {
      perspective: 3,
      star_color: '255, 255, 255',
      speed: 1,
      stars_count: 2
    };
    this.canvas = document.getElementById('canvas');
    this.context = canvas.getContext('2d');
    this.start();
    window.onresize = function(){
      self.start();
    };
  },

  start: function(){
    var self = this;

    this.canvas.width  = this.canvas.offsetWidth;
    this.canvas.height = this.canvas.offsetHeight;
    this.canvas_center_x = this.canvas.width / 2;
    this.canvas_center_y = this.canvas.height / 2;

    this.stars_count = this.canvas.width / this.config.stars_count;
    this.focal_length = this.canvas.width / this.config.perspective;
    this.speed = this.config.speed * this.canvas.width / 2000;

    this.stars = [];

    for(i = 0; i < this.stars_count; i++){
      this.stars.push({
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        z: Math.random() * this.canvas.width,
      });
    }

    window.cancelAnimationFrame(this.animation_frame);
    this.canvas.style.opacity = 1;

    this.cow = new Image();
    this.cow.src = 'https://gallery.yopriceville.com/var/resizes/Free-Clipart-Pictures/Fast-Food-PNG-Clipart/Hamburger_PNG_Vector_Picture.png?m=1507172108';
    this.cow.onload = function(){
      self.render();
    }
  },

  render: function(){
    var self = this;
    this.animation_frame = window.requestAnimationFrame(function(){
      self.render();
    });
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    for(var i = 0, length = this.stars.length; i < length; i += 1){
      var star = this.stars[i];
      star.z += this.speed;
      if(star.z > this.canvas.width) {
        this.stars[i] = {
          x: Math.random() * this.canvas.width,
          y: Math.random() * this.canvas.height,
          z: Math.random() * this.canvas.width,
        };
      }

      var star_x = (star.x - this.canvas_center_x) * (this.focal_length / star.z) + this.canvas_center_x;
      var star_y = (star.y - this.canvas_center_y) * (this.focal_length / star.z) + this.canvas_center_y;
      var star_radius  = Math.max(0, 1.4 * (this.focal_length / star.z) / 2);
      var star_opacity = 1.2 - star.z / this.canvas.width;
      var cow_width = Math.max(0.1, 100 * (this.focal_length / star.z) / 2);

      if(star.cow){
        this.context.save();
        this.context.translate((star_x-cow_width)+(cow_width/2), (star_y-cow_width)+(cow_width/2));
        this.context.rotate(star.z/star.rotation_speed);
        this.context.translate(-((star_x-cow_width)+(cow_width/2)), -((star_y-cow_width)+(cow_width/2)));
        this.context.globalAlpha = star_opacity;
        this.context.drawImage(this.cow, 0, 0, this.cow.width, this.cow.width, star_x-cow_width, star_y-cow_width, cow_width, cow_width);
        this.context.restore();
      } else {
        this.context.fillStyle = 'rgba(' + this.config.star_color + ',' + star_opacity + ')';
        this.context.beginPath();
        this.context.arc(star_x, star_y, star_radius, 0, Math.PI * 2);
        this.context.fill();
      }
    }
  }
};

window.onload = function(){
  Space.init();
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background: black;
    height: 100%;
    min-height: 100%;
}

#canvas {
    height: 100%;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    opacity: 0;
}</code>```

  <canvas id="canvas"></canvas>
```

Body:
so recently I have found this awesome galaxy effect on codepen:
https://codepen.io/zeztron/pen/MPNxxR

I tried to modify the JavaScript and couldn't figure out a way to change it so instead of it feeling like Zooming out, making it to feel like Zooming in.

Can anyone help? Thank you!!

Here are the codes:

  <canvas id="canvas"></canvas>

body {
    background: black;
    height: 100%;
    min-height: 100%;
}

#canvas {
    height: 100%;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    opacity: 0;
}

var Space = {
  init: function(){
    var self = this;
    this.config = {
      perspective: 3,
      star_color: '255, 255, 255',
      speed: 1,
      stars_count: 2
    };
    this.canvas = document.getElementById('canvas');
    this.context = canvas.getContext('2d');
    this.start();
    window.onresize = function(){
      self.start();
    };
  },

  start: function(){
    var self = this;

    this.canvas.width  = this.canvas.offsetWidth;
    this.canvas.height = this.canvas.offsetHeight;
    this.canvas_center_x = this.canvas.width / 2;
    this.canvas_center_y = this.canvas.height / 2;

    this.stars_count = this.canvas.width / this.config.stars_count;
    this.focal_length = this.canvas.width / this.config.perspective;
    this.speed = this.config.speed * this.canvas.width / 2000;

    this.stars = [];

    for(i = 0; i < this.stars_count; i++){
      this.stars.push({
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        z: Math.random() * this.canvas.width,
      });
    }

    window.cancelAnimationFrame(this.animation_frame);
    this.canvas.style.opacity = 1;

    this.cow = new Image();
    this.cow.src = 'https://gallery.yopriceville.com/var/resizes/Free-Clipart-Pictures/Fast-Food-PNG-Clipart/Hamburger_PNG_Vector_Picture.png?m=1507172108';
    this.cow.onload = function(){
      self.render();
    }
  },

  render: function(){
    var self = this;
    this.animation_frame = window.requestAnimationFrame(function(){
      self.render();
    });
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    for(var i = 0, length = this.stars.length; i < length; i += 1){
      var star = this.stars[i];
      star.z -= this.speed;
      if(star.z <= 0) {
        this.stars[i] = {
          x: Math.random() * this.canvas.width,
          y: Math.random() * this.canvas.height,
          z: this.canvas.width,
        };
      }

      var star_x = (star.x - this.canvas_center_x) * (this.focal_length / star.z) + this.canvas_center_x;
      var star_y = (star.y - this.canvas_center_y) * (this.focal_length / star.z) + this.canvas_center_y;
      var star_radius  = Math.max(0, 1.4 * (this.focal_length / star.z) / 2);
      var star_opacity = 1.2 - star.z / this.canvas.width;
      var cow_width = Math.max(0.1, 100 * (this.focal_length / star.z) / 2);

      if(star.cow){
        this.context.save();
        this.context.translate((star_x-cow_width)+(cow_width/2), (star_y-cow_width)+(cow_width/2));
        this.context.rotate(star.z/star.rotation_speed);
        this.context.translate(-((star_x-cow_width)+(cow_width/2)), -((star_y-cow_width)+(cow_width/2)));
        this.context.globalAlpha = star_opacity;
        this.context.drawImage(this.cow, 0, 0, this.cow.width, this.cow.width, star_x-cow_width, star_y-cow_width, cow_width, cow_width);
        this.context.restore();
      } else {
        this.context.fillStyle = 'rgba(' + this.config.star_color + ',' + star_opacity + ')';
        this.context.beginPath();
        this.context.arc(star_x, star_y, star_radius, 0, Math.PI * 2);
        this.context.fill();
      }
    }
  }
};

window.onload = function(){
  Space.init();
};

Body:
The z-axis of each star is decreasing from a random point inside the canvas to 0 to create a zooming-out effect. To reverse it, simply increase the z-axis, not the speed.

This is the zooming-out:

var star = this.stars[i];
star.z -= this.speed; // decreasing
if(star.z <= 0) {
    this.stars[i] = {
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        z: this.canvas.width, // reset the z-axis
    };
}

And this is the zooming-in:

star.z += this.speed; // increasing
if(star.z > this.canvas.width){
    this.stars[i] = {
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        z: Math.random() * this.canvas.width, // reset to a random point
    };
}

You need to reset the z-axis when it reaches a certain point so that it could run infinitely.

var Space = {
  init: function(){
    var self = this;
    this.config = {
      perspective: 3,
      star_color: '255, 255, 255',
      speed: 1,
      stars_count: 2
    };
    this.canvas = document.getElementById('canvas');
    this.context = canvas.getContext('2d');
    this.start();
    window.onresize = function(){
      self.start();
    };
  },

  start: function(){
    var self = this;

    this.canvas.width  = this.canvas.offsetWidth;
    this.canvas.height = this.canvas.offsetHeight;
    this.canvas_center_x = this.canvas.width / 2;
    this.canvas_center_y = this.canvas.height / 2;

    this.stars_count = this.canvas.width / this.config.stars_count;
    this.focal_length = this.canvas.width / this.config.perspective;
    this.speed = this.config.speed * this.canvas.width / 2000;

    this.stars = [];

    for(i = 0; i < this.stars_count; i++){
      this.stars.push({
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        z: Math.random() * this.canvas.width,
      });
    }

    window.cancelAnimationFrame(this.animation_frame);
    this.canvas.style.opacity = 1;

    this.cow = new Image();
    this.cow.src = 'https://gallery.yopriceville.com/var/resizes/Free-Clipart-Pictures/Fast-Food-PNG-Clipart/Hamburger_PNG_Vector_Picture.png?m=1507172108';
    this.cow.onload = function(){
      self.render();
    }
  },

  render: function(){
    var self = this;
    this.animation_frame = window.requestAnimationFrame(function(){
      self.render();
    });
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    for(var i = 0, length = this.stars.length; i < length; i += 1){
      var star = this.stars[i];
      star.z += this.speed;
      if(star.z > this.canvas.width) {
        this.stars[i] = {
          x: Math.random() * this.canvas.width,
          y: Math.random() * this.canvas.height,
          z: Math.random() * this.canvas.width,
        };
      }

      var star_x = (star.x - this.canvas_center_x) * (this.focal_length / star.z) + this.canvas_center_x;
      var star_y = (star.y - this.canvas_center_y) * (this.focal_length / star.z) + this.canvas_center_y;
      var star_radius  = Math.max(0, 1.4 * (this.focal_length / star.z) / 2);
      var star_opacity = 1.2 - star.z / this.canvas.width;
      var cow_width = Math.max(0.1, 100 * (this.focal_length / star.z) / 2);

      if(star.cow){
        this.context.save();
        this.context.translate((star_x-cow_width)+(cow_width/2), (star_y-cow_width)+(cow_width/2));
        this.context.rotate(star.z/star.rotation_speed);
        this.context.translate(-((star_x-cow_width)+(cow_width/2)), -((star_y-cow_width)+(cow_width/2)));
        this.context.globalAlpha = star_opacity;
        this.context.drawImage(this.cow, 0, 0, this.cow.width, this.cow.width, star_x-cow_width, star_y-cow_width, cow_width, cow_width);
        this.context.restore();
      } else {
        this.context.fillStyle = 'rgba(' + this.config.star_color + ',' + star_opacity + ')';
        this.context.beginPath();
        this.context.arc(star_x, star_y, star_radius, 0, Math.PI * 2);
        this.context.fill();
      }
    }
  }
};

window.onload = function(){
  Space.init();
};

body {
    background: black;
    height: 100%;
    min-height: 100%;
}

#canvas {
    height: 100%;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    opacity: 0;
}

<body>
  <canvas id="canvas"></canvas>
</body>


问:
Entity Framework with non-database data source
can you use Entity Framework to expose an EDM over data contained in binary files ? or data contained in some obscure data retrieval mechanism ?</p>

答:
If you can Write an Entity Framework Data Provider for your file type, then you can use Entity Framework with it.

I can certainly say that it won't be easy though.


问:
How to add reaction to message sent from bot
My bot sends a embed into a specific channel, after that he should also add 2 reactions to his embed he sent. But i'm kinda stuck at that and searching through website wasn't successful.

```<code>if '!suggestion' in message.content:
        if "salus insured" in [y.name.lower() for y in message.author.roles]:
            channel = client.get_channel(938973763414921316)
            embedVar = discord.Embed(title="User suggestion, vote below!", color=0x03b2f8)
            embedVar.add_field(name="Suggestion", value="```"+substring+"```", inline=False)
            embedVar.add_field(name="Suggested by", value="<@{}>".format(message.author.id))
            embedVar.set_footer(text="Suggestion Poll | @Salus", icon_url="https://i.imgur.com/rwBBzGK.png")
            await channel.send(embed=embedVar)
            await message.delete()
</code>```

That's the last part of my code.

答:
You should first retain the message object of the message the bot sends with...

msg = await channel.send("whatever")
```
<p>You can then do things with that message object <code>msg</code> as you would any other message.</p>
<p>So in your case:</p>
<pre class="lang-py prettyprint-override"><code>msg.add_reaction(emoji)
</code>```

There are several helpful hints for finding different emoji (e.g. custom emoji) in this question here

Body:
My bot sends a embed into a specific channel, after that he should also add 2 reactions to his embed he sent. But i'm kinda stuck at that and searching through website wasn't successful.

if '!suggestion' in message.content:
        if "salus insured" in [y.name.lower() for y in message.author.roles]:
            channel = client.get_channel(938973763414921316)
            embedVar = discord.Embed(title="User suggestion, vote below!", color=0x03b2f8)
            embedVar.add_field(name="Suggestion", value="```"+substring+"```", inline=False)
            embedVar.add_field(name="Suggested by", value="<@{}>".format(message.author.id))
            embedVar.set_footer(text="Suggestion Poll | @Salus", icon_url="https://i.imgur.com/rwBBzGK.png")
            await channel.send(embed=embedVar)
            await message.delete()

That's the last part of my code.

Body:
You should first retain the message object of the message the bot sends with...

msg = await channel.send("whatever")

You can then do things with that message object msg as you would any other message.

So in your case:

msg.add_reaction(emoji)

There are several helpful hints for finding different emoji (e.g. custom emoji) in this question here


问:
Docker container is restarting, and I cannot stop the cycle
I created a docker container using the following docker compose file listed on the docker hub page...

```<code>version: '3.1'

services:

  redmine:
    image: redmine
    restart: always
    ports:
      - 8080:3000
    environment:
      REDMINE_DB_MYSQL: db
      REDMINE_DB_PASSWORD: example
      REDMINE_SECRET_KEY_BASE: supersecretkey

  db:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: example
      MYSQL_DATABASE: redmine
</code>```

Now it is continually crashing and restarting, and I can not figure out how to kill it permanently!

答:
Remove restart: always setting from your docker-compose file (restart:no is the default value) and use docker-compose up -d again you might see your container be stopped instead of crashing.

```<code>version: '3.1'
services:
  redmine:
    image: redmine
    ports:
      - 8080:3000
    environment:
      REDMINE_DB_MYSQL: db
      REDMINE_DB_PASSWORD: example
      REDMINE_SECRET_KEY_BASE: supersecretkey

  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: example
      MYSQL_DATABASE: redmine
</code>```

restart: always always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted.

more information you can refer restart-policy

if you want to stop all containers from docker-compose we can use docker-compose down

Body:
I created a docker container using the following docker compose file listed on the docker hub page...

version: '3.1'

services:

  redmine:
    image: redmine
    restart: always
    ports:
      - 8080:3000
    environment:
      REDMINE_DB_MYSQL: db
      REDMINE_DB_PASSWORD: example
      REDMINE_SECRET_KEY_BASE: supersecretkey

  db:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: example
      MYSQL_DATABASE: redmine

Now it is continually crashing and restarting, and I can not figure out how to kill it permanently!

Body:
Remove restart: always setting from your docker-compose file (restart:no is the default value) and use docker-compose up -d again you might see your container be stopped instead of crashing.

version: '3.1'
services:
  redmine:
    image: redmine
    ports:
      - 8080:3000
    environment:
      REDMINE_DB_MYSQL: db
      REDMINE_DB_PASSWORD: example
      REDMINE_SECRET_KEY_BASE: supersecretkey

  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: example
      MYSQL_DATABASE: redmine

restart: always always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted.

more information you can refer restart-policy

if you want to stop all containers from docker-compose we can use docker-compose down


问:
How do you allocate an std::array on the heap?
Having a bit of trouble allocating an std::array on the heap.

Here's what I've tried:

```<code>std::array<int,3> *arr1;
arr1 = new std::array<int,3>;
arr1[0] = 1;
</code>```

However, the error I get is:

error: no match for ‘operator*’ (operand type is ‘std::array’).

I've also tried:

```<code>arr1[0][0] = 1;
</code>```

which works, but so does:

```<code>arr1[5][5] = 2;
</code>```

which shouldn't work since std::array<int, 3> indicates the array size should be only 3 integers.

What am I doing wrong here?

答:
The correct syntax to access the array is *arr1 and then to index into it e.g. (*arr1)[1].

arr1[0][1] is equivalent to that, but harder to understand and any higher first index would be out-of-bounds causing undefined behavior.

[] does not do any bounds-checking, so you will not get any warning or error for e.g. (*arr1)[10]. If you do this the program will simply have undefined behavior, meaning that you will have no guarantee on how it will behave.

If you want an exception to be thrown when you index out-of-bounds use arr1->at(10) instead of (*arr1)[10].

A heap-allocated std::array is not likely to have significant benefits over just using a std::vector, but will cause you extra trouble to manage its lifetime manually.

Simply use std::vector instead, which will also allocate the memory for the elements on the heap:

```<code>std::vector<int> arr1(3);
arr1[0] = 1; // ok
arr1.at(10) = 1; // throws out-of-bounds exception
</code>```

Body:
Having a bit of trouble allocating an std::array on the heap.

Here's what I've tried:

std::array<int,3> *arr1;
arr1 = new std::array<int,3>;
arr1[0] = 1;

However, the error I get is:

error: no match for ‘operator*’ (operand type is ‘std::array’).

I've also tried:

arr1[0][0] = 1;

which works, but so does:

arr1[5][5] = 2;

which shouldn't work since std::array<int, 3> indicates the array size should be only 3 integers.

What am I doing wrong here?

Body:
The correct syntax to access the array is *arr1 and then to index into it e.g. (*arr1)[1].

arr1[0][1] is equivalent to that, but harder to understand and any higher first index would be out-of-bounds causing undefined behavior.

[] does not do any bounds-checking, so you will not get any warning or error for e.g. (*arr1)[10]. If you do this the program will simply have undefined behavior, meaning that you will have no guarantee on how it will behave.

If you want an exception to be thrown when you index out-of-bounds use arr1->at(10) instead of (*arr1)[10].

A heap-allocated std::array is not likely to have significant benefits over just using a std::vector, but will cause you extra trouble to manage its lifetime manually.

Simply use std::vector instead, which will also allocate the memory for the elements on the heap:

std::vector<int> arr1(3);
arr1[0] = 1; // ok
arr1.at(10) = 1; // throws out-of-bounds exception


问:
nginx file configuration with static folder, in Flask+Gunicorn+Nginx application
I have a Flask+Gunicorn+Nginx app, this is the settings for the sites-available file inside etc/nginx.

My problem is that the application does not load the images and the css styles, but the Flask logical theme, routes, login and others work.

The problem is with my static folder.

This is the configuration file:

```<code>server {
    listen 443 ssl;
    server_name dominio.com;

    ssl_certificate /etc/letsencrypt/live/dominio.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/dominio.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/suppliers.sock;
    }

    location /static/ {
        root /home/soporte/portal_providers/app_Portal;
        autoindex off;
    }
}

server {
    if ($host = dominio.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name dominio.com;
    return 404; # managed by Certbot
}
</code>```

Archive blueprint Flask:

```<code>auth = Blueprint('auth', __name__,template_folder='templates', static_folder='static')
</code>```

Link in the html with the image:

```<code>{% block logo %}
<img src="images/Logo--definitivo.jpg" class="menu-logo py-0 " style="z-index: auto">
{% endblock %}
</code>```

project structure
enter image description here

答:
Try root instead of alias. The (working, deployed) nginx config for an app I'm working on does

```<code>location /static/ {
    root /home/pi/app;
    autoindex off;
}
</code>```

Body:
I have a Flask+Gunicorn+Nginx app, this is the settings for the sites-available file inside etc/nginx.

My problem is that the application does not load the images and the css styles, but the Flask logical theme, routes, login and others work.

The problem is with my static folder.

This is the configuration file:

server {
    listen 443 ssl;
    server_name dominio.com;

    ssl_certificate /etc/letsencrypt/live/dominio.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/dominio.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/suppliers.sock;
    }

    location /static/ {
        root /home/soporte/portal_providers/app_Portal;
        autoindex off;
    }
}

server {
    if ($host = dominio.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name dominio.com;
    return 404; # managed by Certbot
}

Archive blueprint Flask:

auth = Blueprint('auth', __name__,template_folder='templates', static_folder='static')

Link in the html with the image:

{% block logo %}

{% endblock %}

project structure
enter image description here

Body:
Try root instead of alias. The (working, deployed) nginx config for an app I'm working on does

location /static/ {
    root /home/pi/app;
    autoindex off;
}


问:
how to add support for float16 type in array class
Why does the C/Python array class does not support float16 ?

/ I can see that other projects like numba also dont have support float16/

Is there way to add support ? if yes is it easy ?

the reason i'm asking is because if an array is too big float32 takes twice the space.
Having an option seem reasonable ! if not available there have to be some reason

It seems the intel! CPUs, does not support float16 ops naively , but support conversion ..

```<code>lscpu | grep Flags | grep f16c
</code>```

https://en.wikipedia.org/wiki/F16C

答:
what do you mean its not supported etc?</p>
```<code>a_float_16 = numpy.zeros(10, dtype=numpy.float16)
</code>```

Body:
Why does the C/Python array class does not support float16 ?

/ I can see that other projects like numba also dont have support float16/

Is there way to add support ? if yes is it easy ?

the reason i'm asking is because if an array is too big float32 takes twice the space.
Having an option seem reasonable ! if not available there have to be some reason

It seems the intel! CPUs, does not support float16 ops naively , but support conversion ..

lscpu | grep Flags | grep f16c

https://en.wikipedia.org/wiki/F16C

Body:
what do you mean its not supported etc?

a_float_16 = numpy.zeros(10, dtype=numpy.float16)


问:
Base Table or view not found SQLSTATE[42S02]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'vita_valorelondon.general_settings' doesn't exist (SQL: select active_template from general_settings limit 1)

Databse.php

```<code>  'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'vita_valorelondon'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => false,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],
</code>```

.env

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=vita_valorelondon
DB_USERNAME=root
DB_PASSWORD=
</code>```

How To Fix This ?

答: The issue is not in Database.php file or .env file. Issue is in where you call general settings model. or in general settings model.</p>

Body:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'vita_valorelondon.general_settings' doesn't exist (SQL: select active_template from general_settings limit 1)

Databse.php

  'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'vita_valorelondon'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => false,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=vita_valorelondon
DB_USERNAME=root
DB_PASSWORD=

How To Fix This ?


问:
css :not problem when body or * is specified in style
I'm learning css and trying to change background-color of all html except one div tag using :not element.

When i put like body:not(.one) it is changing background-color of whole html but not excluding the div mentioned in :not condition. Same problem if i use *:not(.one) Am i doing correct?

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">

body:not(.one)
{

background-color:blue;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="one">
this is first div
</div>
<div >
this is second div
</div>
<p>
this  is a paragraph
</p>

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

答:
The :not selector is a CCS3 feature which not many browser support. Which browser are you testing in?

If all browsers are to be supported you should probably look into a javascript/jquery solution.

Body:
I'm learning css and trying to change background-color of all html except one div tag using :not element.

When i put like body:not(.one) it is changing background-color of whole html but not excluding the div mentioned in :not condition. Same problem if i use *:not(.one) Am i doing correct?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

this is first div

this is second div

this  is a paragraph


问:
Calculated Percentile from Histogram Data Element in Anylogic
I have just started to use Anylogic / JAVA and have assembled a process flowchart with agent components. The model includes extracting Histogram Data from a number of locations throughout the flowchart. I'm aiming to get the x%th percentile value of the histogram data such that I get the variable value (in this case queue and delay) that x% of the data is less than.

The help file suggests I can specify a low and high confidence value (i.e the x%th values) I wish to compute. However, during run time, I only see a CDF being shown in the graph and the percentiles are not available. How do I extract the percentile values post-simulation to display as an output? Is there a built-in way within Anylogic to do so?

The closest thing I found was the "getCDF function where I would have to write a custom function to find the closest index that yields the target x%th value. If I have to go the route of a custom function, I started the following code

I was hoping to pass to the function the individual Histogram Data objects as an argument and be able to use the Histogram Data methods within the function body. This does not work since the methods don't get recognized. What did I do wrong? The function is supposed to take in a variable histogram data object and given a specified percentile, calculate the pro-rated index value that yield the target percentile iterating through the getCDF function.

Thank you all for the help in advance!

答:
While I cant confirm if your logic is correct there are a few basic mistakes in your code

The input argument type for histoName should be HistogramSmartData not object. That is why "the methods don't get recognized"

You can verify the type of object by using code complete - see example below how I verified that a histogram data object that I dragged from the palette is of type HistogramSmartData. After that you can lookup HistogramSmartData in the help.

You used a do while syntax for your while loop  - not how it is used in java ;-)

It is either

```<code>do {
   // Do stuff
} while (condition);
</code>```

or

```<code>while (condition) {
   // Do stuff
}
</code>```

The code below works.

PS - screenshots are awesome - but code is better - if it was not for the text recognition on iPhones I used to convert your image to text I would not have answered this question ;-)

```<code>int index = 0;
int indexStart = roundToInt(histoName.getXMin());
int indexStop = roundToInt(histoName.getXMax());
double temp1 = 0;
double temp2 = 0;
double size = histoName.getIntervalWidth();
double result;

while (temp2 < percentile) {
    index = indexStart;
    temp1 = histoName.getCDF(index);
    temp2 = histoName.getCDF(index+1);
    index++;
}

result = index * (percentile-temp1) /(temp2-temp1)+(index-1)*(temp2-percentile)/(temp2-temp1);
return result;
</code>```

Body:
While I cant confirm if your logic is correct there are a few basic mistakes in your code

The input argument type for histoName should be HistogramSmartData not object. That is why "the methods don't get recognized"

You can verify the type of object by using code complete - see example below how I verified that a histogram data object that I dragged from the palette is of type HistogramSmartData. After that you can lookup HistogramSmartData in the help.

You used a do while syntax for your while loop  - not how it is used in java ;-)

It is either

do {
   // Do stuff
} while (condition);

or

while (condition) {
   // Do stuff
}

The code below works.

PS - screenshots are awesome - but code is better - if it was not for the text recognition on iPhones I used to convert your image to text I would not have answered this question ;-)

int index = 0;
int indexStart = roundToInt(histoName.getXMin());
int indexStop = roundToInt(histoName.getXMax());
double temp1 = 0;
double temp2 = 0;
double size = histoName.getIntervalWidth();
double result;

while (temp2 < percentile) {
    index = indexStart;
    temp1 = histoName.getCDF(index);
    temp2 = histoName.getCDF(index+1);
    index++;
}

result = index * (percentile-temp1) /(temp2-temp1)+(index-1)*(temp2-percentile)/(temp2-temp1);
return result;


问:
Laravel Schedule Only Exceute Command on first Run
I create a schedule to send email everyday, but for testing if it works i make it run every minute.
here is my kernel.php

```<code>    class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\SendExpiredReminder::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
        $schedule->command('reminder:send')
        ->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
</code>```

it run every minute but reminder:send only called first time i run the schedule with php /var/www/html/artisan schedule:run >> /dev/null 2>&1
when i run php /var/www/html/artisan schedule:list it show that next due is next minute indicated the scheduler is running. What is going wrong?

答:
your crontab should be to your laravel project folder, not www folder

```<code>* * * * * cd /var/www/html/artisan && php artisan schedule:run >> /dev/null 2>&1
</code>```

note the project folder

Body:
I create a schedule to send email everyday, but for testing if it works i make it run every minute.
here is my kernel.php

    class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\SendExpiredReminder::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
        $schedule->command('reminder:send')
        ->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

it run every minute but reminder:send only called first time i run the schedule with php /var/www/html/artisan schedule:run >> /dev/null 2>&1
when i run php /var/www/html/artisan schedule:list it show that next due is next minute indicated the scheduler is running. What is going wrong?

Body:
your crontab should be to your laravel project folder, not www folder

* * * * * cd /var/www/html/artisan && php artisan schedule:run >> /dev/null 2>&1

note the project folder


问:
Error importing hydralit: "ModuleNotFoundError: No module named 'streamlit.report_thread'"
I installed Hydralit, but when I try to import I get the following error: "ModuleNotFoundError: No module named 'streamlit.report_thread'". Interestingly I can import and use hydralit_components.

Versions used:

```<code>hydralit >=1.0.9
hydralit_components >=1.0.4
streamlit >=0.89
python ==3.8.10
</code>```

Error in full:

```<code>Python 3.8.10 (default, Nov 26 2021, 20:14:08)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import hydralit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/lorena/.local/lib/python3.8/site-packages/hydralit/__init__.py", line 1, in <module>
    from hydralit.hydra_app import HydraApp
  File "/home/lorena/.local/lib/python3.8/site-packages/hydralit/hydra_app.py", line 5, in <module>
    from hydralit.sessionstate import SessionState
  File "/home/lorena/.local/lib/python3.8/site-packages/hydralit/sessionstate.py", line 1, in <module>
    import streamlit.report_thread as ReportThread
ModuleNotFoundError: No module named 'streamlit.report_thread'
</code>```

答: The solution is to update to Hydralit version 1.0.12, as the issue with Streamlit 1.40 was fixed with the last release. pip install -U hydralit should take care of this issue.

Body:
I installed Hydralit, but when I try to import I get the following error: "ModuleNotFoundError: No module named 'streamlit.report_thread'". Interestingly I can import and use hydralit_components.

Versions used:

hydralit >=1.0.9
hydralit_components >=1.0.4
streamlit >=0.89
python ==3.8.10

Error in full:

Python 3.8.10 (default, Nov 26 2021, 20:14:08)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import hydralit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/lorena/.local/lib/python3.8/site-packages/hydralit/__init__.py", line 1, in <module>
    from hydralit.hydra_app import HydraApp
  File "/home/lorena/.local/lib/python3.8/site-packages/hydralit/hydra_app.py", line 5, in <module>
    from hydralit.sessionstate import SessionState
  File "/home/lorena/.local/lib/python3.8/site-packages/hydralit/sessionstate.py", line 1, in <module>
    import streamlit.report_thread as ReportThread
ModuleNotFoundError: No module named 'streamlit.report_thread'


问:
Credential pass through for Databricks Sql
We have so far used Databricks for Data Engineering and Data Science purposes but recently have started exploring the new Databricks Sql analytics as we have a lot of SQL Analysts who also want to join the bandwagon (for some use cases).

However, the big stumbling block I have noticed is that a SQL endpoint always needs a Service Principal for Azure Data Lake Gen2 access. There is no option to just use “credential pass through “ without using a SPN.

I have tried looking up the limitations (known issues)page as well as all existing documentation but have not come across anything regarding this.

Can’t we just use a High Concurency cluster with credential pass through for data lake gen 2 (or a single user standard cluster with credential pass through) without using any spn at all (just like we do for data engineering and data science workloads)? Or at least a timeline?

This really is important in regards to fine grained security requirements in organizations for accessing Production data .

答:
You are correct, this is currently not supported.

Only ways available are as below.

I can see similar requests already shared as ideas here and here. You can post one too or reach support team for an official response.


问:
Data export using react-data-table-component export csv
I am new to React.

I am trying to export JSON data that is displayed using the 'react-data-table-component' to a CSV file.

I have followed the example from this link by copying the exact code snippet provided. Below is my code snippet and the corresponding error occurring during compilation.

```<code>import Export from "react-data-table-component"
import DataTable, { TableColumn, TableStyles } from "react-data-table-component";
import React from "react";

  ---code declarations---

  const actionsMemo = React.useMemo(() => <Export onExport={() => downloadCSV(customerList)} />, []);

  return (
    <>
      <Row>
        <Col lg={3}>
          <Box className="box" sx={{ display: 'flex', alignItems: 'flex-end' }}>

            <TextField id="input-with-sx" label="Input National ID" variant="standard" />
            <PersonSearchIcon sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
          </Box>
        </Col>
      </Row>
      <br/>
      <Row>
        <Col lg={12}>
          <div className="card mb-3">
            <div className="card-body">
              <DataTable columns={columns} data={customerList}
                pagination  customStyles={mycustomStyles} actions={actionsMemo}/>
            </div>
          </div>
        </Col>
      </Row>
    </>
  );
</code>```

Could someone help me in identifying any other modules that I may be missing in order to have an export data functionality. Thanks in advance.

答:
This is actually an import issue.

```<code>import Export from "react-data-table-component"
</code>```

In this line right here, you are importing the default export from the react-data-table-component package and assigning it to the variable Export.  The default export is the DataTable component, which does not have an onExport prop.

There is no Export component exported from the package.  What you are seeing is a locally declared (not exported) Export component which is used in their documentation.

```<code>const Export = ({ onExport }) => <Button onClick={e => onExport(e.target.value)}>Export</Button>;
</code>```

Here's the source file.  It relies on a styled Button component.  Their use of e.target.value here does not make any sense to me.

You can create your own Export component with proper TypeScript types by putting either of these in your code:

Simple version:

```<code>export const Export = ({ onExport }: { onExport: () => void }) => (
  <button onClick={() => onExport()}>Export</button>
);
</code>```

With support for any props of the HTML button (such as className and style):

```<code>type ExportProps = {
  onExport: React.MouseEventHandler<HTMLButtonElement>;
} & JSX.IntrinsicElements["button"];

export const Export = ({ onExport, ...props }: ExportProps) => (
  <button {...props} onClick={onExport}>
    Export
  </button>
);
</code>```

Body:
I am new to React.

I am trying to export JSON data that is displayed using the 'react-data-table-component' to a CSV file.

I have followed the example from this link by copying the exact code snippet provided. Below is my code snippet and the corresponding error occurring during compilation.

import Export from "react-data-table-component"
import DataTable, { TableColumn, TableStyles } from "react-data-table-component";
import React from "react";

  ---code declarations---

  const actionsMemo = React.useMemo(() => <Export onExport={() => downloadCSV(customerList)} />, []);

  return (
    <>
      <Row>
        <Col lg={3}>
          <Box className="box" sx={{ display: 'flex', alignItems: 'flex-end' }}>

            <TextField id="input-with-sx" label="Input National ID" variant="standard" />
            <PersonSearchIcon sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
          </Box>
        </Col>
      </Row>

      <Row>
        <Col lg={12}>

              <DataTable columns={columns} data={customerList}
                pagination  customStyles={mycustomStyles} actions={actionsMemo}/>

        </Col>
      </Row>
    </>
  );

Could someone help me in identifying any other modules that I may be missing in order to have an export data functionality. Thanks in advance.

Body:
This is actually an import issue.

import Export from "react-data-table-component"

In this line right here, you are importing the default export from the react-data-table-component package and assigning it to the variable Export.  The default export is the DataTable component, which does not have an onExport prop.

There is no Export component exported from the package.  What you are seeing is a locally declared (not exported) Export component which is used in their documentation.

const Export = ({ onExport }) => <Button onClick={e => onExport(e.target.value)}>Export</Button>;

Here's the source file.  It relies on a styled Button component.  Their use of e.target.value here does not make any sense to me.

You can create your own Export component with proper TypeScript types by putting either of these in your code:

Simple version:

export const Export = ({ onExport }: { onExport: () => void }) => (
  <button onClick={() => onExport()}>Export</button>
);

With support for any props of the HTML button (such as className and style):

type ExportProps = {
  onExport: React.MouseEventHandler<HTMLButtonElement>;
} & JSX.IntrinsicElements["button"];

export const Export = ({ onExport, ...props }: ExportProps) => (
  <button {...props} onClick={onExport}>
    Export
  </button>
);