问:
How do I use Enum's static functions inside a generic class?
```<code>public class EnumFromInt<TEnum extends Enum<TEnum>> {

    private static TEnum[] _values;

    private static TEnum[] GetValues() {
        if (_values != null)
        {
            return _values;
        }

        _values = TEnum.values();
        return _values;
    }
}
</code>```

Above, there are two instances of "cannot be referenced from a static context". They seem separate, so I'll treat them as different problems. I'd like to understand both.

TEnum[] -  Why? It's an array of whatever type TEnum is. (Well, that's what I'd like it to be)

TEnum.values() - TEnum is declared to be of type Enum, so shouldn't I be able to use the static functions that belong to all enums?

答:
From your comment I've got an idea what you want to do.

In that case you would need to pass the enum's class and call getEnumConstants:

```<code>class EnumFromInt {

    private static final Map<Class<?>, Object[]> _values = new HashMap<>();

    @SuppressWarnings("unchecked")
    private static <TEnum extends Enum<TEnum>> TEnum[] getValues(Class<TEnum> cls) {
        return (TEnum[]) _values.computeIfAbsent(cls, Class::getEnumConstants);
    }
}
</code>```

You'd also have to use a Map, since a field could only store 1 array of values. There's no way to enforce that the type of the key correspond to the type of the value, so you need to store the value arrays as Object[] and use an unchecked cast later when retrieving them.

Body:
public class EnumFromInt<TEnum extends Enum<TEnum>> {

    private static TEnum[] _values;

    private static TEnum[] GetValues() {
        if (_values != null)
        {
            return _values;
        }

        _values = TEnum.values();
        return _values;
    }
}

Above, there are two instances of "cannot be referenced from a static context". They seem separate, so I'll treat them as different problems. I'd like to understand both.

TEnum[] -  Why? It's an array of whatever type TEnum is. (Well, that's what I'd like it to be)

TEnum.values() - TEnum is declared to be of type Enum, so shouldn't I be able to use the static functions that belong to all enums?

Body:
From your comment I've got an idea what you want to do.

In that case you would need to pass the enum's class and call getEnumConstants:

class EnumFromInt {

    private static final Map<Class<?>, Object[]> _values = new HashMap<>();

    @SuppressWarnings("unchecked")
    private static <TEnum extends Enum<TEnum>> TEnum[] getValues(Class<TEnum> cls) {
        return (TEnum[]) _values.computeIfAbsent(cls, Class::getEnumConstants);
    }
}

You'd also have to use a Map, since a field could only store 1 array of values. There's no way to enforce that the type of the key correspond to the type of the value, so you need to store the value arrays as Object[] and use an unchecked cast later when retrieving them.


来源: stackexchange

问:
Laravel Echo not using Auth Headers
I update the header like this:

```<code>window.setAuthToken = (token) => {
    window.Echo.options.auth.headers.Authorization = 'Bearer ' + token;
}
</code>```

The token is set in the Laravel Echo Headers, as seen here:

But it is not used, as seen here:

Why is Laravel Echo not using Auth Headers?

Edit:
I also tried dynamically update the endpoint like window.Echo.connector.options.authEndpoint = '';, and it is set in the options but not used by the request.

This is how I connect to the channel.

```<code>Echo.private('app.User.' + data.user_id)
    .notification((notification) => {
        dispatch('handle', notification);
    });
</code>```

答:
It seems like the way to do it was pretty close to what I was trying. Solution was found here.</p>

```<code>Echo.connector.pusher.config.auth.headers['Authorization'] = 'Bearer token';
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel Echo not using Auth Headers

Body:
I update the header like this:

window.setAuthToken = (token) => {
    window.Echo.options.auth.headers.Authorization = 'Bearer ' + token;
}

The token is set in the Laravel Echo Headers, as seen here:

But it is not used, as seen here:

Why is Laravel Echo not using Auth Headers?

Edit:
I also tried dynamically update the endpoint like window.Echo.connector.options.authEndpoint = '';, and it is set in the options but not used by the request.

This is how I connect to the channel.

Echo.private('app.User.' + data.user_id)
    .notification((notification) => {
        dispatch('handle', notification);
    });

Body:
It seems like the way to do it was pretty close to what I was trying. Solution was found here.

Echo.connector.pusher.config.auth.headers['Authorization'] = 'Bearer token';


问:
How do I include testing in an existing project created with vue cli?
When I do vue init webpack my-project according to these instructions, I'm given a questionaire where I'm asked if I want to include linting and testing. If I say yes, the project is set up with testing in place.

However in one of my vue projects, I started it out without saying yes.
But now, I want to include unit testing.

Traditional methods of installing Karma and Jasmine seems too cumbersome and I don't know which files I need to modify in order to wire up all the dependencies correctly.

Is there a CLI command that I can run, that asks me those questions again so that it wires up unit testing for me, automatically?

答:
Short answer

No you can't do that

Long answer

You should check out the source code for the vue template on GitHub.

What vue-cli does is use inquirer to prompt you for what you want, then it set some variables to define what should be included. Then it uses a combination of the static site generator metalsmith and mustache syntax to inject the code you specified you wanted into the files, and then spitting everything out into your specified project directory. It also filters out files you opted out of and doesn't put it in the root directory.

When the generated files are put into your project directory, all the inline mustaches and conditions in the js files and other files have been replaced with the correct source code matching what you specified you wanted, if these conditions were kept the syntax would be invalid and nothing would run without failing. Since these conditions and mustaches have been removed after generating a project, vue-cli wouldn't know where to put these things, and you would potentially need to remove code that conflict aswell, so it's simply impossible without adding back the conditions and mustache, and then you might aswell copy things over manually.

I recommend that in the future you opt into everything you think you might need, especially things like unit tests, as you don't have to use them, but there isn't an issue if you have them there, linting is also nice to always include, just decide on standard or airbnb and use it for all projects. Adding linting after the fact might require you to refactor the entire code-base if you used say semi-colons and added standard linting after you have coded much of the app.

Also, if you do explore the template code, you could potentially see what vue-cli does, and see what you need to add to a existing project, if generating the project again and copying things over is to much work.

ContentLicense: CC BY-SA 4.0


问:
Haskell: How to read user input to be used in a function inside of a do block?
I am attempting to run a simple palindrome program in Haskell but I want to request input from the user to be used in the program.

code:

```<code>palindrome :: String -> Bool
palindrome x = x == reverse x
main = do
  putStrLn "Brendon Bailey CSCI 4200-DB"
  putStrLn "Enter word to test for Palindrome"
  palindrome <- getLine
  putStrLn "Thanks"
</code>```

The code works but it just displays "thanks". If I exclude the last line of the block I get the "last line of do block must be expression" and if I include the actual palindrome code above the do block I get errors saying I need a "let" statement but incorporating one causes more errors. I am brand new to Haskell (and functional programming in general. I do java, c++, and web langs) I think the explanation here will be simple but after reading input output documentation on haskell I still can't figure out the proper way to accomplish this.

I'm doing it this way because my assignment stipulates that I must show the class info when the program is run. The palindrome part works fine without the do block. I'm just attempting to automatically output my text before testing a palindrome. Also how can I set up a haskell script to just run when loaded? I don't want the user to have to type "main" I want it to just run.

edit:

```<code>palindrome :: String -> Bool
palindrome x = x == reverse x
main = do
  putStrLn "Brendon Bailey CSCI 4200-DB"
  putStrLn "Enter Word"
  x <- getLine
  palindrome x
  putStrLn "thanks"
</code>```

This also doesn't work. How do I get the users input to use in the palindrome???

If the code:

```<code>palindrome :: String -> Bool
palindrome x = x == reverse x
</code>```

works when "palindrome "etc"" is entered in GHCi then why doesn't my second code version do the same thing???

edit 2:
Don't forget to enclose print statements in parentheses or Haskell will think it separate input is a separate argument. Dumb mistake but easy to make.

答:
This question is multiple questions in one, so I'll try to address each problem. I will address these in a different order to which they were stated in.

Before we begin, it must be said that you have critical misconceptions about the way Haskell works. I strongly recommend reading Learn You a Haskell for Great Good, which may seem juvenile, but is in fact a stellar introduction to functional programming, and in fact is the way many of us began learning Haskell.

Question 1: Compilation, GHC, and Haskell executables

(...) how can I set up a haskell script to just run when loaded? I don't want the user to have to type "main" I want it to just run.

You are confusing interpreted scripting languages like Python, Javascript, or Ruby, with compiled languages like C, Java, or Haskell.

Programs in interpreted languages are run by a program on the computer that contains information on how to interpret the text written, hence the name 'interpreted'. However, compiled languages are written, then converted from text into machine code, which is almost unreadable by humans, but which computers can run quickly.

When we write a complete, executable program in Haskell, we expect to compile it with The Glasgow Haskell Compiler, GHC (not GHCi). This looks something like this:

```<code>$ cat MyProgram.hs
main :: IO ()
main = putStrLn "This is my program!"
$ ghc MyProgram.hs
[1 of 1] Compiling Main             ( MyProgram.hs, MyProgram.o )
Linking MyProgram ...
$ ./MyProgram
This is my program!
</code>```

Now, MyProgram.hs was converted by GHC from a Haskell source code file into an executable, MyProgram. We defined an IO action, called main, to tell the compiler where we wanted it to begin. This is called an entry point, and is necessary to create a standalone executable. This is how Haskell programs are created and run.

Crucially, GHCi is not how Haskell programs are run. GHCi is an interactive environment for experimenting with Haskell functions and definitions. GHCi allows you to evaluate expressions (such as palindrome "Hello", or main) but is not intended as the way to run Haskell programs, in the same way that python's IDLE is for Python programs.

Question 2: Functions vs IO actions

(...) If you just have the palindrome code outside of the do block and the user enters "palindrome "etc"" in GHCi the program returns the boolean as output (...)

Haskell does not behave like languages you may be used to. Functions in Haskell are not programs. When you defined your function palindrome, you made a way for the computer to convert a String into a Bool. You did not tell it how to output that Bool in any way. Hence, there is an extra step: the IO monad.

Haskell programs are, in a way, represented as data, hence the somewhat strange type signature main :: IO (). I will not be explaining monads in detail here, but put simply, in a do-block, you can only state things of type IO a where a is any type. So, when you wrote:

```<code>main = do
    -- (...)
    palindrome x
    -- (...)
