问:
How would I loop this
I've modded in custom 'origins' (character classes) to a game and they do show up in-game. Then I tried to add functionality to them. When you click on a origin, you spawn in as a certain character. For example, if i choose a origin "Hank J Wimbleton" in the character creator menu, then i spawn as hank in-game. It works when it isn't in a loop, but copy and pasting the code would take too long, and make the file size bigger because theres a lot of characters in the game. I've tried to loop it but the code returns either the first character of the list or the last one. (crackpot is first and swamp zed is last).

List 'characters' contains all the characters in the game.
array named 'array' contains a character named 'arena'

Expected results:
the code should change "arena" to the character you choose when choosing origin.

my explaining skills are quite bad but i got a screenshot that i hope will clear up some questions:

Choosing The Sheriff should spawn you in as The Sheriff
The character names on the origins on the left side of the screenshots repeat because theres different versions of one character, with different armor and size. The have been named like that by the devs.

What code i tried:

```<code>   array[0].myOrigin = this.selectedOrigin.myOrigin;
            for (int j = 1; j < list.Count; j++)
            {
                if (array[0].myOrigin.FullName == list[j].FullName)
                {
                    array[0] = Char_Data.CreateCharacter(characters[j]);
                }
            }
</code>```

FullName is a string.

myOrigin is the origin that you click on.

The code works when its not in a loop:

```<code>if (array[0].myOrigin.FullName == list[5].FullName)
                    {
                        array[0] = Char_Data.CreateCharacter(characters[5]);
                    }
</code>```

and spawns you in as the character you chose.

答:
The problem with the loop is that it overwrites the value in array[0] for every match which is why you end up with the last one when using the loop. If you want it to stop after the first match use the keyword break; inside the if statement.

```<code>array[0].myOrigin = this.selectedOrigin.myOrigin;

for (int j = 1; j < list.Count; j++)
{
    if (array[0].myOrigin.FullName == list[j].FullName)
    {
        array[0] = Char_Data.CreateCharacter(characters[j]);
        break;
    }
}
</code>```

This will assign the first matching item to array[0] and then exit the loop.

Title: How would I loop this

Body:
I've modded in custom 'origins' (character classes) to a game and they do show up in-game. Then I tried to add functionality to them. When you click on a origin, you spawn in as a certain character. For example, if i choose a origin "Hank J Wimbleton" in the character creator menu, then i spawn as hank in-game. It works when it isn't in a loop, but copy and pasting the code would take too long, and make the file size bigger because theres a lot of characters in the game. I've tried to loop it but the code returns either the first character of the list or the last one. (crackpot is first and swamp zed is last).

List 'characters' contains all the characters in the game.
array named 'array' contains a character named 'arena'

Expected results:
the code should change "arena" to the character you choose when choosing origin.

my explaining skills are quite bad but i got a screenshot that i hope will clear up some questions:

Choosing The Sheriff should spawn you in as The Sheriff
The character names on the origins on the left side of the screenshots repeat because theres different versions of one character, with different armor and size. The have been named like that by the devs.

What code i tried:

   array[0].myOrigin = this.selectedOrigin.myOrigin;
            for (int j = 1; j < list.Count; j++)
            {
                if (array[0].myOrigin.FullName == list[j].FullName)
                {
                    array[0] = Char_Data.CreateCharacter(characters[j]);
                }
            }

FullName is a string.

myOrigin is the origin that you click on.

The code works when its not in a loop:

if (array[0].myOrigin.FullName == list[5].FullName)
                    {
                        array[0] = Char_Data.CreateCharacter(characters[5]);
                    }

and spawns you in as the character you chose.

Body:
The problem with the loop is that it overwrites the value in array[0] for every match which is why you end up with the last one when using the loop. If you want it to stop after the first match use the keyword break; inside the if statement.

array[0].myOrigin = this.selectedOrigin.myOrigin;

for (int j = 1; j < list.Count; j++)
{
    if (array[0].myOrigin.FullName == list[j].FullName)
    {
        array[0] = Char_Data.CreateCharacter(characters[j]);
        break;
    }
}

This will assign the first matching item to array[0] and then exit the loop.


来源: stackexchange

问:
How to insert clipboard content with a macro in Notepad++ per RegEx formula (alternative to ctrl + v) in the replace line window?
Here is an example:

```<code>Search for: test
Replace with: clipboard content
</code>```

Only static characters are added to the found. What I'm looking for could be this:

```<code>a

5
</code>```

Search:

```<code>([a-z])|([0-9])
</code>```

Replace:

```<code>\1\2
</code>```

This is to append group 2 to group 1. If there is a solution for this, the clipboard is unnecessary. The result should be the following:

```<code>a5

5
</code>```

Sense and purpose is to do it with several strings in the upper range.

```<code>a5
abc5
from5

5
</code>```

Group 2 would have to be excluded with some kind of regex command, so that the addition only takes place for group 1. There must also be a limit (lookforward) that stops at an empty line so that replace all can be used. But I don't know how such a regex code should look like.

This:

```<code>1
2
3
4
5
6
7
8
9
10

a A
b B
c C
d D
e E
</code>```

should be this:

```<code>1.*a A|a A.*1| 2.*a A|a A.*2| 3.*a A|a A.*3| 4.*a A|a A.*4| 5.*a A|a A.*5| 6.*a A|a A.*6| 7.*a A|a A.*7| 8.*a A|a A.*8| 9.*a A|a A.*9| 10.*a A|a A.*10|1.*b B|b B.*1| 2.*b B|b B.*2| 3.*b B|b B.*3| 4.*b B|b B.*4| 5.*b B|b B.*5| 6.*b B|b B.*6| 7.*b B|b B.*7| 8.*b B|b B.*8| 9.*b B|b B.*9| 10.*b B|b B.*10|1.*c C|c C.*1| 2.*c C|c C.*2| 3.*c C|c C.*3| 4.*c C|c C.*4| 5.*c C|c C.*5| 6.*c C|c C.*6| 7.*c C|c C.*7| 8.*c C|c C.*8| 9.*c C|c C.*9| 10.*c C|c C.*10|1.*d D|d D.*1| 2.*d D|d D.*2| 3.*d D|d D.*3| 4.*d D|d D.*4| 5.*d D|d D.*5| 6.*d D|d D.*6| 7.*d D|d D.*7| 8.*d D|d D.*8| 9.*d D|d D.*9| 10.*d D|d D.*10|1.*e E|e E.*1| 2.*e E|e E.*2| 3.*e E|e E.*3| 4.*e E|e E.*4| 5.*e E|e E.*5| 6.*e E|e E.*6| 7.*e E|e E.*7| 8.*e E|e E.*8| 9.*e E|e E.*9| 10.*e E|e E.*10
</code>```

答:
[edit:] If you just want to paste in text based on regex matches, you can use the below method for this too. Just follow the first part of my example, but paste in the clipboard content in the 'Replace with:' field instead of the replace text I used.

I commonly do this - if I'm understanding you correctly. It's completely possible to search on a regular expression and then replace matches with modified text that incorporates all, or parts of (groups within), the match. For instance if you want to convert a python function into a C expression:

```<code>def foo(x, y):   --->   int foo(int x, int y) {
</code>```

You can open the replace menu in Notepad++ (ctrl-H), and in the 'Find what:' field put

```<code>def\s+([\w_]+)\(([\w_]+),\s*([\w_]+)\):
</code>```

Then in the 'Replace with:' field put:

```<code>int \1\(int \2, int \3\) {
</code>```

Then use either 'Find Next' to replace one instance at a time, or if you're a risk taker, 'Replace All'... of course my expression is only limited to functions that have two parameters. I kept it simple just for demo.

ContentLicense: CC BY-SA 4.0

Body:
Here is an example:

Search for: test
Replace with: clipboard content

Only static characters are added to the found. What I'm looking for could be this:

a

5

Search:

([a-z])|([0-9])

Replace:

\1\2

This is to append group 2 to group 1. If there is a solution for this, the clipboard is unnecessary. The result should be the following:

a5

5

Sense and purpose is to do it with several strings in the upper range.

a5
abc5
from5

5

Group 2 would have to be excluded with some kind of regex command, so that the addition only takes place for group 1. There must also be a limit (lookforward) that stops at an empty line so that replace all can be used. But I don't know how such a regex code should look like.

This:

1
2
3
4
5
6
7
8
9
10

a A
b B
c C
d D
e E

should be this:

1.*a A|a A.*1| 2.*a A|a A.*2| 3.*a A|a A.*3| 4.*a A|a A.*4| 5.*a A|a A.*5| 6.*a A|a A.*6| 7.*a A|a A.*7| 8.*a A|a A.*8| 9.*a A|a A.*9| 10.*a A|a A.*10|1.*b B|b B.*1| 2.*b B|b B.*2| 3.*b B|b B.*3| 4.*b B|b B.*4| 5.*b B|b B.*5| 6.*b B|b B.*6| 7.*b B|b B.*7| 8.*b B|b B.*8| 9.*b B|b B.*9| 10.*b B|b B.*10|1.*c C|c C.*1| 2.*c C|c C.*2| 3.*c C|c C.*3| 4.*c C|c C.*4| 5.*c C|c C.*5| 6.*c C|c C.*6| 7.*c C|c C.*7| 8.*c C|c C.*8| 9.*c C|c C.*9| 10.*c C|c C.*10|1.*d D|d D.*1| 2.*d D|d D.*2| 3.*d D|d D.*3| 4.*d D|d D.*4| 5.*d D|d D.*5| 6.*d D|d D.*6| 7.*d D|d D.*7| 8.*d D|d D.*8| 9.*d D|d D.*9| 10.*d D|d D.*10|1.*e E|e E.*1| 2.*e E|e E.*2| 3.*e E|e E.*3| 4.*e E|e E.*4| 5.*e E|e E.*5| 6.*e E|e E.*6| 7.*e E|e E.*7| 8.*e E|e E.*8| 9.*e E|e E.*9| 10.*e E|e E.*10

Body:
[edit:] If you just want to paste in text based on regex matches, you can use the below method for this too. Just follow the first part of my example, but paste in the clipboard content in the 'Replace with:' field instead of the replace text I used.

I commonly do this - if I'm understanding you correctly. It's completely possible to search on a regular expression and then replace matches with modified text that incorporates all, or parts of (groups within), the match. For instance if you want to convert a python function into a C expression:

def foo(x, y):   --->   int foo(int x, int y) {

You can open the replace menu in Notepad++ (ctrl-H), and in the 'Find what:' field put

def\s+([\w_]+)\(([\w_]+),\s*([\w_]+)\):

Then in the 'Replace with:' field put:

int \1\(int \2, int \3\) {

Then use either 'Find Next' to replace one instance at a time, or if you're a risk taker, 'Replace All'... of course my expression is only limited to functions that have two parameters. I kept it simple just for demo.


问:
How to implement api login in laravel when I already have web login
I have implemented a web logging system in Laravel, there are already users who use this system, but I want those users to also be able to log in to a mobile app so I need to build the login in the API. How could I do it? Could you use the web login?</p>

答:
Api login is different from web ones .
In api authetication usually use token but web authentication use session.

You can define web authentication and parallel define apis with token . Just in each login you should create api token after authenticate user and return this token to user for other request .


问:
How to get rid of anomalies using lapply in R
I have a list of data frames and I am trying to use lapply to get rid of anomalies in my data, trying to make the code as robust as possible as the data inputted will be constantly different.

I am trying to use:

```<code>newdata <- lapply(ChaseSubSet, function(){
  anomalies <- 0.02 > ChaseSubSet[,1] > 0.03
  anomalies = na
})
</code>```

However a) this doesn't work and b) I'm thinking it would be more robust to get rid of values more than 0.1 away from the mean. I would have to apply different rules to each column of the data but have it apply through all the data.frames in the list. I want to use lapply to result in a list at the end.

My data is as follows:

I would like to sort through all 13 dataframes of the list which are all like this image. I would like if there are anomalous values for value to be replaced with NA my thinking is this will create the least issues later on with different columns of different length.

I am still very new so I apologise if any of this is incorrect.

答:
If the list of dataframes is ChaseSubSet, call the lapply below the function no_anomalies. Note the argument offset that you can set if you want to remove anomalies (outliers?) more than 0.1 away from the mean value of each vector in the dataframes.

```<code>no_anomalies <- function(x, offset = 0.1, na.rm = TRUE){
  x.bar <- mean(x, na.rm = na.rm)
  away <- x < (x.bar - offset) | x > (x.bar + offset)
  is.na(x) <- which(away)
  x
}

newdata <- lapply(ChaseSubSet, function(DF){
  is_num <- sapply(DF, is.numeric)
  DF[is_num] <- lapply(DF[is_num], no_anomalies, offset = 0.1)
  DF
})
</code>```

Body:
I have a list of data frames and I am trying to use lapply to get rid of anomalies in my data, trying to make the code as robust as possible as the data inputted will be constantly different.

I am trying to use:

newdata <- lapply(ChaseSubSet, function(){
  anomalies <- 0.02 > ChaseSubSet[,1] > 0.03
  anomalies = na
})

However a) this doesn't work and b) I'm thinking it would be more robust to get rid of values more than 0.1 away from the mean. I would have to apply different rules to each column of the data but have it apply through all the data.frames in the list. I want to use lapply to result in a list at the end.

My data is as follows:

I would like to sort through all 13 dataframes of the list which are all like this image. I would like if there are anomalous values for value to be replaced with NA my thinking is this will create the least issues later on with different columns of different length.

I am still very new so I apologise if any of this is incorrect.

Body:
If the list of dataframes is ChaseSubSet, call the lapply below the function no_anomalies. Note the argument offset that you can set if you want to remove anomalies (outliers?) more than 0.1 away from the mean value of each vector in the dataframes.

no_anomalies <- function(x, offset = 0.1, na.rm = TRUE){
  x.bar <- mean(x, na.rm = na.rm)
  away <- x < (x.bar - offset) | x > (x.bar + offset)
  is.na(x) <- which(away)
  x
}

newdata <- lapply(ChaseSubSet, function(DF){
  is_num <- sapply(DF, is.numeric)
  DF[is_num] <- lapply(DF[is_num], no_anomalies, offset = 0.1)
  DF
})


问:
how to remove(toggle) 'active' classlist that is already selected
I'm struggling with removing 'active' class from a link that is already selected.

Looking at the line 20 in JavaScript. Shouldn't classLink.toggle add / remove "active" on clickedElement?
I even tried few approaches like

```<code> if (clickedElement.classList.contains('active')) {
  clickedElement.classList.remove('active');
} else {
  clickedElement.classList.add('active');
}
</code>```

but none seem to work on this particular class (works fine on any other class i add).
What am i missing?

https://jsfiddle.net/Evenclan/09sn2kd3/15/

答:
Just to answer the actual question, why toggle does not untoggle .active in your fiddle. https://jsfiddle.net/Evenclan/09sn2kd3/15/

What you are doing first, before toggling is:

```<code>for (let activeLink of activeLinks) {
  activeLink.classList.remove('active');
}
</code>```

This removes .active from all link elements. Which means that all those have no class anymore or atleast no class .active.

In the next line you toggle the class .active which was just removed:

```<code>clickedElement.classList.toggle('active');
</code>```

Thus the class gets added back (what is not there gets added, what is there gets removed).

toggle actually works fine, just your logic does not. To get the desired result you have to exclude the current clicked element from the removing of class.

```<code>for (let activeLink of activeLinks) {
  if(clickedElement !== activeLink) activeLink.classList.remove('active');
}

clickedElement.classList.toggle('active');
</code>```

https://jsfiddle.net/8jrwn3sx/

Body:
I'm struggling with removing 'active' class from a link that is already selected.

Looking at the line 20 in JavaScript. Shouldn't classLink.toggle add / remove "active" on clickedElement?
I even tried few approaches like

 if (clickedElement.classList.contains('active')) {
  clickedElement.classList.remove('active');
} else {
  clickedElement.classList.add('active');
}

but none seem to work on this particular class (works fine on any other class i add).
What am i missing?

https://jsfiddle.net/Evenclan/09sn2kd3/15/

Body:
Just to answer the actual question, why toggle does not untoggle .active in your fiddle. https://jsfiddle.net/Evenclan/09sn2kd3/15/

What you are doing first, before toggling is:

for (let activeLink of activeLinks) {
  activeLink.classList.remove('active');
}

This removes .active from all link elements. Which means that all those have no class anymore or atleast no class .active.

In the next line you toggle the class .active which was just removed:

clickedElement.classList.toggle('active');

Thus the class gets added back (what is not there gets added, what is there gets removed).

toggle actually works fine, just your logic does not. To get the desired result you have to exclude the current clicked element from the removing of class.

for (let activeLink of activeLinks) {
  if(clickedElement !== activeLink) activeLink.classList.remove('active');
}

clickedElement.classList.toggle('active');

https://jsfiddle.net/8jrwn3sx/


问:
Nothing happens when using Cypher-shell for executing scripts
I'm trying to execute a series of Cypher queries using Cypher shell according to here. I have created a file called "cypher.ex1" and placed it into import and bin folder. Here is its content:

```<code>MATCH (n) RETURN n;

MATCH (batman:Person {name: 'Bruce Wayne'}) RETURN batman;
</code>```

I'm trying to execute it using:

```<code>$neo4j-home> cat cypher.ex1 | bin/cypher-shell -u neo4j -p 123456 --format plain
</code>```

but when I run this, nothing happens and after waiting for a long time with no output, I need to press "CTRL + C" to terminate the command. Here is an screenshot of the problem:

In fact, cypher-shell works fine for one line commands, but not for scripts. What's wrong?

答:
You are trying to execute this command line:

```<code>cat cypher.ex1 | bin/cypher.shell -u neo4j - 123456
</code>```

from within the cypher.shell environment. That will not work, since cypher.shell only supports Cypher statements and a limited set of commands (use the :help command to see what is available).

The reason nothing happened for you (not even an error) is because cypher.shell did not see a colon (':') at the start of your command line, so it assumed that you were entering a Cypher statement and was waiting (forever) for the ending semicolon (';') before parsing it.

If you want to execute that exact command line, you have to execute it outside of cypher-shell (when it is not running).

However, if you really do want to perform the equivalent action from within the cypher.shell environment, you can use its :source command. For example:

```<code>:source cypher.ex1
</code>```

The default location for the source file is the "current working directory", which is the directory you were in when you launched cypher.shell. If the file is elsewhere, you can specify the relative path of the file from the current working directory as the :source argument.

Body:
I'm trying to execute a series of Cypher queries using Cypher shell according to here. I have created a file called "cypher.ex1" and placed it into import and bin folder. Here is its content:

MATCH (n) RETURN n;

MATCH (batman:Person {name: 'Bruce Wayne'}) RETURN batman;

I'm trying to execute it using:

$neo4j-home> cat cypher.ex1 | bin/cypher-shell -u neo4j -p 123456 --format plain

but when I run this, nothing happens and after waiting for a long time with no output, I need to press "CTRL + C" to terminate the command. Here is an screenshot of the problem:

In fact, cypher-shell works fine for one line commands, but not for scripts. What's wrong?

Body:
You are trying to execute this command line:

cat cypher.ex1 | bin/cypher.shell -u neo4j - 123456

from within the cypher.shell environment. That will not work, since cypher.shell only supports Cypher statements and a limited set of commands (use the :help command to see what is available).

The reason nothing happened for you (not even an error) is because cypher.shell did not see a colon (':') at the start of your command line, so it assumed that you were entering a Cypher statement and was waiting (forever) for the ending semicolon (';') before parsing it.

If you want to execute that exact command line, you have to execute it outside of cypher-shell (when it is not running).

However, if you really do want to perform the equivalent action from within the cypher.shell environment, you can use its :source command. For example:

:source cypher.ex1

The default location for the source file is the "current working directory", which is the directory you were in when you launched cypher.shell. If the file is elsewhere, you can specify the relative path of the file from the current working directory as the :source argument.


问:
how to check if an addressable asset or scene is cached after been downloaded in unity?
I'm using addressable assets to remote download a new scene from server, What I'm trying to do is to activate a play button if the addressable scene is already downloaded and in cache, and a download button if it is not in cache so that the player won't download the addressable from server every time he wants to play the scene.

I tried using Caching. IsVersionCached to check the bundle is in the cache using the bundle name but the problem here is that the name is not a good reference since in the addressable system I load the scene using Addressable. loadscene which loads the scene directly without giving any reference to the asset bundle. so the question is how to check if the scene is cached?
Here is what I tried with but it is not working since I already know that the asset bundle name won't be the good reference at least in this example.

```<code>private IEnumerator LoadRoutine()
    {

        var lastHash = PlayerPrefs.GetString(LAST_HASH);

        if (Caching.IsVersionCached(AssetBundleHavingTheScene.name, Hash128.Parse(lastHash)))
        {

            Debug.Log("The Bundle is Cached i'll launch it");

            Addressables.LoadScene(AddressableScene);

        }

        else
        {
            Debug.Log("Not Cached I'm going to download it");

            var async = Addressables.LoadScene(AddressableScene);

            while (!async.IsDone)
            {

                ProgressNumber.text = (async.PercentComplete * 100f).ToString("F0") + ("%");
                ProgressSlider.value = async.PercentComplete;

                Debug.Log(async.PercentComplete);
                yield return null;
            }

            // At this point the scene is loaded and referenced in async.Result
            Debug.Log("LOADED!");

            Scene myScene = async.Result;

        }

    }
</code>```