</code>```

It didn't make sense. Think of it this way: how can you 'run' or 'execute' a Bool? It's a boolean, not a program!

However, there is a function, called print, which allows you to do exactly that. Your line should be:

```<code>main = do
    -- (...)
    print (palindrome x)
    -- (...)
</code>```

I won't go into prints type signature, but rest assured that it does indeed return an IO (), which allows us to put it into a do-block. By the way, if you write:

```<code>palindrome :: String -> Bool
palindrome x = x == reverse x

main = do
  putStrLn "Brendon Bailey CSCI 4200-DB"
  putStrLn "Enter Word"
  x <- getLine
  print (palindrome x)
  putStrLn "thanks"
</code>```

...and compile the file with GHC, you will get the desired effect, assuming you did in fact want the program to output True or False. In fact, I compiled this as Palindromes.hs, and here's the result:

```<code>$ ghc Palindromes.hs
[1 of 1] Compiling Main             ( Palindromes.hs, Palindromes.o )
Linking Palindromes ...
$ ./Palindromes
Brendon Bailey CSCI 4200-DB
Enter Word
amanaplanacanalpanama
True
thanks
</code>```

Question 3: GHCi as a testing environment

[My code] works when "palindrome "etc"" is entered in GHCi then why doesn't my second code version do the same thing???

GHCi, as stated before, is different from GHC, in that it is an environment to test and 'play' with Haskell code before writing standalone programs.

In GHCi, you write expressions, and they are evaluated (using GHC's machinery), the result is printed, and it loops, Hence, this kind of system is often called a Read-Evaluate-Print-Loop, or a REPL.

Let's examine a bit of code in GHCi:

```<code>λ let plusOne n = n + 1
λ plusOne 5
6
</code>```

The first line defines a value (here a function) that we can use later. The second line, however, is not a definition, but an expression. Hence, GHCi evaluates it, and prints the result.

GHCi can also execute IO actions:

```<code>λ let myProgram = putStrLn "Hello!"
λ myProgram
Hello!
</code>```

This works because evaluating an IO action in Haskell is equivalent to executing them: this is how Haskell is designed to work - it's a truly brilliant idea provided that you grasp it.

Even though we see these similarities, GHCi is not equivalent to a Haskell program, as one might expect after using Python. GHCi unfortunately bears little resemblance to 'real' Haskell code, because Haskell works in a fundamentally different way to most other languages.

GHCi is nothing more than a useful way to quickly see results of our code, as well as other useful information that I won't explain here.

Other points

Monads are a key part of the problem here. There have been many, many questions on Monads here on StackOverflow as they tend to be a sticking point, so any questions you may have are likely here. This makes things difficult, since Haskell IO cannot be fully appreciated without an understanding of Monads. There is an LYAH chapter on Monads.

Body:
I am attempting to run a simple palindrome program in Haskell but I want to request input from the user to be used in the program.

code:

palindrome :: String -> Bool
palindrome x = x == reverse x
main = do
  putStrLn "Brendon Bailey CSCI 4200-DB"
  putStrLn "Enter word to test for Palindrome"
  palindrome <- getLine
  putStrLn "Thanks"

The code works but it just displays "thanks". If I exclude the last line of the block I get the "last line of do block must be expression" and if I include the actual palindrome code above the do block I get errors saying I need a "let" statement but incorporating one causes more errors. I am brand new to Haskell (and functional programming in general. I do java, c++, and web langs) I think the explanation here will be simple but after reading input output documentation on haskell I still can't figure out the proper way to accomplish this.

I'm doing it this way because my assignment stipulates that I must show the class info when the program is run. The palindrome part works fine without the do block. I'm just attempting to automatically output my text before testing a palindrome. Also how can I set up a haskell script to just run when loaded? I don't want the user to have to type "main" I want it to just run.

edit:

palindrome :: String -> Bool
palindrome x = x == reverse x
main = do
  putStrLn "Brendon Bailey CSCI 4200-DB"
  putStrLn "Enter Word"
  x <- getLine
  palindrome x
  putStrLn "thanks"

This also doesn't work. How do I get the users input to use in the palindrome???

If the code:

palindrome :: String -> Bool
palindrome x = x == reverse x

works when "palindrome "etc"" is entered in GHCi then why doesn't my second code version do the same thing???

edit 2:
Don't forget to enclose print statements in parentheses or Haskell will think it separate input is a separate argument. Dumb mistake but easy to make.

Body:
This question is multiple questions in one, so I'll try to address each problem. I will address these in a different order to which they were stated in.

Before we begin, it must be said that you have critical misconceptions about the way Haskell works. I strongly recommend reading Learn You a Haskell for Great Good, which may seem juvenile, but is in fact a stellar introduction to functional programming, and in fact is the way many of us began learning Haskell.

Question 1: Compilation, GHC, and Haskell executables

(...) how can I set up a haskell script to just run when loaded? I don't want the user to have to type "main" I want it to just run.

You are confusing interpreted scripting languages like Python, Javascript, or Ruby, with compiled languages like C, Java, or Haskell.

Programs in interpreted languages are run by a program on the computer that contains information on how to interpret the text written, hence the name 'interpreted'. However, compiled languages are written, then converted from text into machine code, which is almost unreadable by humans, but which computers can run quickly.

When we write a complete, executable program in Haskell, we expect to compile it with The Glasgow Haskell Compiler, GHC (not GHCi). This looks something like this:

$ cat MyProgram.hs
main :: IO ()
main = putStrLn "This is my program!"
$ ghc MyProgram.hs
[1 of 1] Compiling Main             ( MyProgram.hs, MyProgram.o )
Linking MyProgram ...
$ ./MyProgram
This is my program!

Now, MyProgram.hs was converted by GHC from a Haskell source code file into an executable, MyProgram. We defined an IO action, called main, to tell the compiler where we wanted it to begin. This is called an entry point, and is necessary to create a standalone executable. This is how Haskell programs are created and run.

Crucially, GHCi is not how Haskell programs are run. GHCi is an interactive environment for experimenting with Haskell functions and definitions. GHCi allows you to evaluate expressions (such as palindrome "Hello", or main) but is not intended as the way to run Haskell programs, in the same way that python's IDLE is for Python programs.

Question 2: Functions vs IO actions

(...) If you just have the palindrome code outside of the do block and the user enters "palindrome "etc"" in GHCi the program returns the boolean as output (...)

Haskell does not behave like languages you may be used to. Functions in Haskell are not programs. When you defined your function palindrome, you made a way for the computer to convert a String into a Bool. You did not tell it how to output that Bool in any way. Hence, there is an extra step: the IO monad.

Haskell programs are, in a way, represented as data, hence the somewhat strange type signature main :: IO (). I will not be explaining monads in detail here, but put simply, in a do-block, you can only state things of type IO a where a is any type. So, when you wrote:

main = do
    -- (...)
    palindrome x
    -- (...)

It didn't make sense. Think of it this way: how can you 'run' or 'execute' a Bool? It's a boolean, not a program!

However, there is a function, called print, which allows you to do exactly that. Your line should be:

main = do
    -- (...)
    print (palindrome x)
    -- (...)

I won't go into prints type signature, but rest assured that it does indeed return an IO (), which allows us to put it into a do-block. By the way, if you write:

palindrome :: String -> Bool
palindrome x = x == reverse x

main = do
  putStrLn "Brendon Bailey CSCI 4200-DB"
  putStrLn "Enter Word"
  x <- getLine
  print (palindrome x)
  putStrLn "thanks"

...and compile the file with GHC, you will get the desired effect, assuming you did in fact want the program to output True or False. In fact, I compiled this as Palindromes.hs, and here's the result:

$ ghc Palindromes.hs
[1 of 1] Compiling Main             ( Palindromes.hs, Palindromes.o )
Linking Palindromes ...
$ ./Palindromes
Brendon Bailey CSCI 4200-DB
Enter Word
amanaplanacanalpanama
True
thanks

Question 3: GHCi as a testing environment

[My code] works when "palindrome "etc"" is entered in GHCi then why doesn't my second code version do the same thing???

GHCi, as stated before, is different from GHC, in that it is an environment to test and 'play' with Haskell code before writing standalone programs.

In GHCi, you write expressions, and they are evaluated (using GHC's machinery), the result is printed, and it loops, Hence, this kind of system is often called a Read-Evaluate-Print-Loop, or a REPL.

Let's examine a bit of code in GHCi:

λ let plusOne n = n + 1
λ plusOne 5
6

The first line defines a value (here a function) that we can use later. The second line, however, is not a definition, but an expression. Hence, GHCi evaluates it, and prints the result.

GHCi can also execute IO actions:

λ let myProgram = putStrLn "Hello!"
λ myProgram
Hello!

This works because evaluating an IO action in Haskell is equivalent to executing them: this is how Haskell is designed to work - it's a truly brilliant idea provided that you grasp it.

Even though we see these similarities, GHCi is not equivalent to a Haskell program, as one might expect after using Python. GHCi unfortunately bears little resemblance to 'real' Haskell code, because Haskell works in a fundamentally different way to most other languages.

GHCi is nothing more than a useful way to quickly see results of our code, as well as other useful information that I won't explain here.

Other points

Monads are a key part of the problem here. There have been many, many questions on Monads here on StackOverflow as they tend to be a sticking point, so any questions you may have are likely here. This makes things difficult, since Haskell IO cannot be fully appreciated without an understanding of Monads. There is an LYAH chapter on Monads.


问:
Best way to compare std::strings
What is the best way to compare std::strings? The obvious way would be with if/else:

```<code>std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.
</code>```

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?

答:
"12" isn't a lot... but anyway.

You can only use a switch for integral types (char, int, etc.), so that's out of the question for std::string. Using a map would probably be more readable.

Then again, it all depends on how you define "best".

Title: Best way to compare std::strings

Body:
What is the best way to compare std::strings? The obvious way would be with if/else:

std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?

ContentLicense: CC BY-SA 2.5


问:
Convert CSV import to a string
I have a script:

```<code>import csv

with open('2017020397.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(' '.join(row))
</code>```

Output looks like this:

LastName StartTime EndTime Duration Period TeamAbbrev Pos
Bouwmeester 0:00 0:37 0:37 1 STL D
Schwartz 0:00 0:40 0:40 1 STL W
Foligno 0:00 0:40 0:40 1 MIN W
Pietrangelo 0:00 0:48 0:48 1 STL D
Suter 0:00 0:40 0:40 1 MIN D
```

Instead of printing the rows, I would like the rows to equal data. Then I can just say print(data). New to python and writing scripts.

答:
This does it:

```<code>import csv

with open('2017020397.csv', newline='') as f:
    data = '\n'.join(' '.join(row) for row in csv.reader(f))

print(data)
</code>```

Output:

LastName StartTime EndTime Duration Period TeamAbbrev Pos
Bouwmeester 0:00 0:37 0:37 1 STL D
Schwartz 0:00 0:40 0:40 1 STL W
Foligno 0:00 0:40 0:40 1 MIN W
Pietrangelo 0:00 0:48 0:48 1 STL D
Suter 0:00 0:40 0:40 1 MIN D
```

<p>In order to leave the header out, you'd need to do it slightly differently:</p>

```with open('2017020397.csv', newline='') as f:
    reader = csv.reader(f)
    next(reader)  # Skip header row.
    data = '\n'.join(' '.join(row) for row in reader)

print(data)
```

<p>Output ignoring header:</p>

<pre class="lang-none prettyprint-override"><code>Bouwmeester 0:00 0:37 0:37 1 STL D
Schwartz 0:00 0:40 0:40 1 STL W
Foligno 0:00 0:40 0:40 1 MIN W
Pietrangelo 0:00 0:48 0:48 1 STL D
Suter 0:00 0:40 0:40 1 MIN D
</code>```

Title: Convert CSV import to a string

Body:
I have a script:

import csv

with open('2017020397.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(' '.join(row))

Output looks like this:

LastName StartTime EndTime Duration Period TeamAbbrev Pos
Bouwmeester 0:00 0:37 0:37 1 STL D
Schwartz 0:00 0:40 0:40 1 STL W
Foligno 0:00 0:40 0:40 1 MIN W
Pietrangelo 0:00 0:48 0:48 1 STL D
Suter 0:00 0:40 0:40 1 MIN D

Instead of printing the rows, I would like the rows to equal data. Then I can just say print(data). New to python and writing scripts.

Body:
This does it:

import csv

with open('2017020397.csv', newline='') as f:
    data = '\n'.join(' '.join(row) for row in csv.reader(f))

print(data)

Output:

LastName StartTime EndTime Duration Period TeamAbbrev Pos
Bouwmeester 0:00 0:37 0:37 1 STL D
Schwartz 0:00 0:40 0:40 1 STL W
Foligno 0:00 0:40 0:40 1 MIN W
Pietrangelo 0:00 0:48 0:48 1 STL D
Suter 0:00 0:40 0:40 1 MIN D

In order to leave the header out, you'd need to do it slightly differently:

with open('2017020397.csv', newline='') as f:
    reader = csv.reader(f)
    next(reader)  # Skip header row.
    data = '\n'.join(' '.join(row) for row in reader)

print(data)

Output ignoring header:

Bouwmeester 0:00 0:37 0:37 1 STL D
Schwartz 0:00 0:40 0:40 1 STL W
Foligno 0:00 0:40 0:40 1 MIN W
Pietrangelo 0:00 0:48 0:48 1 STL D
Suter 0:00 0:40 0:40 1 MIN D


问:
powershell retrieve members of group recursively
I got a pretty big audit project that I'm hoping to automate.

I need to get every user's name, SamAccountName, Title and Department who are part of a group. Problem is, the group has groups within it and those groups have groups within them. Another problem is that about 99% of all the groups have an asterisk in it's Display Name (NOT SamAccountName).

Here is the code I currently have, it works fine until it receives a group with an asterisk in it's name.. (hence the .Replace("*","") part.... Anyone got any ideas on how to fix this?

```<code>function Get-NestedGroupMember {
[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [string]$Group
)
$broke = @();
## Find all members  in the group specified
$members = Get-ADGroupMember -Identity $Group
foreach ($member in $members){
    ## If any member in  that group is another group just call this function again
    if ($member.objectClass -eq 'group'){
        $memberGroup = $($member.Name).Replace("*", "")
        try{
            Get-NestedGroupMember -Group "$($memberGroup)"
        }catch{
            $broke += "$($memberGroup)`n"
        }
    }else{
        ## otherwise, just  output the non-group object (probably a user account)
        $member.Name
    }
}
Write-Host "`nThe following groups could not be found automatically.`n`n$($broke)"
}

$getGroup = Read-Host -Prompt "Group name"

Get-NestedGroupMember $getGroup
</code>```

答:
As Bill_Stewart said, you are trying to implement functionality that already exists for you. Get-ADGroupMember has a -Recursive parameter that will search all of the nested groups and get the members for you. You can then pipe the output to a select and get only the properties you care about.

```<code>AD:
  TopGroup
    Betty
    Bob
    NestedGroup1
      Joe
      Frank
    NestedGroup2
      George
      Herman
</code>```

Using -Recursive

```<code>Get-AdGroupMember TopGroup -Recursive | Select-Object SamAccountName
Betty
Bob
Joe
Frank
George
Herman
</code>```

Body:
I got a pretty big audit project that I'm hoping to automate.

I need to get every user's name, SamAccountName, Title and Department who are part of a group. Problem is, the group has groups within it and those groups have groups within them. Another problem is that about 99% of all the groups have an asterisk in it's Display Name (NOT SamAccountName).

Here is the code I currently have, it works fine until it receives a group with an asterisk in it's name.. (hence the .Replace("*","") part.... Anyone got any ideas on how to fix this?

function Get-NestedGroupMember {
[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [string]$Group
)
$broke = @();
## Find all members  in the group specified
$members = Get-ADGroupMember -Identity $Group
foreach ($member in $members){
    ## If any member in  that group is another group just call this function again
    if ($member.objectClass -eq 'group'){
        $memberGroup = $($member.Name).Replace("*", "")
        try{
            Get-NestedGroupMember -Group "$($memberGroup)"
        }catch{
            $broke += "$($memberGroup)`n"
        }
    }else{
        ## otherwise, just  output the non-group object (probably a user account)
        $member.Name
    }
}
Write-Host "`nThe following groups could not be found automatically.`n`n$($broke)"
}

$getGroup = Read-Host -Prompt "Group name"

Get-NestedGroupMember $getGroup

Body:
As Bill_Stewart said, you are trying to implement functionality that already exists for you. Get-ADGroupMember has a -Recursive parameter that will search all of the nested groups and get the members for you. You can then pipe the output to a select and get only the properties you care about.

AD:
  TopGroup
    Betty
    Bob
    NestedGroup1
      Joe
      Frank
    NestedGroup2
      George
      Herman

Using -Recursive

Get-AdGroupMember TopGroup -Recursive | Select-Object SamAccountName
Betty
Bob
Joe
Frank
George
Herman


答:
because they are not the same thing Haskell is a pure functional programming .
with no side effects ,for example if a sum function changes a global variable, or prints the sum before returning it, those are side effects. Functions in most other languages frequently have side effects, typically making them hard to analyze. Functional programming languages seek to avoid side effects when possible.

in this case reading and writing to IO is side effects.
operations that have side effects are handled by Monad (do) == (>>=)

this is valid code

```<code>palindrome :: String -> Bool
palindrome x = x == reverse x
main = do
  putStrLn "Brendon Bailey CSCI 4200-DB"
  putStrLn "Enter Word"
  x <- getLine
  let y = palindrome x
  putStrLn "thanks"
  print y
</code>```

here is a good explanations about Monads

Title: Haskell: How to read user input to be used in a function inside of a do block?

Body:
because they are not the same thing Haskell is a pure functional programming .
with no side effects ,for example if a sum function changes a global variable, or prints the sum before returning it, those are side effects. Functions in most other languages frequently have side effects, typically making them hard to analyze. Functional programming languages seek to avoid side effects when possible.

in this case reading and writing to IO is side effects.
operations that have side effects are handled by Monad (do) == (>>=)

this is valid code

palindrome :: String -> Bool
palindrome x = x == reverse x
main = do
  putStrLn "Brendon Bailey CSCI 4200-DB"
  putStrLn "Enter Word"
  x <- getLine
  let y = palindrome x
  putStrLn "thanks"
  print y

here is a good explanations about Monads


问:
Editing a row in a database table affects all previous records that query that information. How should prior versions be stored/managed?
I’ve been working on a Windows Form App using vb.net that retrieves information from a SQL database. One of the forms, frmContract, queries several tables, such as Addresses, and displays them in various controls, such as Labels and DataGridViews. Every year, the customer’s file is either renewed or expired, and I’m just now realizing that a change committed to any record today will affect the information displayed for the customer in the past. For example, if we update a customer’s mailing address today, this new address will show up in all previous customer profiles. What is the smartest way to avoid this problem without creating separate rows in each table with the same information? Or to put it another way, how can versions of a customer’s profile be preserved?

Another example would be a table that stores customer’s vehicles.

```<code>VehicleID | Year | Make | Model  | VIN                | Body
---------------------------------------------------------------
1         | 2005 | Ford | F150   | 11111111111111111  | Pickup
2         | 2001 | Niss | Sentra | 22222222222222222  | Sedan
3         | 2004 | Intl | 4700   | 33333333333333333  | Car Carrier
</code>```

If today vehicle 1 is changed from a standard pickup to a flatbed, then if I load the customer contract from 2016 it will also show as flatbed even though back then it was a pickup truck.

I have a table for storing individual clients.

```<code>ClientID | First    | Last      | DOB
---------|----------|-----------|------------
1        | John     | Doe       | 01/01/1980
2        | Mickey   | Mouse     | 11/18/1928
3        | Eric     | Forman    | 03/05/1960
</code>```

I have another table to store yearly contracts.

```<code>ContractID | ContractNo | EffectiveDate | ExpirationDate    | ClientID (foreign key)
-----------|------------|---------------|-------------------|-----------
1          | 13579      | 06/15/2013    | 06/15/2014        | 1
2          | 13579      | 06/15/2014    | 06/15/2015        | 1
3          | 24680      | 10/05/2016    | 10/05/2017        | 3
</code>```

Notice that the contract number can remain the same across different periods. In addition, because the same vehicle can be related to multiple contracts, I use a bridge table to relate individual vehicles to different contracts.