答:
As far as I  know, Addressable assets are automatically cached by unity and will not be downloaded twice. But you have to make sure that when you build the addressables in the unity editor, you select 'update existing build' (or similar) rather than a clean build.
But if you still want to check manually, you could use the method "Addressables.GetDownloadSizeAsync()". (Please read more about it in unity docs). </p>

<p>I hope it helps you a little bit. </p>

Body:
I'm using addressable assets to remote download a new scene from server, What I'm trying to do is to activate a play button if the addressable scene is already downloaded and in cache, and a download button if it is not in cache so that the player won't download the addressable from server every time he wants to play the scene.

I tried using Caching. IsVersionCached to check the bundle is in the cache using the bundle name but the problem here is that the name is not a good reference since in the addressable system I load the scene using Addressable. loadscene which loads the scene directly without giving any reference to the asset bundle. so the question is how to check if the scene is cached?
Here is what I tried with but it is not working since I already know that the asset bundle name won't be the good reference at least in this example.

private IEnumerator LoadRoutine()
    {

        var lastHash = PlayerPrefs.GetString(LAST_HASH);

        if (Caching.IsVersionCached(AssetBundleHavingTheScene.name, Hash128.Parse(lastHash)))
        {

            Debug.Log("The Bundle is Cached i'll launch it");

            Addressables.LoadScene(AddressableScene);

        }

        else
        {
            Debug.Log("Not Cached I'm going to download it");

            var async = Addressables.LoadScene(AddressableScene);

            while (!async.IsDone)
            {

                ProgressNumber.text = (async.PercentComplete * 100f).ToString("F0") + ("%");
                ProgressSlider.value = async.PercentComplete;

                Debug.Log(async.PercentComplete);
                yield return null;
            }

            // At this point the scene is loaded and referenced in async.Result
            Debug.Log("LOADED!");

            Scene myScene = async.Result;

        }

    }

Body:
As far as I  know, Addressable assets are automatically cached by unity and will not be downloaded twice. But you have to make sure that when you build the addressables in the unity editor, you select 'update existing build' (or similar) rather than a clean build.
But if you still want to check manually, you could use the method "Addressables.GetDownloadSizeAsync()". (Please read more about it in unity docs).

I hope it helps you a little bit.


问:
Do my VisualStudio versions have to match on Windows and Mac for Xamarin?
I'm getting started with Xamarin. I have VisualStudio 2017 installed on a Windows 10 machine. I need to develop for both Android and iOS so I'm drafting requirements for the Mac I'm going to ask my boss to buy. If I ask for a Mac running VisualStudio 2019 for Mac (so it will more easily scale when we get around to upgrading to VisualStudio 2019 in Windows), will that pair  with a Windows machine running VisualStudio 2017?</p>

答:
Yes and no. Strictly speaking only versions of the .Net framework need to match. Technically you don't even need to have a complete VS for the Mac for the connection to work.

But as the easiest way to connect is to have VS for the Mac you probably do want to match the versions.


问:
Calculated columns as axis & value
I have a bunch of calculated DAX columns that I want to show as a visual. If I use a normal bar chart I get the following image, Barchart 1, where because I do not have any fields in the axis field. The titles of each of the calculated columns are what I want the x-axis to be similar to how it is in the funnel chart below.

The funnel chart only requires the value field to be filled in and it creates the following image which is kind of what I want but it needs to be vertical similar to the last image.

This final image, Barchart 3 is what I want to achieve with my calculated columns but so far I have had no luck in figuring this out. This visual was created using a different file which is irrelevant to the project I am working on now.  I believe that if I could unpivot the calculated columns then it would create the graph I am looking for but I can't figure out how to unpivot columns that are created in DAX. Is there a way to unpivot DAX columns or a visual on the marketplace to accomplish what I am trying to do? Or would I need to create my own custom visual to accomplish this?  Other ideas/thoughts?

Sample data file

答:
I'd recommend creating a calculated table that has Month unpivoted so that you only need to put a single series on the bar chart.

For example, you can write a calculated table like this with only 7 columns:

```<code>CalcTable =
VAR ThisYear = YEAR ( MAX ( Sheet4[Start] ) )
RETURN
    ADDCOLUMNS (
        CROSSJOIN (
            SELECTCOLUMNS (
                Sheet4,
                "Project", Sheet4[Project],
                "Start", Sheet4[Start],
                "End", Sheet4[End],
                "Cost", Sheet4[Cost]
            ),
            ADDCOLUMNS (
                GENERATESERIES ( 1, 12 ),
                "Month", FORMAT ( DATE ( ThisYear, [Value], 1 ), "MMMM YYYY" )
            )
        ),
        "MonthCost", IF (
            [Value] >= MONTH ( [Start] ) && [Value] <= MONTH ( [End] ),
            DIVIDE ( [Cost], DATEDIFF ( [Start], [End], MONTH ) + 1 ),
            0
        )
    )
</code>```

This table looks like this:

And allows you to create a bar chart with Month on the axis and sum of MonthCost for the values.

Title: Calculated columns as axis & value

Body:
I'd recommend creating a calculated table that has Month unpivoted so that you only need to put a single series on the bar chart.

For example, you can write a calculated table like this with only 7 columns:

CalcTable =
VAR ThisYear = YEAR ( MAX ( Sheet4[Start] ) )
RETURN
    ADDCOLUMNS (
        CROSSJOIN (
            SELECTCOLUMNS (
                Sheet4,
                "Project", Sheet4[Project],
                "Start", Sheet4[Start],
                "End", Sheet4[End],
                "Cost", Sheet4[Cost]
            ),
            ADDCOLUMNS (
                GENERATESERIES ( 1, 12 ),
                "Month", FORMAT ( DATE ( ThisYear, [Value], 1 ), "MMMM YYYY" )
            )
        ),
        "MonthCost", IF (
            [Value] >= MONTH ( [Start] ) && [Value] <= MONTH ( [End] ),
            DIVIDE ( [Cost], DATEDIFF ( [Start], [End], MONTH ) + 1 ),
            0
        )
    )

This table looks like this:

And allows you to create a bar chart with Month on the axis and sum of MonthCost for the values.


问:
What is the difference between ".class element" and "element.class"?
Is there a difference between .class element and element.class in a CSS selector?

I had always been shown element.class but just the other day came across a CSS file at work that had .class element and wanted to know if this was just a style choice (in which case I would make my changes match), or if there was a specific reason (in which case I would not necessarily want to make my changes match).

答:
"element.class" selects elements that have the given class.

".class element" selects all elements that are children of anything with the given class.

Example:

```<code><div class="foo">
    <p>...</p>
</div>
</code>```

div.foo would select the div, while .foo p would select the child paragraph.  It should be noted that without specifying direct child via the ">" selector, this will traverse the entire document tree when looking for children.

Body:
"element.class" selects elements that have the given class.

".class element" selects all elements that are children of anything with the given class.

Example:

<div class="foo">
    <p>...</p>
</div>

div.foo would select the div, while .foo p would select the child paragraph.  It should be noted that without specifying direct child via the ">" selector, this will traverse the entire document tree when looking for children.

ContentLicense: CC BY-SA 3.0


问:
Getting today's date in YYYY-MM-DD in Python?
Is there a nicer way than the following to return today's date in the YYYY-MM-DD format?

```<code>str(datetime.datetime.today()).split()[0]
</code>```

答:
Very late answer, but you can simply use:</p>
```<code>import time
today = time.strftime("%Y-%m-%d")
# 2023-05-27
</code>```

Body:
Is there a nicer way than the following to return today's date in the YYYY-MM-DD format?

str(datetime.datetime.today()).split()[0]

Body:
Very late answer, but you can simply use:

import time
today = time.strftime("%Y-%m-%d")
# 2023-05-27


问:
C# FizzBuzz Switch Solution
Is it possible to create the FizzBuzz solution in C# with the switch construct. I've found solutions that work for JavaScript and other languages, but these (or the syntax equivalent) don't seem to be working in C#.

For reference, I'll write the if statement version down below:

```<code>for (int x = 1; x <= 15; x++)
        {
            if (x % 5 == 0 && x % 3 == 0)
                Console.WriteLine("FizzBuzz");
            else if (x % 5 == 0)
                Console.WriteLine("Buzz");
            else if (x % 3 == 0)
                Console.WriteLine("Fizz");
            else
                Console.WriteLine(x);
        }
        Console.ReadLine();
</code>```

EDIT: forgot to put my switch statement code, sorry about that:

```<code>for (x = 1; x <= 15; x++)
{
    switch (x)
    {
        case (x % 3 == 0 && x % 5 == 0):
            Console.WriteLine("FizzBuzz");
            break;
        case (x % 5 == 0):
            Console.WriteLine("Buzz");
            break;
        case (x % 3 == 0):
            Console.WriteLine("Fizz");
            break;
        default:
            Console.WriteLine(x);
            break;
    }
}
</code>```

My problem is with the modulo statements. Error is "Cannot implicitly convert type bool to int. I've tried replacing switch (x) with switch (true) but that doesn't help much, just changes the error to "A constant value is expected" for each of my cases.

答:
It is possible to write a fizzbuzz as a simple switch.

It is just about as fast as an if else. I got a bit obsessed about this and created a little benchmark which I uploaded to git: https://github.com/chrisaddams/fizzbuzz-everyway-c-sharp

The results I found for speed are as follows:

```<code>Average Speed of Switch  is             63.46 ms
Average Speed of IfElseCont is          62.03 ms
Average Speed of If Else is             60.62 ms
Average Speed of If Only is             73.35 ms
Average Speed of If Cont is             73.55 ms
</code>```

Anyway, here's the code, I think it's quite a neat and readable solution.

```<code>using System.Diagnostics;
using System;
namespace fizzbuzz
{
    class fizzyCase
    {
        static void Main(string[] args)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            for (int i = 0; i <= 10000; i++)
            {
                switch (true)
                {
                    case var FizzBuzz when (i % 15 == 0):
                        Console.WriteLine("fizzbuzz");
                        break;
                    case var Fizz when (i % 3 == 0):
                        Console.WriteLine("fizz");
                        break;
                    case var Buzz when (i % 5 == 0):
                        Console.WriteLine("buzz");
                        break;
                    default:
                        Console.WriteLine(i);
                        break;
                }
            }
            timer.Stop();
            Console.WriteLine("Elapsed:{0}milliseconds", timer.Elapsed.TotalMilliseconds);

        }
    }
}
</code>```