```<code>Id | VehicleID | ContractID   <-- both foreign keys
---|-----------|------------
1  | 1         | 1
2  | 3         | 1
3  | 1         | 2
4  | 3         | 2
5  | 2         | 3
6  | 2         | 2
</code>```

When frmContract is loaded, it queries the database and displays information about that particular contract year. However, if Vehicle 1 is changed from pickup to flatbed right now, then all the previous contract years will also show it as a flatbed.

I hope this illustrates my predicament. Any guidance will be appreaciated.

答: Some DB systems have built-in temporal features so you can keep audit history of rows.  Check to see if your DB has built-in support for this.</p>

Body:
I’ve been working on a Windows Form App using vb.net that retrieves information from a SQL database. One of the forms, frmContract, queries several tables, such as Addresses, and displays them in various controls, such as Labels and DataGridViews. Every year, the customer’s file is either renewed or expired, and I’m just now realizing that a change committed to any record today will affect the information displayed for the customer in the past. For example, if we update a customer’s mailing address today, this new address will show up in all previous customer profiles. What is the smartest way to avoid this problem without creating separate rows in each table with the same information? Or to put it another way, how can versions of a customer’s profile be preserved?

Another example would be a table that stores customer’s vehicles.

VehicleID | Year | Make | Model  | VIN                | Body
---------------------------------------------------------------
1         | 2005 | Ford | F150   | 11111111111111111  | Pickup
2         | 2001 | Niss | Sentra | 22222222222222222  | Sedan
3         | 2004 | Intl | 4700   | 33333333333333333  | Car Carrier

If today vehicle 1 is changed from a standard pickup to a flatbed, then if I load the customer contract from 2016 it will also show as flatbed even though back then it was a pickup truck.

I have a table for storing individual clients.

ClientID | First    | Last      | DOB
---------|----------|-----------|------------
1        | John     | Doe       | 01/01/1980
2        | Mickey   | Mouse     | 11/18/1928
3        | Eric     | Forman    | 03/05/1960

I have another table to store yearly contracts.

ContractID | ContractNo | EffectiveDate | ExpirationDate    | ClientID (foreign key)
-----------|------------|---------------|-------------------|-----------
1          | 13579      | 06/15/2013    | 06/15/2014        | 1
2          | 13579      | 06/15/2014    | 06/15/2015        | 1
3          | 24680      | 10/05/2016    | 10/05/2017        | 3

Notice that the contract number can remain the same across different periods. In addition, because the same vehicle can be related to multiple contracts, I use a bridge table to relate individual vehicles to different contracts.

Id | VehicleID | ContractID   <-- both foreign keys
---|-----------|------------
1  | 1         | 1
2  | 3         | 1
3  | 1         | 2
4  | 3         | 2
5  | 2         | 3
6  | 2         | 2

When frmContract is loaded, it queries the database and displays information about that particular contract year. However, if Vehicle 1 is changed from pickup to flatbed right now, then all the previous contract years will also show it as a flatbed.

I hope this illustrates my predicament. Any guidance will be appreaciated.


问:
string with values selection based on values
I have a set with 2 values  </p>

```<code>list = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]
</code>```

<p>how can I keep only those values that have score bigger than 1? </p>

答:
```<code>list_of_stuff = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]
newlist = [x for x in list_of_stuff if x[1] > 1.0]
print newlist
</code>```

<p>will result in </p>

```<code>[('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334)]
</code>```

Body:
I have a set with 2 values

list = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]

how can I keep only those values that have score bigger than 1?

Body:
list_of_stuff = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]
newlist = [x for x in list_of_stuff if x[1] > 1.0]
print newlist

will result in