Title: C# FizzBuzz Switch Solution

Body:
Is it possible to create the FizzBuzz solution in C# with the switch construct. I've found solutions that work for JavaScript and other languages, but these (or the syntax equivalent) don't seem to be working in C#.

For reference, I'll write the if statement version down below:

for (int x = 1; x <= 15; x++)
        {
            if (x % 5 == 0 && x % 3 == 0)
                Console.WriteLine("FizzBuzz");
            else if (x % 5 == 0)
                Console.WriteLine("Buzz");
            else if (x % 3 == 0)
                Console.WriteLine("Fizz");
            else
                Console.WriteLine(x);
        }
        Console.ReadLine();

EDIT: forgot to put my switch statement code, sorry about that:

for (x = 1; x <= 15; x++)
{
    switch (x)
    {
        case (x % 3 == 0 && x % 5 == 0):
            Console.WriteLine("FizzBuzz");
            break;
        case (x % 5 == 0):
            Console.WriteLine("Buzz");
            break;
        case (x % 3 == 0):
            Console.WriteLine("Fizz");
            break;
        default:
            Console.WriteLine(x);
            break;
    }
}

My problem is with the modulo statements. Error is "Cannot implicitly convert type bool to int. I've tried replacing switch (x) with switch (true) but that doesn't help much, just changes the error to "A constant value is expected" for each of my cases.

Body:
It is possible to write a fizzbuzz as a simple switch.

It is just about as fast as an if else. I got a bit obsessed about this and created a little benchmark which I uploaded to git: https://github.com/chrisaddams/fizzbuzz-everyway-c-sharp

The results I found for speed are as follows:

Average Speed of Switch  is             63.46 ms
Average Speed of IfElseCont is          62.03 ms
Average Speed of If Else is             60.62 ms
Average Speed of If Only is             73.35 ms
Average Speed of If Cont is             73.55 ms

Anyway, here's the code, I think it's quite a neat and readable solution.

using System.Diagnostics;
using System;
namespace fizzbuzz
{
    class fizzyCase
    {
        static void Main(string[] args)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            for (int i = 0; i <= 10000; i++)
            {
                switch (true)
                {
                    case var FizzBuzz when (i % 15 == 0):
                        Console.WriteLine("fizzbuzz");
                        break;
                    case var Fizz when (i % 3 == 0):
                        Console.WriteLine("fizz");
                        break;
                    case var Buzz when (i % 5 == 0):
                        Console.WriteLine("buzz");
                        break;
                    default:
                        Console.WriteLine(i);
                        break;
                }
            }
            timer.Stop();
            Console.WriteLine("Elapsed:{0}milliseconds", timer.Elapsed.TotalMilliseconds);

        }
    }
}


问:
Converting a member function to a static function in C++
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

```<code>typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}
</code>```

答: After the edit, the intent seems clearer to me. The simplest thing that you can do is using static member functions in the MemoryTester instead of non-static member functions. If they need to hold state, that state will have to be moved to be static members of the class.

Body:
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}


问:
Using multiple render pipelines in a single MTLRenderCommandEncoder: How to Synchronize MTLBuffer?
Central Issue

I have two render pipelines in one single render command encoder. The first pipeline writes to a buffer which is used in the second pipeline. This does not seem to work and I expect it to be a synchronization problem. When I use one separate render command encoder for each render pipeline I get the desired result. Can this be solved with one single render command encoder or do I need two separate encoders to synchronize the buffer?

Here is the more specific case:

The first pipeline is a non-rasterizing pipeline only running a vertex shader to output to a MTLBuffer storing MTLDrawPrimitivesIndirectArguments to use for the drawPrimitives call for the second pipeline, which looks like this:

```<code>// renderCommandEncoder is MTLRenderCommandEncoder
// firstPipelineState and secondPipelineState are two different MTLRenderPipelineState
// indirectArgumentsBuffer is a MTLBuffer containing MTLDrawPrimitivesIndirectArguments
// numberOfVertices is number of vertices suited for first pipeline

// first pipeline
renderCommandEncoder.setRenderPipelineState(firstPipelineState)
renderCommandEncoder.setVertexBuffer(indirectArgumentsBuffer, offset: 0, index: 0)
renderCommandEncoder.drawPrimitives(type: .point, vertexStart: 0, vertexCount: numberOfVertices)

// second pipeline
renderCommandEncoder.setRenderPipelineState(secondPipelineState)
renderCommandEncoder.setVertexBuffer(secondPipelineBuffer, offset: 0, index: 0)
renderCommandEncoder.drawPrimitives(type: .point, indirectBuffer: indirectArgumentsBuffer, indirectBufferOffset: 0)

renderCommandEncoder.endEncoding()
</code>```

How can I make sure that the indirectArgumentsBuffer has been written to by the first pipeline when issuing a call to drawPrimitives for the second pipeline, which uses and needs the contents of indirectArgumentsBuffer?

答: I believe you need to use separate encoders. In this (somewhat dated) documentation about function writes, only atomic operations are synchronized for buffers shared between draw calls.</p>

Body:
Central Issue

I have two render pipelines in one single render command encoder. The first pipeline writes to a buffer which is used in the second pipeline. This does not seem to work and I expect it to be a synchronization problem. When I use one separate render command encoder for each render pipeline I get the desired result. Can this be solved with one single render command encoder or do I need two separate encoders to synchronize the buffer?

Here is the more specific case:

The first pipeline is a non-rasterizing pipeline only running a vertex shader to output to a MTLBuffer storing MTLDrawPrimitivesIndirectArguments to use for the drawPrimitives call for the second pipeline, which looks like this:

// renderCommandEncoder is MTLRenderCommandEncoder
// firstPipelineState and secondPipelineState are two different MTLRenderPipelineState
// indirectArgumentsBuffer is a MTLBuffer containing MTLDrawPrimitivesIndirectArguments
// numberOfVertices is number of vertices suited for first pipeline

// first pipeline
renderCommandEncoder.setRenderPipelineState(firstPipelineState)
renderCommandEncoder.setVertexBuffer(indirectArgumentsBuffer, offset: 0, index: 0)
renderCommandEncoder.drawPrimitives(type: .point, vertexStart: 0, vertexCount: numberOfVertices)

// second pipeline
renderCommandEncoder.setRenderPipelineState(secondPipelineState)
renderCommandEncoder.setVertexBuffer(secondPipelineBuffer, offset: 0, index: 0)
renderCommandEncoder.drawPrimitives(type: .point, indirectBuffer: indirectArgumentsBuffer, indirectBufferOffset: 0)

renderCommandEncoder.endEncoding()

How can I make sure that the indirectArgumentsBuffer has been written to by the first pipeline when issuing a call to drawPrimitives for the second pipeline, which uses and needs the contents of indirectArgumentsBuffer?


问:
How ignore/hide/deactivate my policy non-compliance state and get 100% compliance?
Below is my policy definition and is correctly working (policy is responsible to assign tags from resource group to resources):

```<code>{
  "properties": {
    "displayName": "inheritTags",
    "policyType": "Custom",
    "mode": "Indexed",
    "metadata": {
      "createdBy": "3332dc03-2402-46e3-9098-c7350b0bc8dd",
      "createdOn": "2019-11-25T14:49:57.8136557Z",
      "updatedBy": "3332dc03-2402-46e3-9098-c7350b0bc8dd",
      "updatedOn": "2019-11-26T19:43:48.752452Z"
    },
    "parameters": {},
    "policyRule": {
      "if": {
        "allOf": [
          {
            "value": "[resourceGroup().tags]",
            "exists": "true"
          },
          {
            "value": "[resourceGroup().tags]",
            "notEquals": ""
          }
        ]
      },
      "then": {
        "effect": "modify",
        "details": {
          "operations": [
            {
              "operation": "addOrReplace",
              "field": "tags",
              "value": "[resourceGroup().tags]"
            }
          ],
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
          ]
        }
      }
    }
  },
  "id": "/subscriptions/78afced4-1c58-4e66-8242-c042890d34c3/providers/Microsoft.Authorization/policyDefinitions/9f2a0e94-5ada-47b0-8125-42464f93cf37",
  "type": "Microsoft.Authorization/policyDefinitions",
  "name": "9f2a0e94-5ada-47b0-8125-42464f93cf37"
}
</code>```

Nevertheless in Overview tab on Policy page I have information that assigned policy definition is in Non-compliant state:

Reason for that? Different values due to comparing previous state to expected state and I know that source of "issues" are keywords like exists, notEquals and so on: https://learn.microsoft.com/en-us/azure/governance/policy/how-to/determine-non-compliance#compliance-reasons

How to ignore those compliance messages and get resource compliance, you know tags are correctly assigned so what is the problem? or maybe I have wrong understanding of azure policies?

答: The resources that are coming up as non-compliant is because they do not have the same tags as  the RG. For some resources, modify won't because they don't support tags or don't support updating/adding tags. I can't tell what type of resource it is so I can't say forsure that is the issues. If this is the case that those resources don't support tags, then you can just excluded that resource from the assignment to see the compliance percentage not including those. (Edit the assignment and add an exclusion) </p>

Body:
Below is my policy definition and is correctly working (policy is responsible to assign tags from resource group to resources):

{
  "properties": {
    "displayName": "inheritTags",
    "policyType": "Custom",
    "mode": "Indexed",
    "metadata": {
      "createdBy": "3332dc03-2402-46e3-9098-c7350b0bc8dd",
      "createdOn": "2019-11-25T14:49:57.8136557Z",
      "updatedBy": "3332dc03-2402-46e3-9098-c7350b0bc8dd",
      "updatedOn": "2019-11-26T19:43:48.752452Z"
    },
    "parameters": {},
    "policyRule": {
      "if": {
        "allOf": [
          {
            "value": "[resourceGroup().tags]",
            "exists": "true"
          },
          {
            "value": "[resourceGroup().tags]",
            "notEquals": ""
          }
        ]
      },
      "then": {
        "effect": "modify",
        "details": {
          "operations": [
            {
              "operation": "addOrReplace",
              "field": "tags",
              "value": "[resourceGroup().tags]"
            }
          ],
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
          ]
        }
      }
    }
  },
  "id": "/subscriptions/78afced4-1c58-4e66-8242-c042890d34c3/providers/Microsoft.Authorization/policyDefinitions/9f2a0e94-5ada-47b0-8125-42464f93cf37",
  "type": "Microsoft.Authorization/policyDefinitions",
  "name": "9f2a0e94-5ada-47b0-8125-42464f93cf37"
}

Nevertheless in Overview tab on Policy page I have information that assigned policy definition is in Non-compliant state:

Reason for that? Different values due to comparing previous state to expected state and I know that source of "issues" are keywords like exists, notEquals and so on: https://learn.microsoft.com/en-us/azure/governance/policy/how-to/determine-non-compliance#compliance-reasons