[('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334)]


问:
Is it possible to rename a file during copy with Nuspec files node
I am currently working on changing our codebase to use Nuget. As part of the process the copying of ressources to the output directory should be moved from postbuild events in the projects to the files tag in the .nuspec file.

For the particular project the ressource was called Resources.resx and is renamed to something more specific during the copy (yes I know great programming - not mine and not my place to change it).

Is it possible to change the filename using the file node in nuspec or do I need to keep a postbuild in this case?

My attemp of renaming it with the target property fails:

```<code>< file src="foo/bar.resx" target="foo/foobar.resx"/>
</code>```

creates the following output:
"foo/foobar.resx/bar.rex"

I found a familiar problem on github but it was rejected due to being posted on a dead branch and not trying to rename a file but change its type.

https://github.com/NuGet/Home/issues/2019

Thanks for the help

答: This functionality is not built into NuGet. The only conceivable way to do this would be to implement a powershell script (install.ps1) that would handle the rename of both the file and the csproj. </p>

Body:
I am currently working on changing our codebase to use Nuget. As part of the process the copying of ressources to the output directory should be moved from postbuild events in the projects to the files tag in the .nuspec file.

For the particular project the ressource was called Resources.resx and is renamed to something more specific during the copy (yes I know great programming - not mine and not my place to change it).

Is it possible to change the filename using the file node in nuspec or do I need to keep a postbuild in this case?

My attemp of renaming it with the target property fails:

< file src="foo/bar.resx" target="foo/foobar.resx"/>

creates the following output:
"foo/foobar.resx/bar.rex"

I found a familiar problem on github but it was rejected due to being posted on a dead branch and not trying to rename a file but change its type.

https://github.com/NuGet/Home/issues/2019

Thanks for the help


问:
Laravel 5 Eloquent: How to get raw sql that is being executed? (with binded data)
Im trying to figure out how to get the raw sql query being executed including the binded data in it. Here is what ive got:

```<code>\DB::connection()->enableQueryLog();
$query = \DB::getQueryLog();
$lastQuery = end($query);
</code>```

And here is what the result looks like:

```<code>array(3) {
  ["query"]=>
  string(57) "select * from `table_1` where `field_1` = ? limit 1"
  ["bindings"]=>
  array(1) {
    [0]=>
    string(34) "xyz"
  }
}
</code>```

So how do I get a dump of a full sql query like this (the good old fashioned way)?

```<code>select * from `table_1` where `field_1` = 'xyz' limit 1
</code>```

Thanks

答:
You may want to check out the Laravel debugbar. I wouldn't develop a Laravel app without it. It will give you a breakdown of all queries (including repeated queries and ajax queries), with the speed they executed at and a note to the line in the controller/method that called them. (It provides TONS more info as well, such as views, gates, routes, etc.)

Also, Laravel has a toSql() method that you can use instead of your example. It will only show you the prepared statement as your example does, but it's at least a little cleaner. If you use toSql(), you have to apply it before you execute the query though.

```<code>$foo = Foo::where('bar', 'baz');
$foo_sql = $foo->toSql();
$foo->get();
</code>```

Body:
Im trying to figure out how to get the raw sql query being executed including the binded data in it. Here is what ive got:

\DB::connection()->enableQueryLog();
$query = \DB::getQueryLog();
$lastQuery = end($query);

And here is what the result looks like:

array(3) {
  ["query"]=>
  string(57) "select * from `table_1` where `field_1` = ? limit 1"
  ["bindings"]=>
  array(1) {
    [0]=>
    string(34) "xyz"
  }
}

So how do I get a dump of a full sql query like this (the good old fashioned way)?

select * from `table_1` where `field_1` = 'xyz' limit 1

Thanks

Body:
You may want to check out the Laravel debugbar. I wouldn't develop a Laravel app without it. It will give you a breakdown of all queries (including repeated queries and ajax queries), with the speed they executed at and a note to the line in the controller/method that called them. (It provides TONS more info as well, such as views, gates, routes, etc.)

Also, Laravel has a toSql() method that you can use instead of your example. It will only show you the prepared statement as your example does, but it's at least a little cleaner. If you use toSql(), you have to apply it before you execute the query though.

$foo = Foo::where('bar', 'baz');
$foo_sql = $foo->toSql();
$foo->get();


问:
(42,18): error CS1525: Unexpected symbol (', expecting,', ;', or=
I am making a game in unity, where i will make a time system. But im getting this error "(42,18): error CS1525: Unexpected symbol (', expecting,', ;', or='" and i can not find out why i doesnt want work.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TimeManager : MonoBehaviour {

    public int seconds = 0;
    public int minutes = 0;
    public int hours = 0;
    public int days = 0;
    public int year = 0;
    public Text TotalTimePlayed;

    void Start(){
        StartCoroutine(time());
    }

    void Update(){
        TotalTimePlayed = year + " Y" + days + " D" + hours + " H" + minutes + " M" + seconds + " S";
    }

    private void timeAdd(){
        seconds += 1;
        if(seconds >= 60){
            minutes = 1;
        }

        if(minutes >= 60){
            hours = 1;
        }

        if(hours >= 24){
            days = 1;
        }

        if(days >= 365){
            year = 1;
        }

        IEnumerator time() {  // Its in this line there is an error.
            while (true){
                timeAdd();
                yield return new WaitForSeconds(1);
            }
        }
    }
}
</code>```

What would work better/at all? Right now im getting the error "(42,18): error CS1525: Unexpected symbol (', expecting,', ;', or='"

Thanks for your help.

答:
You've nested the time() function inside of timeAdd(), and I'm assuming you don't have C# 7 support for local functions. Pull the time() function out of timeAdd() to look like this:</p>

```<code>private void timeAdd(){
    seconds += 1;
    if(seconds >= 60){
        minutes = 1;
    }

    if(minutes >= 60){
        hours = 1;
    }

    if(hours >= 24){
        days = 1;
    }

    if(days >= 365){
        year = 1;
    }
}

IEnumerator time() {  // Its in this line there is an error.
    while (true){
        timeAdd();
        yield return new WaitForSeconds(1);
    }
}
</code>```

Body:
I am making a game in unity, where i will make a time system. But im getting this error "(42,18): error CS1525: Unexpected symbol (', expecting,', ;', or='" and i can not find out why i doesnt want work.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TimeManager : MonoBehaviour {

    public int seconds = 0;
    public int minutes = 0;
    public int hours = 0;
    public int days = 0;
    public int year = 0;
    public Text TotalTimePlayed;

    void Start(){
        StartCoroutine(time());
    }

    void Update(){
        TotalTimePlayed = year + " Y" + days + " D" + hours + " H" + minutes + " M" + seconds + " S";
    }

    private void timeAdd(){
        seconds += 1;
        if(seconds >= 60){
            minutes = 1;
        }

        if(minutes >= 60){
            hours = 1;
        }

        if(hours >= 24){
            days = 1;
        }

        if(days >= 365){
            year = 1;
        }

        IEnumerator time() {  // Its in this line there is an error.
            while (true){
                timeAdd();
                yield return new WaitForSeconds(1);
            }
        }
    }
}

What would work better/at all? Right now im getting the error "(42,18): error CS1525: Unexpected symbol (', expecting,', ;', or='"

Thanks for your help.

Body:
You've nested the time() function inside of timeAdd(), and I'm assuming you don't have C# 7 support for local functions. Pull the time() function out of timeAdd() to look like this:

private void timeAdd(){
    seconds += 1;
    if(seconds >= 60){
        minutes = 1;
    }

    if(minutes >= 60){
        hours = 1;
    }

    if(hours >= 24){
        days = 1;
    }

    if(days >= 365){
        year = 1;
    }
}

IEnumerator time() {  // Its in this line there is an error.
    while (true){
        timeAdd();
        yield return new WaitForSeconds(1);
    }
}


问:
Move an image to the left every time I press enter
The image moves to the left once correctly, but afterwards I press enter again it doesn't move. I'm looking for it to move left 10 more pixels everytime I press enter. Thanks</p>

```<code>    document.body.addEventListener("keydown", function (event) {
        if (event.keyCode === 13)  {

       document.getElementById("wagon").style.left=-10 + "px";
   }
  });
</code>```

答:
In your code above, it should be        </p>

```<code>document.getElementById("wagon").style.left -= 10 + "px";
</code>```

Body:
The image moves to the left once correctly, but afterwards I press enter again it doesn't move. I'm looking for it to move left 10 more pixels everytime I press enter. Thanks

    document.body.addEventListener("keydown", function (event) {
        if (event.keyCode === 13)  {

       document.getElementById("wagon").style.left=-10 + "px";
   }
  });

Body:
In your code above, it should be

document.getElementById("wagon").style.left -= 10 + "px";


答:
using operator== is pretty good, but if performance is really critical, you can improve it depending on your use case. If the goal is to pick one of a few choices and perform a specific action, you can use a TRIE. Also if the strings are different enough, you could do something like this:

```<code>switch(s[0]) {
case 'a':
    // only compare to strings which start with an 'a'
    if(s == "abcd") {

    } else if (s == "abcde") {

    }
    break;
case 'b':
    // only compare to strings which start with an 'b'
    if(s == "bcd") {

    } else if (s == "bcde") {

    }
    break;
default:
    // we know right away it doesn't match any of the above 4 choices...
}
</code>```

basically use a certain character in the string which good uniqueness (doesn't have to be the first if all strings are at least N in length any character before N will do!) to do a switch then do a series of compares on a subset of the strings which match that unique characteristic

Title: Best way to compare std::strings

Body:
using operator== is pretty good, but if performance is really critical, you can improve it depending on your use case. If the goal is to pick one of a few choices and perform a specific action, you can use a TRIE. Also if the strings are different enough, you could do something like this:

switch(s[0]) {
case 'a':
    // only compare to strings which start with an 'a'
    if(s == "abcd") {

    } else if (s == "abcde") {

    }
    break;
case 'b':
    // only compare to strings which start with an 'b'
    if(s == "bcd") {

    } else if (s == "bcde") {

    }
    break;
default:
    // we know right away it doesn't match any of the above 4 choices...
}

basically use a certain character in the string which good uniqueness (doesn't have to be the first if all strings are at least N in length any character before N will do!) to do a switch then do a series of compares on a subset of the strings which match that unique characteristic


问:
View with minHeight in ConstraintLayout
I have a ConstraintLayout inside a NestedScrollView. The ConstraintLayout contains a bunch of views but the last View can have a dynamic height to fill up the bottom space if there is any but it also needs to be a minimum height if there is not enough space.

For arguments sake, here is an example.

```<code><android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:layout_height="match_parent">

        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintHeight_min="1500dp"
            android:background="@color/red"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

    </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

As you can see I have put the ConstraintLayout version in but it doesn't work. Obviously the values are ridiculously large but this is just for testing.

If I don't set fillViewport="true" on the NestedScrollView then ConstraintLayout has a height of 0. When I do set the fillViewport, the ConstraintLayout does not scroll but just fills the screen.

How can I set the View so that it expands to the bottom of the ConstraintLayout which should be as big as the Viewport but if my View is not of the minHeight then we allow scrolling?

I am using version 1.0.2 of the ConstraintLayout library.

What I expect to see is the being all the way to the bottom of the parent but if that size is less than 1500dp then the view scrolls.

I have entered 1500dp like so android:layout_height="1500dp" and the view scrolls accordingly.

UPDATE 1

Seems to be once I put the layout within a FragmentViewPager. The app:layout_constraintHeight_min property isn't respected and it only matches the height of the viewport.

I also tried taking the NestedScrollView out of the fragment and putting the ViewPager inside it but again didn't work.

答:
Add this attribute to the view you'd like to have stretch:

```<code>app:layout_constraintHeight_default="spread"
</code>```

I made a tiny app to demonstrate. No java logic to speak of, but here's the layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:background="#caf">

        <TextView
            android:id="@+id/one"
            android:layout_width="0dp"
            android:layout_height="48dp"
            android:gravity="center"
            android:text="hello world"
            android:background="#fff"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/two"/>

        <TextView
            android:id="@+id/two"
            android:layout_width="0dp"
            android:layout_height="48dp"
            android:gravity="center"
            android:text="hello world"
            android:background="#eee"
            app:layout_constraintTop_toBottomOf="@+id/one"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/three"/>

        <TextView
            android:id="@+id/three"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:gravity="center"
            android:text="hello world"
            android:background="#ddd"
            app:layout_constraintHeight_default="spread"
            app:layout_constraintHeight_min="300dp"
            app:layout_constraintTop_toBottomOf="@+id/two"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>

    </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

The bottom view stretches to fill the viewport when it is smaller than the remaining available space, and scrolling is impossible:

The bottom view maintains a fixed height when it is larger than the remaining available space, which makes scrolling possible:

Title: View with minHeight in ConstraintLayout

Body:
I have a ConstraintLayout inside a NestedScrollView. The ConstraintLayout contains a bunch of views but the last View can have a dynamic height to fill up the bottom space if there is any but it also needs to be a minimum height if there is not enough space.

For arguments sake, here is an example.

<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:layout_height="match_parent">

        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintHeight_min="1500dp"
            android:background="@color/red"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

    </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>

As you can see I have put the ConstraintLayout version in but it doesn't work. Obviously the values are ridiculously large but this is just for testing.

If I don't set fillViewport="true" on the NestedScrollView then ConstraintLayout has a height of 0. When I do set the fillViewport, the ConstraintLayout does not scroll but just fills the screen.

How can I set the View so that it expands to the bottom of the ConstraintLayout which should be as big as the Viewport but if my View is not of the minHeight then we allow scrolling?

I am using version 1.0.2 of the ConstraintLayout library.

What I expect to see is the being all the way to the bottom of the parent but if that size is less than 1500dp then the view scrolls.

I have entered 1500dp like so android:layout_height="1500dp" and the view scrolls accordingly.

UPDATE 1

Seems to be once I put the layout within a FragmentViewPager. The app:layout_constraintHeight_min property isn't respected and it only matches the height of the viewport.

I also tried taking the NestedScrollView out of the fragment and putting the ViewPager inside it but again didn't work.

Body:
Add this attribute to the view you'd like to have stretch:

app:layout_constraintHeight_default="spread"

I made a tiny app to demonstrate. No java logic to speak of, but here's the layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:background="#caf">

        <TextView
            android:id="@+id/one"
            android:layout_width="0dp"
            android:layout_height="48dp"
            android:gravity="center"
            android:text="hello world"
            android:background="#fff"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/two"/>

        <TextView
            android:id="@+id/two"
            android:layout_width="0dp"
            android:layout_height="48dp"
            android:gravity="center"
            android:text="hello world"
            android:background="#eee"
            app:layout_constraintTop_toBottomOf="@+id/one"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/three"/>

        <TextView
            android:id="@+id/three"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:gravity="center"
            android:text="hello world"
            android:background="#ddd"
            app:layout_constraintHeight_default="spread"
            app:layout_constraintHeight_min="300dp"
            app:layout_constraintTop_toBottomOf="@+id/two"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>

    </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>

The bottom view stretches to fill the viewport when it is smaller than the remaining available space, and scrolling is impossible:

The bottom view maintains a fixed height when it is larger than the remaining available space, which makes scrolling possible:


问:
How to use multiple && ORs in a PHP If statement?
How I adjust this in order to get the brackets to work?</p>

```<code>if (mysql_num_rows($printPricealertsdata) < 5 && ($_POST['pricetype'] == "pricebelow" && $_POST['price'] < $marketdata['priceusd']) OR ($_POST['pricetype'] == "priceabove" && $_POST['price'] > $marketdata['priceusd'])) {
   echo "success";
}else{
   echo "fail";
}
</code>```

答:
It would be easier if you told us what you want, and what you get with your code. But since you make me guess, I think you print "success" sometimes, even when the number of rows is 5 or more; and you don't want that. If that's the problem you need brackets around your OR-clause, because && binds closer. Check the manual for the precedence of different operators. </p>

<p>BTW you can use new lines and indentation to make your code more readable: </p>

```<code>if ( mysql_num_rows($printPricealertsdata) < 5
  && (
  ($_POST['pricetype'] == "pricebelow" && $_POST['price'] < $marketdata['priceusd'])
  OR
  ($_POST['pricetype'] == "priceabove" && $_POST['price'] > $marketdata['priceusd'])
  )) {
   echo "success";
 } else {
   echo "fail";
 }
</code>```

Body:
How I adjust this in order to get the brackets to work?

if (mysql_num_rows($printPricealertsdata) < 5 && ($_POST['pricetype'] == "pricebelow" && $_POST['price'] < $marketdata['priceusd']) OR ($_POST['pricetype'] == "priceabove" && $_POST['price'] > $marketdata['priceusd'])) {
   echo "success";
}else{
   echo "fail";
}

Body:
It would be easier if you told us what you want, and what you get with your code. But since you make me guess, I think you print "success" sometimes, even when the number of rows is 5 or more; and you don't want that. If that's the problem you need brackets around your OR-clause, because && binds closer. Check the manual for the precedence of different operators.

BTW you can use new lines and indentation to make your code more readable:

if ( mysql_num_rows($printPricealertsdata) < 5
  && (
  ($_POST['pricetype'] == "pricebelow" && $_POST['price'] < $marketdata['priceusd'])
  OR
  ($_POST['pricetype'] == "priceabove" && $_POST['price'] > $marketdata['priceusd'])
  )) {
   echo "success";
 } else {
   echo "fail";
 }


问:
How to get a script to read and write a file?
I'm completing exercise 16 from Learn Python the Hard Way and it's asking this question:

Write a script similar to the last exercise that uses read and argv to
  read the file you just created.

I'm attempting to use the 'read' function in order to have the script automatically run and display the text file that the script creates. But nothing shows up when I run everything, it's just an extra blank space before "close it". How do I get it to display anything?

```<code>from sys import argv

script, filename = argv

txt = open(filename)

print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file."
target.truncate()

print "Need 3 lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "Write these to a file"

target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))

print txt.read()

print "Close it."
target.close()
</code>```

答:
You should close the file after writing and then open it again for reading:

```<code>from sys import argv

script, filename = argv

print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."

raw_input("?")

print "Opening the file..."
with open(filename, 'w') as target:

    print "Truncating the file."
    target.truncate()

    print "Need 3 lines."

    line1 = raw_input("line 1: ")
    line2 = raw_input("line 2: ")
    line3 = raw_input("line 3: ")

    print "Write these to a file"

    target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))

txt = open(filename)
print txt.read()

print "Close it."
target.close()
</code>```

The second version (without "with as" structure):

```<code>from sys import argv

script, filename = argv

print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file."
target.truncate()

print "Need 3 lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "Write these to a file"

target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))
print "Close it."
target.close()

txt = open(filename)
print txt.read()
</code>```

Body:
I'm completing exercise 16 from Learn Python the Hard Way and it's asking this question:

Write a script similar to the last exercise that uses read and argv to
  read the file you just created.

I'm attempting to use the 'read' function in order to have the script automatically run and display the text file that the script creates. But nothing shows up when I run everything, it's just an extra blank space before "close it". How do I get it to display anything?

from sys import argv

script, filename = argv

txt = open(filename)

print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file."
target.truncate()

print "Need 3 lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "Write these to a file"

target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))

print txt.read()

print "Close it."
target.close()

Body:
You should close the file after writing and then open it again for reading:

from sys import argv

script, filename = argv

print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."

raw_input("?")

print "Opening the file..."
with open(filename, 'w') as target:

    print "Truncating the file."
    target.truncate()

    print "Need 3 lines."

    line1 = raw_input("line 1: ")
    line2 = raw_input("line 2: ")
    line3 = raw_input("line 3: ")

    print "Write these to a file"

    target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))