How to ignore those compliance messages and get resource compliance, you know tags are correctly assigned so what is the problem? or maybe I have wrong understanding of azure policies?


问:
React - How to detect when all sub-components of a parent component are visible to the user?
TL;DR

How can a parent component know when the rendering of every child
  component under it has finished and the DOM visible to the user with its most up to date version?

Let's say I have a component A that has a child Grid component consisting of 3x3 grandchild components. Each of those grandchild components fetches data from a restful API endpoint and renders itself when the data becomes available.

I would like to cover the entire area of Component A with a loader placeholder, to be unveiled only when the last of the components in the grid has fetched the data successfully, and rendered it, such that it's already on the DOM and can be viewed.

The user experience should be a super smooth transition from "loader" to a fully populated grid without flickering.

My problem is knowing exactly when to unveil the components under the loader.

Is there any mechanism I can rely on to do this with absolute accuracy? I don't to hard code a time limit for the loader. As I understand relying on ComponentDidMount for every child is also unreliable as it doesn't actually guarantee the component is fully visible to the user at the time of the call.

To distill the question even further:

I have a component that renders some kind of data. After it's
  initialized it doesn't have it, so in its componentDidMount it hits
  an API endpoint for it. Once it receives the data, it's changing its
  state to reflect it. This understandably causes a re-render of the
  final state of that component. My question is this: How do I know when
  that re-render has taken place and is reflected in the User
  facing DOM. That point in time != the point in time when the
  component's state has changed to contain data.

答:
As you are making an api call in componentDidMount, when the API call will resolve you will have the data in componentDidUpdate as this lifecycle will pass you prevProps and prevState. So you can do something like below:

```<code>class Parent extends Component {
  getChildUpdateStatus = (data) => {
 // data is any data you want to send from child
}
render () {
 <Child sendChildUpdateStatus={getChildUpdateStatus}/>
}
}

class Child extends Component {
componentDidUpdate = (prevProps, prevState) => {
   //compare prevProps from this.props or prevState from current state as per your requirement
  this.props.sendChildUpdateStatus();
}

render () {
   return <h2>{.. child rendering}</h2>
  }
}
</code>```

If you want to know this before the component re renders, you can use getSnapshotBeforeUpdate.

https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate.

Body:
As you are making an api call in componentDidMount, when the API call will resolve you will have the data in componentDidUpdate as this lifecycle will pass you prevProps and prevState. So you can do something like below:

class Parent extends Component {
  getChildUpdateStatus = (data) => {
 // data is any data you want to send from child
}
render () {
 <Child sendChildUpdateStatus={getChildUpdateStatus}/>
}
}

class Child extends Component {
componentDidUpdate = (prevProps, prevState) => {
   //compare prevProps from this.props or prevState from current state as per your requirement
  this.props.sendChildUpdateStatus();
}

render () {
   return <h2>{.. child rendering}</h2>
  }
}

If you want to know this before the component re renders, you can use getSnapshotBeforeUpdate.

https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate.


问:
Laravel migration table field's type change
Following is my file 2015_09_14_051851_create_orders_table.php.
And I want to change $table->integer('category_id'); as a string with new migration.

```<code><?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOrdersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('orders', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('num');
            $table->integer('user_id');

            $table->text('store_name');
            $table->integer('store_name_publication');

            $table->string('postal_code', 255);
            $table->string('phone_number', 255);

            $table->text('title');
            $table->text('description');

            $table->string('list_image_filename1', 255);
            $table->string('list_image_filename2', 255)->nullable();
            $table->string('list_image_filename3', 255)->nullable();
            $table->string('list_image_filename4', 255)->nullable();
            $table->string('list_image_filename5', 255)->nullable();

            $table->integer('term');

            $table->datetime('state0_at')->nullable();
            $table->datetime('state1_at')->nullable();
            $table->datetime('state2_at')->nullable();
            $table->datetime('state3_at')->nullable();
            $table->datetime('state4_at')->nullable();
            $table->datetime('state5_at')->nullable();
            $table->datetime('state6_at')->nullable();
            $table->datetime('state7_at')->nullable();
            $table->datetime('state8_at')->nullable();
            $table->datetime('state9_at')->nullable();
            $table->datetime('state10_at')->nullable();

            $table->integer('category_id');
            $table->integer('target_customer_sex');
            $table->integer('target_customer_age');

            $table->integer('payment_order');
            $table->integer('num_comment');
            $table->integer('num_view');
            $table->string('num_pop');

            $table->integer('money');
            $table->integer('point');

            $table->datetime('closed_at');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('orders');
    }

}
</code>```

答:
First composer requires doctrine/dbal, then:

```<code>$table->longText('column_name')->change();
</code>```

Body:
Following is my file 2015_09_14_051851_create_orders_table.php.
And I want to change $table->integer('category_id'); as a string with new migration.

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOrdersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('orders', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('num');
            $table->integer('user_id');

            $table->text('store_name');
            $table->integer('store_name_publication');

            $table->string('postal_code', 255);
            $table->string('phone_number', 255);

            $table->text('title');
            $table->text('description');

            $table->string('list_image_filename1', 255);
            $table->string('list_image_filename2', 255)->nullable();
            $table->string('list_image_filename3', 255)->nullable();
            $table->string('list_image_filename4', 255)->nullable();
            $table->string('list_image_filename5', 255)->nullable();

            $table->integer('term');

            $table->datetime('state0_at')->nullable();
            $table->datetime('state1_at')->nullable();
            $table->datetime('state2_at')->nullable();
            $table->datetime('state3_at')->nullable();
            $table->datetime('state4_at')->nullable();
            $table->datetime('state5_at')->nullable();
            $table->datetime('state6_at')->nullable();
            $table->datetime('state7_at')->nullable();
            $table->datetime('state8_at')->nullable();
            $table->datetime('state9_at')->nullable();
            $table->datetime('state10_at')->nullable();

            $table->integer('category_id');
            $table->integer('target_customer_sex');
            $table->integer('target_customer_age');

            $table->integer('payment_order');
            $table->integer('num_comment');
            $table->integer('num_view');
            $table->string('num_pop');

            $table->integer('money');
            $table->integer('point');

            $table->datetime('closed_at');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('orders');
    }

}

Body:
First composer requires doctrine/dbal, then:

$table->longText('column_name')->change();


问:
Filling a Java array with elements produced in another class
I'm trying to fill a deck of cards in my "Deck" class with cards created in my "Card" class. When I print the result in my Deck class, I get 52 "null"s, which tells me the two are communicating, just not very well. I've copied the code below. Where am I going wrong? Thanks!</p>

```<code>public class Card {
    public String cardName;
    private int[] cardValue = {(Integer) null, 1, 2, 3, 4, 5, 6, 7, 8,
        9, 10, 11};
    private String[] cardSuit = {"C", "D", "H", "S"};

    public Card(String cardName, int[] cardValue, String[] cardSuit) {
        this.cardName = cardName;
        this.cardValue = cardValue;
        this.cardSuit = cardSuit;
    }
    public String makeCard(int[] cardValue, String[] cardSuit) {
        for(int i = 0; i < 12; i++) {
            for(int j = 0; j < 4; j++) {
                cardName = cardValue[i] + cardSuit[j];
                j++;
            }
            i++;
        }
        return cardName;
    }
}
</code>```

```<code>import java.util.Arrays;

public class Deck {

    public static String[] cardDeck = new String[52];

    public String[] makeDeck(String cardName) {
        for(int i =0; i < 52; i++) {
            cardDeck[i] = cardName;
            i++;
        }

        Arrays.fill(cardDeck, cardName);
        return cardDeck;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(cardDeck));
    }
}
</code>```

答: You create a new string array with String[] cardDeck = new String[52]; but you never assign any values to this array. String is an object and initialized with null. So only null will be printed. You never call any method of any class nor are you initializing deck and card.

Body:
I'm trying to fill a deck of cards in my "Deck" class with cards created in my "Card" class. When I print the result in my Deck class, I get 52 "null"s, which tells me the two are communicating, just not very well. I've copied the code below. Where am I going wrong? Thanks!

public class Card {
    public String cardName;
    private int[] cardValue = {(Integer) null, 1, 2, 3, 4, 5, 6, 7, 8,
        9, 10, 11};
    private String[] cardSuit = {"C", "D", "H", "S"};

    public Card(String cardName, int[] cardValue, String[] cardSuit) {
        this.cardName = cardName;
        this.cardValue = cardValue;
        this.cardSuit = cardSuit;
    }
    public String makeCard(int[] cardValue, String[] cardSuit) {
        for(int i = 0; i < 12; i++) {
            for(int j = 0; j < 4; j++) {
                cardName = cardValue[i] + cardSuit[j];
                j++;
            }
            i++;
        }
        return cardName;
    }
}

import java.util.Arrays;

public class Deck {

    public static String[] cardDeck = new String[52];

    public String[] makeDeck(String cardName) {
        for(int i =0; i < 52; i++) {
            cardDeck[i] = cardName;
            i++;
        }

        Arrays.fill(cardDeck, cardName);
        return cardDeck;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(cardDeck));
    }
}


答:
I would set it up so that you're relying a global state variable to tell your components when to render.  Redux is better for this scenario where many components are talking to each other, and you mentioned in a comment that you use it sometimes.  So I'll sketch out an answer using Redux.

You'd have to move your API calls to the parent container, Component A.  If you are wanting to have your grandchildren render only after the API calls complete, you can't keep those API calls in the grandchildren themselves.  How can an API call be made from a component that doesn't exist yet?

Once all the API calls are made, you can use actions to update a global state variable containing a bunch of data objects.  Every time data is recieved (or an error is caught), you can dispatch an action to check if your data object is fully filled out.  Once its completely filled out, you can update a loading variable to false, and conditionally render your Grid component.

So for example:

// Component A

import { acceptData, catchError } from '../actions'

class ComponentA extends React.Component{

  componentDidMount () {

    fetch('yoururl.com/data')
      .then( response => response.json() )
      // send your data to the global state data array
      .then( data => this.props.acceptData(data, grandChildNumber) )
      .catch( error => this.props.catchError(error, grandChildNumber) )

    // make all your fetch calls here

  }

  // Conditionally render your Loading or Grid based on the global state variable 'loading'
  render() {
    return (
      { this.props.loading && <Loading /> }
      { !this.props.loading && <Grid /> }
    )
  }

}

const mapStateToProps = state => ({ loading: state.loading })