txt = open(filename)
print txt.read()

print "Close it."
target.close()

The second version (without "with as" structure):

from sys import argv

script, filename = argv

print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file."
target.truncate()

print "Need 3 lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "Write these to a file"

target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))
print "Close it."
target.close()

txt = open(filename)
print txt.read()


问:
where can I find a good wordlist
I'm looking for a file that is a wordlist and also is set up by type of word. For example something in this format

```<code>Nouns: {
    bus
    car
    deck
    elephant
    ...
}
Adjectives {
    awful
    bashful
    ...
}
Advervb {
    ...
}
</code>```

Any ideas?

答:
One problem is that the word type depends on usage and context.  For example, 'root' can be a noun or verb.

On a Unix/Linux system with aspell installed, this will give you all the words in the dictionary:

```<code>aspell dump master
</code>```

Finally, see the related question:  Need free English dictionary or Corpus, ultimately for a MySQL database

Title: where can I find a good wordlist

Body:
I'm looking for a file that is a wordlist and also is set up by type of word. For example something in this format

Nouns: {
    bus
    car
    deck
    elephant
    ...
}
Adjectives {
    awful
    bashful
    ...
}
Advervb {
    ...
}

Any ideas?

Body:
One problem is that the word type depends on usage and context.  For example, 'root' can be a noun or verb.

On a Unix/Linux system with aspell installed, this will give you all the words in the dictionary:

aspell dump master

Finally, see the related question:  Need free English dictionary or Corpus, ultimately for a MySQL database


问:
PyQt GUI size on high resolution screens
I posted a question a while ago asking about Tkinter backends and subsequently forgot about it but I've since realised that I'm using the pyqt backend. Is there a fix for that?

Original Question:

So it appears that matplotlib gui plots (a la plt.show()) don't adapt to monitor resolution and appear tiny on high resolution screens. Is there a matplotlib+Pyqt fix or do I have fiddle around somewhere in Windows settings?

Thanks

答:
Before app is loaded, and not while loading.

insert:

```<code>if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)

if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
</code>```

like so :

```<code>import PyQt5
from PyQt5 import QtCore, QtGui, uic, QtWidgets
from PyQt5.QtWidgets import QWidget

if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)

if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)

class MyWindow(PyQt5.QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
</code>```

And if that still don't work, in user en var and not system en var.

```<code>QT_AUTO_SCREEN_SCALE_FACTOR=2
</code>```

qt-5/highdpi

Body:
Before app is loaded, and not while loading.

insert:

if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)

if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)

like so :

import PyQt5
from PyQt5 import QtCore, QtGui, uic, QtWidgets
from PyQt5.QtWidgets import QWidget

if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)

if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)