const mapDispatchToProps = dispatch => ({
  acceptData: data => dispatch( acceptData( data, number ) )
  catchError: error=> dispatch( catchError( error, number) )
})
```

<pre class="lang-js prettyprint-override"><code>// Grid - not much going on here...

render () {
  return (
    <div className="Grid">
      <GrandChild1 number={1} />
      <GrandChild2 number={2} />
      <GrandChild3 number={3} />
      ...
      // Or render the granchildren from an array with a .map, or something similar
    </div>
  )
}
</code>```

// Grandchild

// Conditionally render either an error or your data, depending on what came back from fetch
render () {
  return (
    { !this.props.data[this.props.number].error && <Your Content Here /> }
    { this.props.data[this.props.number].error && <Your Error Here /> }
  )
}

const mapStateToProps = state => ({ data: state.data })
```

<p>Your reducer willhold the global state object which will say if things are all ready to go yet or not:</p>

<pre class="lang-js prettyprint-override"><code>// reducers.js

const initialState = {
  data: [{},{},{},{}...], // 9 empty objects
  loading: true
}

const reducers = (state = initialState, action) {
  switch(action.type){

    case RECIEVE_SOME_DATA:
      return {
        ...state,
        data: action.data
      }

     case RECIEVE_ERROR:
       return {
         ...state,
         data: action.data
       }

     case STOP_LOADING:
       return {
         ...state,
         loading: false
       }

  }
}
</code>```

In your actions:

export const acceptData = (data, number) => {
  // First revise your data array to have the new data in the right place
  const updatedData = data
  updatedData[number] = data
  // Now check to see if all your data objects are populated
  // and update your loading state:
  dispatch( checkAllData() )
  return {
    type: RECIEVE_SOME_DATA,
    data: updatedData,
  }
}

// error checking - because you want your stuff to render even if one of your api calls
// catches an error
export const catchError(error, number) {
  // First revise your data array to have the error in the right place
  const updatedData = data
  updatedData[number].error = error
  // Now check to see if all your data objects are populated
  // and update your loading state:
  dispatch( checkAllData() )
  return {
    type: RECIEVE_ERROR,
    data: updatedData,
  }
}

export const checkAllData() {
  // Check that every data object has something in it
  if ( // fancy footwork to check each object in the data array and see if its empty or not
    store.getState().data.every( dataSet =>
      Object.entries(dataSet).length === 0 && dataSet.constructor === Object ) ) {
        return {
          type: STOP_LOADING
        }
      }
  }
```

Aside

If you are really married to the idea that your API calls live inside each grandchild, but that the whole Grid of grandchildren does not render until all API calls are completed, you'd have to use a completely different solution.  In this case, your grandchildren would have to be rendered from the start to make their calls, but have a css class with display: none, which only changes after the global state variable loading is marked as false.  This is also doable, but sort of besides the point of React.

Title: React - How to detect when all sub-components of a parent component are visible to the user?

Body:
TL;DR

How can a parent component know when the rendering of every child
  component under it has finished and the DOM visible to the user with its most up to date version?

Let's say I have a component A that has a child Grid component consisting of 3x3 grandchild components. Each of those grandchild components fetches data from a restful API endpoint and renders itself when the data becomes available.

I would like to cover the entire area of Component A with a loader placeholder, to be unveiled only when the last of the components in the grid has fetched the data successfully, and rendered it, such that it's already on the DOM and can be viewed.

The user experience should be a super smooth transition from "loader" to a fully populated grid without flickering.

My problem is knowing exactly when to unveil the components under the loader.

Is there any mechanism I can rely on to do this with absolute accuracy? I don't to hard code a time limit for the loader. As I understand relying on ComponentDidMount for every child is also unreliable as it doesn't actually guarantee the component is fully visible to the user at the time of the call.

To distill the question even further:

I have a component that renders some kind of data. After it's
  initialized it doesn't have it, so in its componentDidMount it hits
  an API endpoint for it. Once it receives the data, it's changing its
  state to reflect it. This understandably causes a re-render of the
  final state of that component. My question is this: How do I know when
  that re-render has taken place and is reflected in the User
  facing DOM. That point in time != the point in time when the
  component's state has changed to contain data.

Body:
I would set it up so that you're relying a global state variable to tell your components when to render.  Redux is better for this scenario where many components are talking to each other, and you mentioned in a comment that you use it sometimes.  So I'll sketch out an answer using Redux.

You'd have to move your API calls to the parent container, Component A.  If you are wanting to have your grandchildren render only after the API calls complete, you can't keep those API calls in the grandchildren themselves.  How can an API call be made from a component that doesn't exist yet?

Once all the API calls are made, you can use actions to update a global state variable containing a bunch of data objects.  Every time data is recieved (or an error is caught), you can dispatch an action to check if your data object is fully filled out.  Once its completely filled out, you can update a loading variable to false, and conditionally render your Grid component.

So for example:

// Component A

import { acceptData, catchError } from '../actions'

class ComponentA extends React.Component{

  componentDidMount () {

    fetch('yoururl.com/data')
      .then( response => response.json() )
      // send your data to the global state data array
      .then( data => this.props.acceptData(data, grandChildNumber) )
      .catch( error => this.props.catchError(error, grandChildNumber) )

    // make all your fetch calls here

  }

  // Conditionally render your Loading or Grid based on the global state variable 'loading'
  render() {
    return (
      { this.props.loading && <Loading /> }
      { !this.props.loading && <Grid /> }
    )
  }

}

const mapStateToProps = state => ({ loading: state.loading })

const mapDispatchToProps = dispatch => ({
  acceptData: data => dispatch( acceptData( data, number ) )
  catchError: error=> dispatch( catchError( error, number) )
})

// Grid - not much going on here...

render () {
  return (
    <div className="Grid">
      <GrandChild1 number={1} />
      <GrandChild2 number={2} />
      <GrandChild3 number={3} />
      ...
      // Or render the granchildren from an array with a .map, or something similar
    </div>
  )
}

// Grandchild

// Conditionally render either an error or your data, depending on what came back from fetch
render () {
  return (
    { !this.props.data[this.props.number].error && <Your Content Here /> }
    { this.props.data[this.props.number].error && <Your Error Here /> }
  )
}

const mapStateToProps = state => ({ data: state.data })

Your reducer willhold the global state object which will say if things are all ready to go yet or not:

// reducers.js

const initialState = {
  data: [{},{},{},{}...], // 9 empty objects
  loading: true
}

const reducers = (state = initialState, action) {
  switch(action.type){

    case RECIEVE_SOME_DATA:
      return {
        ...state,
        data: action.data
      }

     case RECIEVE_ERROR:
       return {
         ...state,
         data: action.data
       }

     case STOP_LOADING:
       return {
         ...state,
         loading: false
       }

  }
}

In your actions:

export const acceptData = (data, number) => {
  // First revise your data array to have the new data in the right place
  const updatedData = data
  updatedData[number] = data
  // Now check to see if all your data objects are populated
  // and update your loading state:
  dispatch( checkAllData() )
  return {
    type: RECIEVE_SOME_DATA,
    data: updatedData,
  }
}

// error checking - because you want your stuff to render even if one of your api calls
// catches an error
export const catchError(error, number) {
  // First revise your data array to have the error in the right place
  const updatedData = data
  updatedData[number].error = error
  // Now check to see if all your data objects are populated
  // and update your loading state:
  dispatch( checkAllData() )
  return {
    type: RECIEVE_ERROR,
    data: updatedData,
  }
}

export const checkAllData() {
  // Check that every data object has something in it
  if ( // fancy footwork to check each object in the data array and see if its empty or not
    store.getState().data.every( dataSet =>
      Object.entries(dataSet).length === 0 && dataSet.constructor === Object ) ) {
        return {
          type: STOP_LOADING
        }
      }
  }

Aside

If you are really married to the idea that your API calls live inside each grandchild, but that the whole Grid of grandchildren does not render until all API calls are completed, you'd have to use a completely different solution.  In this case, your grandchildren would have to be rendered from the start to make their calls, but have a css class with display: none, which only changes after the global state variable loading is marked as false.  This is also doable, but sort of besides the point of React.


问:
PowerShell - concatenate a calculated property with another selected field
I am simply trying to concatenate two columns from my result set. I want to concatenate the columns SamAccountName and domain

Here's the code:

```<code>$ad_list = Get-Content C:\AD\ad_groups.txt
$domain = "@domain.com"
ForEach ($ad_group in $ad_list) {
    Get-ADGroupMember -Identity $ad_group -Server MyServer |
        Select-Object Name,SamAccountName, @{Name='domain';Expression={$domain}} , @{Name='Ad_Group';Expression={$ad_group}}
}
</code>```

答:
The Expression would look like {$_.SamAccountName + $domain}, I've edited domain in the below example

```<code>$ad_list = Get-Content C:\AD\ad_groups.txt
$domain = "@domain.com"
ForEach ($ad_group in $ad_list) {
    Get-ADGroupMember -Identity $ad_group -Server MyServer |
        Select-Object Name,SamAccountName, @{Name='domain';Expression={$_.SamAccountName + $domain}} , @{Name='Ad_Group';Expression={$ad_group}}
}
</code>```

Body:
I am simply trying to concatenate two columns from my result set. I want to concatenate the columns SamAccountName and domain

Here's the code:

$ad_list = Get-Content C:\AD\ad_groups.txt
$domain = "@domain.com"
ForEach ($ad_group in $ad_list) {
    Get-ADGroupMember -Identity $ad_group -Server MyServer |
        Select-Object Name,SamAccountName, @{Name='domain';Expression={$domain}} , @{Name='Ad_Group';Expression={$ad_group}}
}

Body:
The Expression would look like {$_.SamAccountName + $domain}, I've edited domain in the below example

$ad_list = Get-Content C:\AD\ad_groups.txt
$domain = "@domain.com"
ForEach ($ad_group in $ad_list) {
    Get-ADGroupMember -Identity $ad_group -Server MyServer |
        Select-Object Name,SamAccountName, @{Name='domain';Expression={$_.SamAccountName + $domain}} , @{Name='Ad_Group';Expression={$ad_group}}
}


问:
How can I count the number of elements in a vector that fall within a particular range using r?
Let's say we a vector a = (10,23,57,37,59,25,63,33) and we want to calculate the frequency in the bins 10-19,20-29,30-39,40-49,50-59,60-69.The output should be in the form of a vector, in this case (1,2,2,2,1).

答:
Another base R solution is to use hist, i.e.,

```<code>hist(a,plot = FALSE,breaks = seq(10,70,by=10))$counts
# [1] 1 2 2 0 2 1
</code>```

Body:
Another base R solution is to use hist, i.e.,

hist(a,plot = FALSE,breaks = seq(10,70,by=10))$counts
# [1] 1 2 2 0 2 1


问:
how to improve performance of nested for loops when comparing values in an array
```<code>var twoSum = function(nums, target) {
  for(let i = 0; i < nums.length; i++){
    for(let j = i + 1; j < nums.length; j++){
      if(nums[i] + nums[j] === target){
        return [nums.indexOf(nums[i]), nums.lastIndexOf(nums[j])]
      }
    }
  }
}
function([3,5,3,7,2], 9) //It should return [3, 4] since 7 + 2 = 9
</code>```

This is a Javascript function and it's iterating over the array of numbers with nested for loops and find a pair that when summed, it equals the target and return their indexes. Since it has a nested for loop it I believe it has O(n^2) or quadratic time complexity, and I was wondering if there is a faster way to do this. I'm just trying to get the first pass solution and after improve upon it.  Thanks in advance!

答:
You could use nested map():

var twoSum = (nums, target)=> {
  //  map trough list for first number
  nums.map(
   (val1, index1)=>
    {
      // map through list again for second number to compare to number returned from first map at each instance
      nums.map((val2, index2) =>
      {
      //  Ensure that index1 and index2 are not the same before you compare
        if(index1 != index2 && (val1 + val2 === target))
        {
          alert([index1, index2]);
          return [index1, index2];
        }
      });
    }
  );
}

twoSum([3,5,3,7,2], 9) //It should return [3, 4] since 7 + 2 = 9```