class MyWindow(PyQt5.QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()

And if that still don't work, in user en var and not system en var.

QT_AUTO_SCREEN_SCALE_FACTOR=2

qt-5/highdpi


问:
Kotlin type missmatch. Expected Any received MyObject
I am making a list of observable LiveData objects, that should contain Resource object (https://developer.android.com/topic/libraries/architecture/guide.html#addendum). I don't care what type of data that Resource object is containing.

```<code>abstract class LiveResources : LiveData<Resource<Any>>() {
  private val mediatorLiveData = MediatorLiveData<Resource<Any>>()
  protected val resources = HashSet<LiveData<Resource<Any>>>()

  fun addResource(source: LiveData<Resource<Any>>) {
    resources.add(source)
    mediatorLiveData.addSource(source, resourceObserver)
  }

  fun removeResource(source: LiveData<Resource<Any>>) {
    resources.remove(source)
    mediatorLiveData.removeSource(source)
  }

  private val resourceObserver = Observer<Resource<Any>> {
    onSourceChange()
  }

  abstract fun onSourceChange()
}
</code>```

Unfortunately when I try to use LiveResources.addResource() with LiveData<Resource<List<String>>> I get TypeMismatch error in my IDE, saying that LiveData<Resource<Any>> was expected.

答:
Your Resource (and/or LiveData) class should be defined with generic covariance in order to make it work. Like so:</p>

```<code>class Resource<out T> // <- out marks generic type as covariant
</code>```

Body:
I am making a list of observable LiveData objects, that should contain Resource object (https://developer.android.com/topic/libraries/architecture/guide.html#addendum). I don't care what type of data that Resource object is containing.

abstract class LiveResources : LiveData<Resource<Any>>() {
  private val mediatorLiveData = MediatorLiveData<Resource<Any>>()
  protected val resources = HashSet<LiveData<Resource<Any>>>()

  fun addResource(source: LiveData<Resource<Any>>) {
    resources.add(source)
    mediatorLiveData.addSource(source, resourceObserver)
  }

  fun removeResource(source: LiveData<Resource<Any>>) {
    resources.remove(source)
    mediatorLiveData.removeSource(source)
  }

  private val resourceObserver = Observer<Resource<Any>> {
    onSourceChange()
  }

  abstract fun onSourceChange()
}

Unfortunately when I try to use LiveResources.addResource() with LiveData<Resource<List<String>>> I get TypeMismatch error in my IDE, saying that LiveData<Resource<Any>> was expected.

Body:
Your Resource (and/or LiveData) class should be defined with generic covariance in order to make it work. Like so:

class Resource<out T> // <- out marks generic type as covariant


问:
How do I overwrite files locally? From master to my current working directory.
So I changed my directory to the correct location and I want to pull the changes and from the master to my working directory and overwrite what I have on my computer locally. How would I go about that?

Would I use "git checkout -- " to discard changes that I have locally and in with the files I wish to pull from the master?

答:
Assuming your remote repo is called 'origin', you'll want to execute both of these commands:

```<code>git fetch origin
git reset --hard origin/master
</code>```

Be sure that you won't need any of your local changes before doing this, they will be gone for good if they don't match what's on the remote repo.

Body:
Assuming your remote repo is called 'origin', you'll want to execute both of these commands:

git fetch origin
git reset --hard origin/master

Be sure that you won't need any of your local changes before doing this, they will be gone for good if they don't match what's on the remote repo.


问:
How to determine if a point is in a 2D triangle?
Is there an easy way to determine if a point is inside a triangle? It's 2D, not 3D.</p>

答:
Since there's no JS answer,

Clockwise & Counter-Clockwise solution:

function triangleContains(ax, ay, bx, by, cx, cy, x, y) {

    let det = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)

    return  det * ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) >= 0 &&
            det * ((cx - bx) * (y - by) - (cy - by) * (x - bx)) >= 0 &&
            det * ((ax - cx) * (y - cy) - (ay - cy) * (x - cx)) >= 0

}
```
<p>EDIT: fixed two typos (about sign & comparison).</p>
<p>https://jsfiddle.net/jniac/rctb3gfL/</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function triangleContains(ax, ay, bx, by, cx, cy, x, y) {

    let det = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)

    return  det * ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) > 0 &&
            det * ((cx - bx) * (y - by) - (cy - by) * (x - bx)) > 0 &&
            det * ((ax - cx) * (y - cy) - (ay - cy) * (x - cx)) > 0

}

let width = 500, height = 500

// clockwise
let triangle1 = {

    A : { x: 10, y: -10 },
    C : { x: 20, y: 100 },
    B : { x: -90, y: 10 },

    color: '#f00',

}

// counter clockwise
let triangle2 = {

    A : { x: 20, y: -60 },
    B : { x: 90, y: 20 },
    C : { x: 20, y: 60 },

    color: '#00f',

}

let scale = 2
let mouse = { x: 0, y: 0 }

// DRAW >

let wrapper = document.querySelector('div.wrapper')

wrapper.onmousemove = ({ layerX:x, layerY:y }) => {

    x -= width / 2
    y -= height / 2
    x /= scale
    y /= scale

    mouse.x = x
    mouse.y = y

    drawInteractive()

}

function drawArrow(ctx, A, B) {

    let v = normalize(sub(B, A), 3)
    let I = center(A, B)

    let p

    p = add(I, rotate(v, 90), v)
    ctx.moveTo(p.x, p.y)
    ctx.lineTo(I.x, I .y)
    p = add(I, rotate(v, -90), v)
    ctx.lineTo(p.x, p.y)

}

function drawTriangle(ctx, { A, B, C, color }) {

    ctx.beginPath()
    ctx.moveTo(A.x, A.y)
    ctx.lineTo(B.x, B.y)
    ctx.lineTo(C.x, C.y)
    ctx.closePath()

    ctx.fillStyle = color + '6'
    ctx.strokeStyle = color
    ctx.fill()

    drawArrow(ctx, A, B)
    drawArrow(ctx, B, C)
    drawArrow(ctx, C, A)

    ctx.stroke()

}

function contains({ A, B, C }, P) {

    return triangleContains(A.x, A.y, B.x, B.y, C.x, C.y, P.x, P.y)

}

function resetCanvas(canvas) {

    canvas.width = width
    canvas.height = height

    let ctx = canvas.getContext('2d')

    ctx.resetTransform()
    ctx.clearRect(0, 0, width, height)
    ctx.setTransform(scale, 0, 0, scale, width/2, height/2)

}

function drawDots() {

    let canvas = document.querySelector('canvas#dots')
    let ctx = canvas.getContext('2d')

    resetCanvas(canvas)

    let count = 1000

    for (let i = 0; i < count; i++) {

        let x = width * (Math.random() - .5)
        let y = width * (Math.random() - .5)

        ctx.beginPath()
        ctx.ellipse(x, y, 1, 1, 0, 0, 2 * Math.PI)

        if (contains(triangle1, { x, y })) {

            ctx.fillStyle = '#f00'

        } else if (contains(triangle2, { x, y })) {

            ctx.fillStyle = '#00f'

        } else {

            ctx.fillStyle = '#0003'

        }

        ctx.fill()

    }

}

function drawInteractive() {

    let canvas = document.querySelector('canvas#interactive')
    let ctx = canvas.getContext('2d')

    resetCanvas(canvas)

    ctx.beginPath()
    ctx.moveTo(0, -height/2)
    ctx.lineTo(0, height/2)
    ctx.moveTo(-width/2, 0)
    ctx.lineTo(width/2, 0)
    ctx.strokeStyle = '#0003'
    ctx.stroke()

    drawTriangle(ctx, triangle1)
    drawTriangle(ctx, triangle2)

    ctx.beginPath()
    ctx.ellipse(mouse.x, mouse.y, 4, 4, 0, 0, 2 * Math.PI)

    if (contains(triangle1, mouse)) {

        ctx.fillStyle = triangle1.color + 'a'
        ctx.fill()

    } else if (contains(triangle2, mouse)) {

        ctx.fillStyle = triangle2.color + 'a'
        ctx.fill()

    } else {

        ctx.strokeStyle = 'black'
        ctx.stroke()

    }

}

drawDots()
drawInteractive()

// trigo

function add(...points) {

    let x = 0, y = 0

    for (let point of points) {

        x += point.x
        y += point.y

    }

    return { x, y }

}

function center(...points) {

    let x = 0, y = 0

    for (let point of points) {

        x += point.x
        y += point.y

    }

    x /= points.length
    y /= points.length

    return { x, y }

}

function sub(A, B) {

    let x = A.x - B.x
    let y = A.y - B.y

    return { x, y }

}

function normalize({ x, y }, length = 10) {

    let r = length / Math.sqrt(x * x + y * y)

    x *= r
    y *= r

    return { x, y }

}

function rotate({ x, y }, angle = 90) {

    let length = Math.sqrt(x * x + y * y)

    angle *= Math.PI / 180
    angle += Math.atan2(y, x)

    x = length * Math.cos(angle)
    y = length * Math.sin(angle)

    return { x, y }

}</code>```

* {
    margin: 0;
}

html {
    font-family: monospace;
}

body {
    padding: 32px;
}

span.red {
    color: #f00;
}

span.blue {
    color: #00f;
}

canvas {
    position: absolute;
    border: solid 1px #ddd;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><span class="red">red triangle</span> is clockwise</p>
<p><span class="blue">blue triangle</span> is couter clockwise</p>
<br>
<div class="wrapper">
    <canvas id="dots"></canvas>
    <canvas id="interactive"></canvas>
</div></code>```

I'm using here the same method as described above: a point is inside ABC if it is respectively on the "same" side of each line AB, BC, CA.

Body:
Since there's no JS answer,

Clockwise & Counter-Clockwise solution:

function triangleContains(ax, ay, bx, by, cx, cy, x, y) {

    let det = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)

    return  det * ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) >= 0 &&
            det * ((cx - bx) * (y - by) - (cy - by) * (x - bx)) >= 0 &&
            det * ((ax - cx) * (y - cy) - (ay - cy) * (x - cx)) >= 0

}

EDIT: fixed two typos (about sign & comparison).

https://jsfiddle.net/jniac/rctb3gfL/

function triangleContains(ax, ay, bx, by, cx, cy, x, y) {

    let det = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)

    return  det * ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) > 0 &&
            det * ((cx - bx) * (y - by) - (cy - by) * (x - bx)) > 0 &&
            det * ((ax - cx) * (y - cy) - (ay - cy) * (x - cx)) > 0

}

let width = 500, height = 500

// clockwise
let triangle1 = {

    A : { x: 10, y: -10 },
    C : { x: 20, y: 100 },
    B : { x: -90, y: 10 },

    color: '#f00',

}

// counter clockwise
let triangle2 = {

    A : { x: 20, y: -60 },
    B : { x: 90, y: 20 },
    C : { x: 20, y: 60 },

    color: '#00f',

}

let scale = 2
let mouse = { x: 0, y: 0 }

// DRAW >

let wrapper = document.querySelector('div.wrapper')

wrapper.onmousemove = ({ layerX:x, layerY:y }) => {

    x -= width / 2
    y -= height / 2
    x /= scale
    y /= scale

    mouse.x = x
    mouse.y = y

    drawInteractive()

}

function drawArrow(ctx, A, B) {

    let v = normalize(sub(B, A), 3)
    let I = center(A, B)

    let p

    p = add(I, rotate(v, 90), v)
    ctx.moveTo(p.x, p.y)
    ctx.lineTo(I.x, I .y)
    p = add(I, rotate(v, -90), v)
    ctx.lineTo(p.x, p.y)

}

function drawTriangle(ctx, { A, B, C, color }) {

    ctx.beginPath()
    ctx.moveTo(A.x, A.y)
    ctx.lineTo(B.x, B.y)
    ctx.lineTo(C.x, C.y)
    ctx.closePath()

    ctx.fillStyle = color + '6'
    ctx.strokeStyle = color
    ctx.fill()

    drawArrow(ctx, A, B)
    drawArrow(ctx, B, C)
    drawArrow(ctx, C, A)

    ctx.stroke()

}

function contains({ A, B, C }, P) {

    return triangleContains(A.x, A.y, B.x, B.y, C.x, C.y, P.x, P.y)

}

function resetCanvas(canvas) {

    canvas.width = width
    canvas.height = height

    let ctx = canvas.getContext('2d')

    ctx.resetTransform()
    ctx.clearRect(0, 0, width, height)
    ctx.setTransform(scale, 0, 0, scale, width/2, height/2)

}

function drawDots() {

    let canvas = document.querySelector('canvas#dots')
    let ctx = canvas.getContext('2d')

    resetCanvas(canvas)

    let count = 1000

    for (let i = 0; i < count; i++) {

        let x = width * (Math.random() - .5)
        let y = width * (Math.random() - .5)

        ctx.beginPath()
        ctx.ellipse(x, y, 1, 1, 0, 0, 2 * Math.PI)

        if (contains(triangle1, { x, y })) {

            ctx.fillStyle = '#f00'

        } else if (contains(triangle2, { x, y })) {

            ctx.fillStyle = '#00f'

        } else {

            ctx.fillStyle = '#0003'

        }

        ctx.fill()

    }

}

function drawInteractive() {

    let canvas = document.querySelector('canvas#interactive')
    let ctx = canvas.getContext('2d')

    resetCanvas(canvas)

    ctx.beginPath()
    ctx.moveTo(0, -height/2)
    ctx.lineTo(0, height/2)
    ctx.moveTo(-width/2, 0)
    ctx.lineTo(width/2, 0)
    ctx.strokeStyle = '#0003'
    ctx.stroke()

    drawTriangle(ctx, triangle1)
    drawTriangle(ctx, triangle2)

    ctx.beginPath()
    ctx.ellipse(mouse.x, mouse.y, 4, 4, 0, 0, 2 * Math.PI)

    if (contains(triangle1, mouse)) {

        ctx.fillStyle = triangle1.color + 'a'
        ctx.fill()

    } else if (contains(triangle2, mouse)) {

        ctx.fillStyle = triangle2.color + 'a'
        ctx.fill()

    } else {

        ctx.strokeStyle = 'black'
        ctx.stroke()

    }

}

drawDots()
drawInteractive()

// trigo

function add(...points) {

    let x = 0, y = 0

    for (let point of points) {

        x += point.x
        y += point.y

    }

    return { x, y }

}

function center(...points) {

    let x = 0, y = 0

    for (let point of points) {

        x += point.x
        y += point.y

    }

    x /= points.length
    y /= points.length

    return { x, y }

}

function sub(A, B) {

    let x = A.x - B.x
    let y = A.y - B.y

    return { x, y }

}

function normalize({ x, y }, length = 10) {

    let r = length / Math.sqrt(x * x + y * y)

    x *= r
    y *= r

    return { x, y }

}

function rotate({ x, y }, angle = 90) {

    let length = Math.sqrt(x * x + y * y)

    angle *= Math.PI / 180
    angle += Math.atan2(y, x)

    x = length * Math.cos(angle)
    y = length * Math.sin(angle)

    return { x, y }

}

* {
    margin: 0;
}

html {
    font-family: monospace;
}

body {
    padding: 32px;
}

span.red {
    color: #f00;
}

span.blue {
    color: #00f;
}

canvas {
    position: absolute;
    border: solid 1px #ddd;
}

<p><span class="red">red triangle</span> is clockwise</p>
<p><span class="blue">blue triangle</span> is couter clockwise</p>
<br>
<div class="wrapper">
    <canvas id="dots"></canvas>
    <canvas id="interactive"></canvas>
</div>

I'm using here the same method as described above: a point is inside ABC if it is respectively on the "same" side of each line AB, BC, CA.


问:
Which CMS can use Oracle as database?
My client has an Oracle 11g installed and want migrate the company site to a CMS that uses the oracle.</p>

答: There is this post on the forum for the Fabrik joomla extension extension that describes a patch to allow the component to connect to an Oracle database. It was contributed by a user, and I personally cannot vouch for it, however. </p>

Title: Which CMS can use Oracle as database?


问:
Why my custom report header is showing in html but not in pdf in Odoo v10?
I have created a custom report which inherits sale.report_saleorder and I am trying to add custom header.

<openerp>
    <data>
        <template id="report_saleorder_inherit" inherit_id="sale.report_saleorder">
            <xpath expr="t" position="before">

            </xpath>
        </template>
    </data>
</openerp>
```

When I select report format as 'HTML', it is working without any problem. But when I print it as 'PDF', it doesn't render my header. Is there a solution for this? How can I print report with my header?

答:
If you want to use a custom header you must inherit the report.external_layout_header, this one:

<t t-name="report.external_layout_header">

</t>
```

<p>So, you should inherit the header like this:</p>

<pre class="lang-xml prettyprint-override"><code><openerp>
    <data>
        <template id="custom_external_layout_header" inherit_id="report.external_layout_header">

        <!-- [...] -->

        </template>
    </data>
</openerp>
</code>```

Body:
I have created a custom report which inherits sale.report_saleorder and I am trying to add custom header.

<openerp>
    <data>
        <template id="report_saleorder_inherit" inherit_id="sale.report_saleorder">
            <xpath expr="t" position="before">

            </xpath>
        </template>
    </data>
</openerp>

When I select report format as 'HTML', it is working without any problem. But when I print it as 'PDF', it doesn't render my header. Is there a solution for this? How can I print report with my header?

Body:
If you want to use a custom header you must inherit the report.external_layout_header, this one:

<t t-name="report.external_layout_header">
    <div class="header">
        <div class="row">
            <div class="col-xs-3">
                <img t-if="company.logo" t-att-src="'data:image/png;base64,%s' % company.logo" style="max-height: 45px;"/>
            </div>
            <div class="col-xs-9 text-right" style="margin-top:20px;" t-field="company.rml_header1"/>
        </div>
        <div class="row zero_min_height">
            <div class="col-xs-12">
                <div style="border-bottom: 1px solid black;"/>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-5">
                <div t-field="company.partner_id" t-field-options="{&quot;widget&quot;: &quot;contact&quot;, &quot;fields&quot;: [&quot;address&quot;, &quot;name&quot;], &quot;no_marker&quot;: true}" style="border-bottom: 1px solid black;" class="pull-left"/>
            </div>
        </div>
    </div>
</t>

So, you should inherit the header like this:

<openerp>
    <data>
        <template id="custom_external_layout_header" inherit_id="report.external_layout_header">

        <!-- [...] -->

        </template>
    </data>
</openerp>


问:
React fontawesome 5 SVG not rerendering
I am using a pro license of Fontawesome 5 with React and I have created a row header component for the header cell in a div table. The cell has Fontawesome generated svgs for the sort icons. I can't get the SVGs to rerender.

Here is my code:

export const row = (value, className, clickHandler) => (
  <div className={`align-self-center text-center ${className ? className : ''}`} onClick={clickHandler}>
    {value}

);

export const rowHeader = (value, className, sort, clickHandler) => {
  let iconClass;
  switch (sort) {
    case 'asc':
      iconClass =  'fas fa-sort-up';
      break;
    case 'desc':
      iconClass = 'fas fa-sort-down';
      break;
    default:
      iconClass = 'fal fa-sort';
      break;
  }

  return row({value} {iconClass} , className +  ' clickable', clickHandler);
};
```

I tried creating the  as a separate component and that didn't work. The icons render correctly the first time appropriatelys and the iconClass is being changed in my cell. However, the SVG element is not being rerendered.

How do I force the Fontawesome generated SVG icons to rerender when the parent element rerenders?

答:
This is the solution that finally worked. I was able to find the documentation for using my pro license.

import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import { faSortDown, faSortUp } from '@fortawesome/fontawesome-pro-solid';
import { faSort } from '@fortawesome/fontawesome-pro-light';

export const row = (value, className, clickHandler) => (
  <div className={`align-self-center text-center ${className ? className : ''}`} onClick={clickHandler}>
    {value}

);

export const rowHeader = (value, className, sort, clickHandler) => {
  return row({value} {sortIcon(sort)}, className +  ' clickable', clickHandler);
};

export const sortIcon = (sort) => {
  switch (sort) {
    case 'asc':
      return <FontAwesomeIcon icon={faSortDown} size='lg' className='float-right'/>;
    case 'desc':
      return <FontAwesomeIcon icon={faSortUp} size='lg' className='float-right'/>;
    default:
      return <FontAwesomeIcon icon={faSort} size='lg' className='float-right'/>;
  }
};
```

Edit - Clarification:

The problem appeared to be that changing the CSS class names on the rendered SVG elements would not cause React to re-render them. Switching to the React Fontawesome library and updating the FontAwesomeIcon component worked.

Title: React fontawesome 5 SVG not rerendering

Body:
I am using a pro license of Fontawesome 5 with React and I have created a row header component for the header cell in a div table. The cell has Fontawesome generated svgs for the sort icons. I can't get the SVGs to rerender.

Here is my code:

export const row = (value, className, clickHandler) => (
  <div className={`align-self-center text-center ${className ? className : ''}`} onClick={clickHandler}>
    {value}

);

export const rowHeader = (value, className, sort, clickHandler) => {
  let iconClass;
  switch (sort) {
    case 'asc':
      iconClass =  'fas fa-sort-up';
      break;
    case 'desc':
      iconClass = 'fas fa-sort-down';
      break;
    default:
      iconClass = 'fal fa-sort';
      break;
  }

  return row({value} {iconClass} , className +  ' clickable', clickHandler);
};

I tried creating the  as a separate component and that didn't work. The icons render correctly the first time appropriatelys and the iconClass is being changed in my cell. However, the SVG element is not being rerendered.

How do I force the Fontawesome generated SVG icons to rerender when the parent element rerenders?

Body:
This is the solution that finally worked. I was able to find the documentation for using my pro license.

import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import { faSortDown, faSortUp } from '@fortawesome/fontawesome-pro-solid';
import { faSort } from '@fortawesome/fontawesome-pro-light';

export const row = (value, className, clickHandler) => (
  <div className={`align-self-center text-center ${className ? className : ''}`} onClick={clickHandler}>
    {value}
  </div>
);

export const rowHeader = (value, className, sort, clickHandler) => {
  return row(<span>{value} {sortIcon(sort)}</span>, className +  ' clickable', clickHandler);
};

export const sortIcon = (sort) => {
  switch (sort) {
    case 'asc':
      return <FontAwesomeIcon icon={faSortDown} size='lg' className='float-right'/>;
    case 'desc':
      return <FontAwesomeIcon icon={faSortUp} size='lg' className='float-right'/>;
    default:
      return <FontAwesomeIcon icon={faSort} size='lg' className='float-right'/>;
  }
};

Edit - Clarification:

The problem appeared to be that changing the CSS class names on the rendered SVG elements would not cause React to re-render them. Switching to the React Fontawesome library and updating the FontAwesomeIcon component worked.


问:
How to modify a string inside a struct in C?
I am trying to modify a field inside a struct. I have no trouble doing this with other types (i.e. int, float etc.) but char * is giving me problems. I think I have to do something like:

```<code>typedef struct{
    char *string_field;
} struct_name;

struct_name *struct_name1;
struct_name1 = (struct_name *) malloc(sizeof(struct_name));
strcpy(struct_name1->string_field, new_string);

printf("New string: %s\n", struct_name1->string_field);
</code>```

But this gives me a segmentation fault. What reason do you think I would get this problem for? Initially, I thought maybe the char *string_field was not big enough to copy to, but I changed the size of it manually to be of size 100 (more than enough) and I still get this problem.

答:
You reserve memory for your struct, which comprises a pointer to a string, but not the space for a string's content. Reserve memory for the string content and let your struct's pointer point to it; then you can copy newstring's content into that memory:

```<code>struct_name1->string_field = malloc(strlen(new_string)+1);
strcpy(struct_name1->string_field, new_string);
</code>```

Body:
I am trying to modify a field inside a struct. I have no trouble doing this with other types (i.e. int, float etc.) but char * is giving me problems. I think I have to do something like:

typedef struct{
    char *string_field;
} struct_name;

struct_name *struct_name1;
struct_name1 = (struct_name *) malloc(sizeof(struct_name));
strcpy(struct_name1->string_field, new_string);

printf("New string: %s\n", struct_name1->string_field);

But this gives me a segmentation fault. What reason do you think I would get this problem for? Initially, I thought maybe the char *string_field was not big enough to copy to, but I changed the size of it manually to be of size 100 (more than enough) and I still get this problem.

Body:
You reserve memory for your struct, which comprises a pointer to a string, but not the space for a string's content. Reserve memory for the string content and let your struct's pointer point to it; then you can copy newstring's content into that memory:

struct_name1->string_field = malloc(strlen(new_string)+1);
strcpy(struct_name1->string_field, new_string);


问:
Best way to compare std::strings
What is the best way to compare std::strings? The obvious way would be with if/else:

```<code>std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.
</code>```

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?

答: The answer to this question is all too dependent upon the problem.  You've named two examples.  You could add to your options things like hash tables, regular expressions, etc...</p>

Title: Best way to compare std::strings

Body:
What is the best way to compare std::strings? The obvious way would be with if/else:

std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?