Note: Remember this won't loop through all the items unless a match has not been found. As soon as a match is found, the function returns, and exit.

Body:
var twoSum = function(nums, target) {
  for(let i = 0; i < nums.length; i++){
    for(let j = i + 1; j < nums.length; j++){
      if(nums[i] + nums[j] === target){
        return [nums.indexOf(nums[i]), nums.lastIndexOf(nums[j])]
      }
    }
  }
}
function([3,5,3,7,2], 9) //It should return [3, 4] since 7 + 2 = 9

This is a Javascript function and it's iterating over the array of numbers with nested for loops and find a pair that when summed, it equals the target and return their indexes. Since it has a nested for loop it I believe it has O(n^2) or quadratic time complexity, and I was wondering if there is a faster way to do this. I'm just trying to get the first pass solution and after improve upon it.  Thanks in advance!

Body:
You could use nested map():

var twoSum = (nums, target)=> {
  //  map trough list for first number
  nums.map(
   (val1, index1)=>
    {
      // map through list again for second number to compare to number returned from first map at each instance
      nums.map((val2, index2) =>
      {
      //  Ensure that index1 and index2 are not the same before you compare
        if(index1 != index2 && (val1 + val2 === target))
        {
          alert([index1, index2]);
          return [index1, index2];
        }
      });
    }
  );
}

twoSum([3,5,3,7,2], 9) //It should return [3, 4] since 7 + 2 = 9

Note: Remember this won't loop through all the items unless a match has not been found. As soon as a match is found, the function returns, and exit.


问:
How would I create a PostgreSQL database using "CREATE DATABASE" over an ODBC connection using PyODBC?
I am attempting to create a PostgreSQL 12.1 database (not a schema) using the CREATE DATABASE statement from a Python 3.7.5 program connecting to a PostgreSQL 12.1 instance as user postgres over UnixODBC and using the PyODBC module, all running on Ubuntu 19.10. My program runs a loop that reads lines from a SQL DDL script, splitting SQL statements on the semicolon character. It logs the following errors:

```<code>16:15:20 ERROR    Error executing statement 'CREATE DATABASE "TestV1" WITH OWNER = postgres': ('25001', '[25001] ERROR: CREATE DATABASE cannot run inside a transaction block;\nError while executing the query (1) (SQLExecDirectW)')
16:15:20 CRITICAL Unable to create objects: ('25001', '[25001] ERROR: CREATE DATABASE cannot run inside a transaction block;\nError while executing the query (1) (SQLExecDirectW)')
</code>```

My SQL DDL script begins with the following line:
CREATE DATABASE "TestV1" WITH OWNER = postgres;

I've had success with CREATE SCHEMA in the same context, but not with CREATE DATABASE. As well, I cannot seem to find any answers here related to CREATE DATABASE on PostgreSQL specifically. I can create a database from the shell command line using createdb. I have tried setting AUTOCOMMIT on within the SQL DDL script, but that does not work.

答: It seems it is best to issue the createdb command from the Bash shell and be done with it. I can then connect to the newly created database from ODBC. Rinse and repeat for each database to be created and populated.

Body:
I am attempting to create a PostgreSQL 12.1 database (not a schema) using the CREATE DATABASE statement from a Python 3.7.5 program connecting to a PostgreSQL 12.1 instance as user postgres over UnixODBC and using the PyODBC module, all running on Ubuntu 19.10. My program runs a loop that reads lines from a SQL DDL script, splitting SQL statements on the semicolon character. It logs the following errors:

16:15:20 ERROR    Error executing statement 'CREATE DATABASE "TestV1" WITH OWNER = postgres': ('25001', '[25001] ERROR: CREATE DATABASE cannot run inside a transaction block;\nError while executing the query (1) (SQLExecDirectW)')
16:15:20 CRITICAL Unable to create objects: ('25001', '[25001] ERROR: CREATE DATABASE cannot run inside a transaction block;\nError while executing the query (1) (SQLExecDirectW)')

My SQL DDL script begins with the following line:
CREATE DATABASE "TestV1" WITH OWNER = postgres;

I've had success with CREATE SCHEMA in the same context, but not with CREATE DATABASE. As well, I cannot seem to find any answers here related to CREATE DATABASE on PostgreSQL specifically. I can create a database from the shell command line using createdb. I have tried setting AUTOCOMMIT on within the SQL DDL script, but that does not work.


问:
Angular PWA error Site cannot be installed: no matching service worker detected
I have a website (Angular 9.0.1), I added the @angular/pwa package to turn it into a PWA and it's not working.

The website is on production site but with test data right now on https://new.indomablestore.com

I have checked that the required files (manifest.webmanifest, ngsw.json, ngsw-worker.js) are on the root folder.
I have checked that the index.html file points correctly to the manifest, and it is shown on Chrome Devtools Application tab.

But on the Installability section it says: No matching service worker detected. You may need to reload the page, or check that the service worker for the current page also controls the start URL from the manifest.

I have also checked that the app.module.ts file has this line:

ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })

And I haven't modified any of the PWA files, I let Angular CLI build them.

Any help would be appreciated as the site is going to go live soon and this is the last thing on my list :)

Thanks!

UPDATE: The manifest looks like this:

```<code>  "name": "Indomable",
  "short_name": "Indomable",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "display": "standalone",
  "scope": "/",
  "start_url": "/",
  "icons": [
    ...
  ]
}
</code>```

And the Service Worker is registered on the app.module like this:

```<code>@NgModule({
  declarations: [
    AppComponent,
    ...PAGES,
    ...COMPONENTS,
    ...PIPES
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    routing,
    NgxPayPalModule,
    ServiceWorkerModule.register('./ngsw-worker.js', { enabled: environment.production, scope: './' })
  ],
  ...
</code>```

Thanks for the quick answers anyway :)

答:
You can try to set the scop (/) in both the app manifest:

```<code>"scope": "/",
"start_url": "/",
</code>```

and while registering the service worker:

```<code>    ServiceWorkerModule.register('./ngsw-worker.js', {
      scope: './',
    }),
</code>```

but I think the issue is that your web server should append the trailing slash. That is, when user visit your site, they should be redirected to
new.indomablestore.com/, which correspond to the scope of your application and the basepath in your index.

Body:
I have a website (Angular 9.0.1), I added the @angular/pwa package to turn it into a PWA and it's not working.

The website is on production site but with test data right now on https://new.indomablestore.com

I have checked that the required files (manifest.webmanifest, ngsw.json, ngsw-worker.js) are on the root folder.
I have checked that the index.html file points correctly to the manifest, and it is shown on Chrome Devtools Application tab.

But on the Installability section it says: No matching service worker detected. You may need to reload the page, or check that the service worker for the current page also controls the start URL from the manifest.

I have also checked that the app.module.ts file has this line:

ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })

And I haven't modified any of the PWA files, I let Angular CLI build them.

Any help would be appreciated as the site is going to go live soon and this is the last thing on my list :)

Thanks!

UPDATE: The manifest looks like this:

  "name": "Indomable",
  "short_name": "Indomable",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "display": "standalone",
  "scope": "/",
  "start_url": "/",
  "icons": [
    ...
  ]
}

And the Service Worker is registered on the app.module like this:

@NgModule({
  declarations: [
    AppComponent,
    ...PAGES,
    ...COMPONENTS,
    ...PIPES
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    routing,
    NgxPayPalModule,
    ServiceWorkerModule.register('./ngsw-worker.js', { enabled: environment.production, scope: './' })
  ],
  ...

Thanks for the quick answers anyway :)

Body:
You can try to set the scop (/) in both the app manifest:

"scope": "/",
"start_url": "/",

and while registering the service worker:

    ServiceWorkerModule.register('./ngsw-worker.js', {
      scope: './',
    }),

but I think the issue is that your web server should append the trailing slash. That is, when user visit your site, they should be redirected to
new.indomablestore.com/, which correspond to the scope of your application and the basepath in your index.


问:
What is the difference between class: 'item' and :class => "item" in Ruby on Rails? Which style should I use?
I am pretty new to Rails and I'm working with a new code base that sometimes uses two different syntax for the same thing.

```<code>class: 'item'
</code>```

vs

```<code>:class => "item"
</code>```

However, I have have not been able to find what the difference is or which style I should use as best-practice.

I assume that it has something to do with the Rails version. We are planning to move to Rails 6. Can somebody shed some insight on this for me?

答:
They are the same thing, both create a key/value pair. Where the key is the Symbol :class and the value is the String 'item'.

Normally you create a key/value pair using the => syntax. {'key' => 'value'} (here both the key and value are a String) however, since a symbol already starts with a symbol they've added some syntactic sugar later on.

The : at the end of a symbol denotes both that the key is a symbol and that it concerns a key/value pair. For symbols {:key => 'value'} is the old syntax and {key: 'value'} is the newer variant. The examples given here are hash literals but this also applies when calling methods. some_method(key: 'value')

Body:
I am pretty new to Rails and I'm working with a new code base that sometimes uses two different syntax for the same thing.

class: 'item'

vs

:class => "item"

However, I have have not been able to find what the difference is or which style I should use as best-practice.

I assume that it has something to do with the Rails version. We are planning to move to Rails 6. Can somebody shed some insight on this for me?


问:
Remove the "Custom" argument from PayPal transaction details
I'm using Woocommerce with the PayPal standard payment features. In my orders transaction details there is a "Custom" string like the following:

{"order_id":26143,"order_key":"wc_order_sHM1ITT24fTC9"}

I really don't like my customers to see this field in the transaction details.

I was wondering what is the "custom" argument for? Is this argument essential for the plugin to work or can it be removed?

Here is the filter I would like to use to unset the "Custom" argument. Does it make sense?

```<code>add_filter('woocommerce_paypal_args', 'custom_paypal_args', 10, 2 );
function custom_paypal_args($args, $order) {
    unset($args["custom"]);  //Remove the custom argument
    return $args;
}
</code>```

答:
Customers don't see that value in their transaction details. Only the receiver of the transaction sees it.

WooCommerce uses that JSON data to reconcile notifications about the payment status (usually received via IPN), with orders in its database

There are many plugins available for PayPal payments via WooCommerce, and it does not necessarily ship with the best one. I would recommend trying this one if you haven't already: https://woocommerce.com/woocommerce-and-paypal/

Body:
I'm using Woocommerce with the PayPal standard payment features. In my orders transaction details there is a "Custom" string like the following:

{"order_id":26143,"order_key":"wc_order_sHM1ITT24fTC9"}

I really don't like my customers to see this field in the transaction details.

I was wondering what is the "custom" argument for? Is this argument essential for the plugin to work or can it be removed?

Here is the filter I would like to use to unset the "Custom" argument. Does it make sense?

add_filter('woocommerce_paypal_args', 'custom_paypal_args', 10, 2 );
function custom_paypal_args($args, $order) {
    unset($args["custom"]);  //Remove the custom argument
    return $args;
}


问:
React with TypeScript - define defaultProps in stateless function
I'm using React with TypeScript and I've created stateless function. I've removed useless code from the example for readability.

```<code>interface CenterBoxProps extends React.Props<CenterBoxProps> {
    minHeight?: number;
}

export const CenterBox = (props: CenterBoxProps) => {
    const minHeight = props.minHeight || 250;
    const style = {
        minHeight: minHeight
    };
    return <div style={style}>Example div</div>;
};
</code>```

Everything is great and this code is working correctly. But there's my question: how can I define defaultProps for CenterBox component?

As it is mentioned in react docs:

(...) They are pure functional transforms of their input, with zero
  boilerplate. However, you may still specify .propTypes and
  .defaultProps by setting them as properties on the function, just as
  you would set them on an ES6 class. (...)

it should be easy as:

```<code>CenterBox.defaultProps = {
    minHeight: 250
}
</code>```

But this code generates TSLint error: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.

So again: how can I correctly define defaultProps in my above stack (React + TypeScript)?

答:
Simplest for me is to define (partial) defaults in the defaultProps directly:</p>

```<code>export default class TSError extends React.Component<ITSErrorProps, {}> {
  private static defaultProps: Partial<ITSErrorProps> = {
    fullPage: true,
    controlClick: true,
    doubleClick: true
  };

...

}
</code>```

Body:
I'm using React with TypeScript and I've created stateless function. I've removed useless code from the example for readability.

interface CenterBoxProps extends React.Props<CenterBoxProps> {
    minHeight?: number;
}

export const CenterBox = (props: CenterBoxProps) => {
    const minHeight = props.minHeight || 250;
    const style = {
        minHeight: minHeight
    };
    return
Example div
;
};

Everything is great and this code is working correctly. But there's my question: how can I define defaultProps for CenterBox component?

As it is mentioned in react docs:

(...) They are pure functional transforms of their input, with zero
  boilerplate. However, you may still specify .propTypes and
  .defaultProps by setting them as properties on the function, just as
  you would set them on an ES6 class. (...)

it should be easy as:

CenterBox.defaultProps = {
    minHeight: 250
}

But this code generates TSLint error: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.

So again: how can I correctly define defaultProps in my above stack (React + TypeScript)?

Body:
Simplest for me is to define (partial) defaults in the defaultProps directly:

export default class TSError extends React.Component<ITSErrorProps, {}> {
  private static defaultProps: Partial<ITSErrorProps> = {
    fullPage: true,
    controlClick: true,
    doubleClick: true
  };

...

}


答:
They're the same.

Consider this:

```<code>{a: 1}    # => {:a=>1}
{:a => 1} # => {:a=>1}
</code>```

Use either form of assigning the value as Ruby is happy. The shorter form was added as a convenience, not because it was any better or was preferable.

Title: What is the difference between class: 'item' and :class => "item" in Ruby on Rails? Which style should I use?

Body:
They're the same.

Consider this:

{a: 1}    # => {:a=>1}
{:a => 1} # => {:a=>1}

Use either form of assigning the value as Ruby is happy. The shorter form was added as a convenience, not because it was any better or was preferable.


问:
Removing first three elements of 2d array C++
So here's my problem.. I have a 2d array of 2 char strings.

```<code>9D 5C 6S 9D KS 4S 9D
         9S
</code>```

If 3 found I need to delete the first 3 based on the first char.
card
My problem is I segfault almost anything i do...
pool is the 2d vector

```<code>        selection = "9S";
        while(col != GameBoard::pool.size()  ){
            while(GameBoard::pool[col][0].at(0) == selection.at(0) || cardsRem!=0){
                if(GameBoard::pool[col].size() == 1){
                    GameBoard::pool.erase(GameBoard::pool.begin() + col);
                    cardsRem--;
                }
                else{
                    GameBoard::pool[col].pop_back();
                    cardsRem--;
                }
            }
            if(GameBoard::pool[col][0].at(0) != selection.at(0)){
                col++;
            }
        }
</code>```

I've tried a series of for loops etc, and no luck! Any thoughts would save my sanity!

So I've tried to pull out a code segment to replicate it.  But I can't...
If I run my whole program in a loop it will eventually throw a segfault. If I run that exact code in the same circumstance it doesn't... I'm trying to figure out what I'm missing. I'll get back in if I figure out exactly where my issue is..

So in the end the issue is not my code itself, i've got memory leaks or something somewhere that are adding up to eventually crash my program... That tends to be in the same method each time I guess.

答:
The safer and most efficient way to erase some elements from a container is to apply the erase-remove idiom.

For instance, your snippet can be rewritten as the following (which is testable here):

```<code>using card_t = std::string;
std::vector<std::vector<card_t>> decks = {
    {"9D", "5C", "6S", "9D", "KS", "4S", "9D"},
    {"9S"}
};

card_t selection{"9S"};

// Predicate specifing which cards should be removed
auto has_same_rank = [rank = selection.at(0)] (card_t const& card) {
    return card.at(0) == rank;
};

auto & deck = decks.at(0);

// 'std::remove_if' removes all the elements satisfying the predicate from the range
// by moving the elements that are not to be removed at the beginning of the range
// and returns a past-the-end iterator for the new end of the range.

// 'std::vector::erase' removes from the vector the elements from the iterator
// returned by 'std::remove_if' up to the end iterator. Note that it invalidates
// iterators and references at or after the point of the erase, including the
// end() iterator (it's the most common cause of errors in code like OP's).
deck.erase(std::remove_if(deck.begin(), deck.end(), has_same_rank),
           deck.end());
</code>```

Body:
So here's my problem.. I have a 2d array of 2 char strings.

9D 5C 6S 9D KS 4S 9D
         9S

If 3 found I need to delete the first 3 based on the first char.
card
My problem is I segfault almost anything i do...
pool is the 2d vector

        selection = "9S";
        while(col != GameBoard::pool.size()  ){
            while(GameBoard::pool[col][0].at(0) == selection.at(0) || cardsRem!=0){
                if(GameBoard::pool[col].size() == 1){
                    GameBoard::pool.erase(GameBoard::pool.begin() + col);
                    cardsRem--;
                }
                else{
                    GameBoard::pool[col].pop_back();
                    cardsRem--;
                }
            }
            if(GameBoard::pool[col][0].at(0) != selection.at(0)){
                col++;
            }
        }

I've tried a series of for loops etc, and no luck! Any thoughts would save my sanity!

So I've tried to pull out a code segment to replicate it.  But I can't...
If I run my whole program in a loop it will eventually throw a segfault. If I run that exact code in the same circumstance it doesn't... I'm trying to figure out what I'm missing. I'll get back in if I figure out exactly where my issue is..

So in the end the issue is not my code itself, i've got memory leaks or something somewhere that are adding up to eventually crash my program... That tends to be in the same method each time I guess.

Body:
The safer and most efficient way to erase some elements from a container is to apply the erase-remove idiom.

For instance, your snippet can be rewritten as the following (which is testable here):

using card_t = std::string;
std::vector<std::vector<card_t>> decks = {
    {"9D", "5C", "6S", "9D", "KS", "4S", "9D"},
    {"9S"}
};

card_t selection{"9S"};

// Predicate specifing which cards should be removed
auto has_same_rank = [rank = selection.at(0)] (card_t const& card) {
    return card.at(0) == rank;
};

auto & deck = decks.at(0);

// 'std::remove_if' removes all the elements satisfying the predicate from the range
// by moving the elements that are not to be removed at the beginning of the range
// and returns a past-the-end iterator for the new end of the range.

// 'std::vector::erase' removes from the vector the elements from the iterator
// returned by 'std::remove_if' up to the end iterator. Note that it invalidates
// iterators and references at or after the point of the erase, including the
// end() iterator (it's the most common cause of errors in code like OP's).
deck.erase(std::remove_if(deck.begin(), deck.end(), has_same_rank),
           deck.end());


问:
Java JUnit Testing
Chris has written a function called toBinary that has an input parameter of an integer number and returns a string that represents the binary equivalent. For example, if the function is called with the integer number 3 then the returned string should be '11'.

Write a sequence of test specifications in English possibly using the "given", "when", and "then" sequence and their equivalent JUnit code.

My answer is:

The test should cover normal cases, extreme cases, and erroneous cases. Given an integer for example 3, it should then covert it to 11 after the method is executed.

```<code>@Test
public void testToBinary() {
Binary aBinary = new Binary();
assertEquals(3, 11);
assertEquals(2, 10);
assertFail(10, 8575);
}
</code>```

is this correct?

答:
First and foremost each unit test should have at most one assert.  As others have stated you must invoke the constructor or whichever method you are relying on in the actual test case:

assertEquals("11",toBinary(3);

Title: Java JUnit Testing

Body:
Chris has written a function called toBinary that has an input parameter of an integer number and returns a string that represents the binary equivalent. For example, if the function is called with the integer number 3 then the returned string should be '11'.

Write a sequence of test specifications in English possibly using the "given", "when", and "then" sequence and their equivalent JUnit code.

My answer is:

The test should cover normal cases, extreme cases, and erroneous cases. Given an integer for example 3, it should then covert it to 11 after the method is executed.

@Test
public void testToBinary() {
Binary aBinary = new Binary();
assertEquals(3, 11);
assertEquals(2, 10);
assertFail(10, 8575);
}

is this correct?