问:
How Recursion works in C
I am new to C and I'm reading about recursion, but I am totally confused.

The main part where I'm getting confused is how things get unwind when the exit condition is reached. I would like to know how during recursion values got pushed and popped from stack.

Also can anyone please give me a diagramatic  view of recursion?

Thanks...

答:
Lets assume a function:

```<code>int MyFunc(int counter) {
    // check this functions counter value from the stack (most recent push)

    // if counter is 0, we've reached the terminating condition, return it
    if(counter == 0) {
        return counter;
    }
    else {
        // terminating condition not reached, push (counter-1) onto stack and recurse
        int valueToPrint = MyFunc(counter - 1);

        // print out the value returned by the recursive call
        printf("%d", valueToPrint);

        // return the value that was supplied to use
        // (usually done via a register I think)
        return counter;
    }
}

int main() {
    // Push 9 onto the stack, we don't care about the return value...
    MyFunc(9);
}
</code>```

The output is: 012345678

The first time through MyFunc, count is 9.  It fails the terminating check (it is not 0), so the recursive call is invoked, with (counter -1), 8.

This repeats, decrementing the value pushed onto the stack each time until counter == 0.  At this point, the terminating clause fires and the function simply returns the value of counter (0), usually in a register.

The next call up the stack, uses the returned value to print (0), then returns the value that was supplied into it when it was called (1).  This repeats:

The next call up the stack, uses the returned value to print (1), then returns the value that was supplied into it when it was called (2).  etc, till you get to the top of the stack.

So, if MyFunc was invoked with 3, you'd get the equivalent of (ignoring return addresses etc from the stack):

```<code>Call MyFunc(3) Stack: [3]
Call MyFunc(2) Stack: [2,3]
Call MyFunc(1) Stack: [1,2,3]
Call MyFunc(0) Stack: [0,1,2,3]
Termination fires (top of stack == 0), return top of stack(0).
// Flow returns to:
MyFunc(1) Stack: [1,2,3]
Print returned value (0)
return current top of stack (1)

// Flow returns to:
MyFunc(2) Stack: [2,3]
Print returned value (1)
return current top of stack (2)

// Flow returns to:
MyFunc(3) Stack: [3]
Print returned value (2)
return current top of stack (3)

// and you're done...
</code>```

Title: How Recursion works in C

Body:
Lets assume a function:

int MyFunc(int counter) {
    // check this functions counter value from the stack (most recent push)

    // if counter is 0, we've reached the terminating condition, return it
    if(counter == 0) {
        return counter;
    }
    else {
        // terminating condition not reached, push (counter-1) onto stack and recurse
        int valueToPrint = MyFunc(counter - 1);

        // print out the value returned by the recursive call
        printf("%d", valueToPrint);

        // return the value that was supplied to use
        // (usually done via a register I think)
        return counter;
    }
}

int main() {
    // Push 9 onto the stack, we don't care about the return value...
    MyFunc(9);
}

The output is: 012345678

The first time through MyFunc, count is 9.  It fails the terminating check (it is not 0), so the recursive call is invoked, with (counter -1), 8.

This repeats, decrementing the value pushed onto the stack each time until counter == 0.  At this point, the terminating clause fires and the function simply returns the value of counter (0), usually in a register.

The next call up the stack, uses the returned value to print (0), then returns the value that was supplied into it when it was called (1).  This repeats:

The next call up the stack, uses the returned value to print (1), then returns the value that was supplied into it when it was called (2).  etc, till you get to the top of the stack.

So, if MyFunc was invoked with 3, you'd get the equivalent of (ignoring return addresses etc from the stack):

Call MyFunc(3) Stack: [3]
Call MyFunc(2) Stack: [2,3]
Call MyFunc(1) Stack: [1,2,3]
Call MyFunc(0) Stack: [0,1,2,3]
Termination fires (top of stack == 0), return top of stack(0).
// Flow returns to:
MyFunc(1) Stack: [1,2,3]
Print returned value (0)
return current top of stack (1)

// Flow returns to:
MyFunc(2) Stack: [2,3]
Print returned value (1)
return current top of stack (2)

// Flow returns to:
MyFunc(3) Stack: [3]
Print returned value (2)
return current top of stack (3)

// and you're done...


来源: stackexchange

问:
Node Creation Takes too long and failed
I installed Blockchain platform v2 beta then I tried to configure it and add nodes.
My Question is:
is there anyone faced long delay in node creation like CA node for example.
I faced this problem and cannot find from where I can check logs.

Notification Error Image:

Note:
the node did not be created till now since 2 days.

答:
Here the link to the official IBP documentation where is explained how to retrieve and visualize logs.

IBM Blockchain Platform - Viewing your node logs

I also suggest you to check if there is any issue in your kubernetes cluster where the IBP is running.

ContentLicense: CC BY-SA 4.0

Title: Node Creation Takes too long and failed


问:
Laravel Vue SPA login
I just created Vue + Laravel SPA login but I'm not sure if it's safe enough. I'm new in VUE :)

I'm using JWT Auth. When user enter credentials and submit form, Auth on Laravel side returns user model with token. This user is stored in local storage. In my Vue router I created middleware which run beforeEach view change. This is working good but there is not actual token in database related to this user. When I manually change token in storage I'm still passing middleware because token is not checked anymore. It just check if exists in local storage... Should I store token in DB and check it on every view change? Or...??

答:
It doesn't sound like its safe, no :)

I've never used Laravel, so I can't talk about it specifically, but I can explain how the process is suppose to work.

In your server, you should have a middlewere or somekind of logic that reads the token and verifies it integrity. The token itself is just a Base64 string with three components

Header

Payload (the actual data)

Signature

If you have the token, its easy to read the payload, because its just Base64 string. So its not enough just to read that, you need to make sure that the signature is correct.

When you create a JWT token you do so with a secret, when there's a request to your server. The server should verify the signature to make sure that this is a valid token. If you don't have the secret you can't verify the signature. Only you should have the secret.

This stops "me as an attacker" to send a token with some fake payload. By verifying the signature you are making sure that this is the token you created, not some fake token I'm sending to your website.

You should also not store that token in a local storage. Local storage should never contain information like token or password, because is just a dictionary/map that's accessable for everybody. So I can make a website that reads the local storage, get the token you created, and since this is your token with a correect signature I can now make requests to your website.

I would reccomend storing a JWT token in a httpOnly cookie on https (safe: true option in most environments). The browser can't read httpOnly cookies, only the server.

When making requests from the VueJS app to the server, like saving a blog post the server should

Never trust the payload in the JWT blindly.

Never trust user information from the VueJS app.

Always verify the user on the server side (by verifying the signature of the token in your example)

For example

```<code>methods: {
  saveBlogPost() {
    axios.post('/api/save', {
      title: 'My blog title'
      userId: 'bergur'
    })
  }
}
</code>```

Your server should never, never read that userId sent from the VueJS app. The JWT middlewere should check the JWT, verify its integrity and then use the information from the payload.

Edit: I answered a similar post about securing VueJS apps. You can find it here: VueJS Secure with Auth0 - How is it secure?

Basically: Its fine to store information in the client that help to make the user interface make sense, but when doing the actual work like saving into the database or fetching some private data the server should always verify the user.

Title: Laravel Vue SPA login

Body:
It doesn't sound like its safe, no :)

I've never used Laravel, so I can't talk about it specifically, but I can explain how the process is suppose to work.

In your server, you should have a middlewere or somekind of logic that reads the token and verifies it integrity. The token itself is just a Base64 string with three components

Header

Payload (the actual data)

Signature

If you have the token, its easy to read the payload, because its just Base64 string. So its not enough just to read that, you need to make sure that the signature is correct.

When you create a JWT token you do so with a secret, when there's a request to your server. The server should verify the signature to make sure that this is a valid token. If you don't have the secret you can't verify the signature. Only you should have the secret.

This stops "me as an attacker" to send a token with some fake payload. By verifying the signature you are making sure that this is the token you created, not some fake token I'm sending to your website.

You should also not store that token in a local storage. Local storage should never contain information like token or password, because is just a dictionary/map that's accessable for everybody. So I can make a website that reads the local storage, get the token you created, and since this is your token with a correect signature I can now make requests to your website.

I would reccomend storing a JWT token in a httpOnly cookie on https (safe: true option in most environments). The browser can't read httpOnly cookies, only the server.

When making requests from the VueJS app to the server, like saving a blog post the server should

Never trust the payload in the JWT blindly.

Never trust user information from the VueJS app.

Always verify the user on the server side (by verifying the signature of the token in your example)

For example

methods: {
  saveBlogPost() {
    axios.post('/api/save', {
      title: 'My blog title'
      userId: 'bergur'
    })
  }
}

Your server should never, never read that userId sent from the VueJS app. The JWT middlewere should check the JWT, verify its integrity and then use the information from the payload.

Edit: I answered a similar post about securing VueJS apps. You can find it here: VueJS Secure with Auth0 - How is it secure?

Basically: Its fine to store information in the client that help to make the user interface make sense, but when doing the actual work like saving into the database or fetching some private data the server should always verify the user.


问:
kotlin ...ArrayOf scoping issues
Why does the first sample of code below compile but the second fails. The only change is that I've moved the val involved from file scope to class scope.

  longArrayOf(...) creates a LongArray, right?

Compiles with no problem:

```<code>val CORRECT_BUZZ_PATTERN = longArrayOf(100, 100, 100, 100, 100, 100)
class TestLongArrayOf {
    enum class BuzzType(val pattern: LongArray) {
        CORRECT(CORRECT_BUZZ_PATTERN)
    }
}
</code>```

Fails with message "unresolved reference CORRECT_BUZZ_PATTERN"

```<code>class TestLongArrayOf {
    val CORRECT_BUZZ_PATTERN = longArrayOf(100, 100, 100, 100, 100, 100)
    enum class BuzzType(val pattern: LongArray) {
        CORRECT(CORRECT_BUZZ_PATTERN)
    }
}
</code>```

答:
The main difference is that in the first case CORRECT_BUZZ_PATTERN is defined outside of the class and is treated as read-only variable (accessible through its getter), while in the second snippet it's a read-only instance variable, so it cannot be used as a constant.
However, this code would work:

```<code>class TestLongArrayOf {
    val CORRECT_BUZZ_PATTERN = longArrayOf(100, 100, 100, 100, 100, 100)
    enum class BuzzType(val pattern: LongArray) {
        CORRECT(TestLongArrayOf().CORRECT_BUZZ_PATTERN)
    }
}
</code>```

Let's look at the generated bytecode. In the first case you have:

```<code>public final class MainKt {
    private final static long[] CORRECT_BUZZ_PATTERN
    public final static long[] getCORRECT_BUZZ_PATTERN() {
        ...
    }
    static {
        // initialize CORRECT_BUZZ_PATTERN here
        ...
    }
}

public final enum TestLongArrayOf$BuzzType {
    ...
}
</code>```

So CORRECT_BUZZ_PATTERN is a static final array belonging to class MainKt that can be accessed through its getter.

In the second case what you get is:

```<code>public final class TestLongArrayOf {
    private final long[] CORRECT_BUZZ_PATTERN

    public final long[] getCORRECT_BUZZ_PATTERN() {
        ...
    }
}

public final enum TestLongArrayOf$BuzzType {
    ...
}
</code>```

Note that in this case CORRECT_BUZZ_PATTERN is an instance variable that can be retrieved via its getter. However, since it's an instance variable you must call the getter on an instance of TestLongArrayOf, that's why the snippet at the top of my answer is working.

Title: kotlin ...ArrayOf scoping issues

Body:
Why does the first sample of code below compile but the second fails. The only change is that I've moved the val involved from file scope to class scope.

  longArrayOf(...) creates a LongArray, right?

Compiles with no problem:

val CORRECT_BUZZ_PATTERN = longArrayOf(100, 100, 100, 100, 100, 100)
class TestLongArrayOf {
    enum class BuzzType(val pattern: LongArray) {
        CORRECT(CORRECT_BUZZ_PATTERN)
    }
}

Fails with message "unresolved reference CORRECT_BUZZ_PATTERN"

class TestLongArrayOf {
    val CORRECT_BUZZ_PATTERN = longArrayOf(100, 100, 100, 100, 100, 100)
    enum class BuzzType(val pattern: LongArray) {
        CORRECT(CORRECT_BUZZ_PATTERN)
    }
}

Body:
The main difference is that in the first case CORRECT_BUZZ_PATTERN is defined outside of the class and is treated as read-only variable (accessible through its getter), while in the second snippet it's a read-only instance variable, so it cannot be used as a constant.
However, this code would work:

class TestLongArrayOf {
    val CORRECT_BUZZ_PATTERN = longArrayOf(100, 100, 100, 100, 100, 100)
    enum class BuzzType(val pattern: LongArray) {
        CORRECT(TestLongArrayOf().CORRECT_BUZZ_PATTERN)
    }
}

Let's look at the generated bytecode. In the first case you have:

public final class MainKt {
    private final static long[] CORRECT_BUZZ_PATTERN
    public final static long[] getCORRECT_BUZZ_PATTERN() {
        ...
    }
    static {
        // initialize CORRECT_BUZZ_PATTERN here
        ...
    }
}

public final enum TestLongArrayOf$BuzzType {
    ...
}

So CORRECT_BUZZ_PATTERN is a static final array belonging to class MainKt that can be accessed through its getter.

In the second case what you get is:

public final class TestLongArrayOf {
    private final long[] CORRECT_BUZZ_PATTERN

    public final long[] getCORRECT_BUZZ_PATTERN() {
        ...
    }
}

public final enum TestLongArrayOf$BuzzType {
    ...
}

Note that in this case CORRECT_BUZZ_PATTERN is an instance variable that can be retrieved via its getter. However, since it's an instance variable you must call the getter on an instance of TestLongArrayOf, that's why the snippet at the top of my answer is working.


问:
How do I fix this: Use of undefined constant slug - assumed 'slug'
I took my HTML website and turned it into a PHP site. I'm in the testing phase currently however, I keep getting "Notices" on the rendered page instead of content.

I've tried turning the constants to variables with $, but the notice still appears. However, it changed from undefined constant to undefined variable. I changed them back to constants.

I'm on a WinXP 32-bit, therefore, I use Xammp 1.8.2 with PHP 5.4.31

the array in question:

```<code>    $navItems = array(
                      array(
                              slug => "index.php",
                              title => "Home"
                            ),
                      array(
                              slug => "about.php",
                              title => "About Me"
                            ),
                      array(
                              slug => "portfolio.php",
                              title => "Portfolio"
                            ),
                      array(
                              slug => "contact.php",
                              title => "Contact"
                            )
        );
</code>```

I am expecting to see the actual page content. However, I get:

Notice: Use of undefined constant slug - assumed 'slug' in C:\xampp\htdocs\zmglobal-it.com.php\includes\arrays.php on line 5

Notice: Use of undefined constant title - assumed 'title' in C:\xampp\htdocs\zmglobal-it.com.php\includes\arrays.php on line 6

答:
Key values must be quoted so use "keyname" or 'keyname'</p>

```<code>''' { $navItems = array( array( "slug" => "index.php", "title" => "Home", ), array( "slug" => "about.php", "title" => "About Me", ), array( "slug" => "portfolio.php", "title" => "Portfolio", ), array( "slug" => "contact.php", "title" => "Contact", ) ); } '''
</code>```

Body:
I took my HTML website and turned it into a PHP site. I'm in the testing phase currently however, I keep getting "Notices" on the rendered page instead of content.

I've tried turning the constants to variables with $, but the notice still appears. However, it changed from undefined constant to undefined variable. I changed them back to constants.

I'm on a WinXP 32-bit, therefore, I use Xammp 1.8.2 with PHP 5.4.31

the array in question:

    $navItems = array(
                      array(
                              slug => "index.php",
                              title => "Home"
                            ),
                      array(
                              slug => "about.php",
                              title => "About Me"
                            ),
                      array(
                              slug => "portfolio.php",
                              title => "Portfolio"
                            ),
                      array(
                              slug => "contact.php",
                              title => "Contact"
                            )
        );

I am expecting to see the actual page content. However, I get:

Notice: Use of undefined constant slug - assumed 'slug' in C:\xampp\htdocs\zmglobal-it.com.php\includes\arrays.php on line 5

Notice: Use of undefined constant title - assumed 'title' in C:\xampp\htdocs\zmglobal-it.com.php\includes\arrays.php on line 6

Body:
Key values must be quoted so use "keyname" or 'keyname'

''' { $navItems = array( array( "slug" => "index.php", "title" => "Home", ), array( "slug" => "about.php", "title" => "About Me", ), array( "slug" => "portfolio.php", "title" => "Portfolio", ), array( "slug" => "contact.php", "title" => "Contact", ) ); } '''


问:
Why can't I center a SizeTransition horizontally in a Column in Flutter?
Please check the following code. Regardless what I tried, the SizeTransition is not centered horizontally in the Column. I tried to wrap Column in a Container and then provide infinite width. I tried to wrap SizeTransition in a Center. I tried to wrap SizeTransition in a Container which has center alignment property. I tried to wrap it in a Stack. I tried to give the container child with alignment center property etc... But none of them works...

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: AnimatedBox(),
    );
  }
}

class AnimatedBox extends StatefulWidget {
  @override
  createState() => _AnimatedBoxState();
}

class _AnimatedBoxState extends State<AnimatedBox> with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 400),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          child: Text('animate forward'),
          onPressed: () {_controller.forward();},
        ),
        RaisedButton(
          child: Text('animate reverse'),
          onPressed: () {_controller.reverse();},
        ),
        const SizedBox(height: 100.0,),
        SizeTransition(
          child: Container(
            width: 200.0,
            height: 200.0,
            color: Colors.blue,
          ),
          sizeFactor: CurvedAnimation(
            curve: Curves.fastOutSlowIn,
            parent: _controller,
          ),
        ),
      ],
    );
  }
}
```

<p>For instance, the following code does not work for <code>SizeTransition</code>, but works for <code>ScaleTransition</code>. I have no idea what's wrong with <code>SizeTransition</code>.</p>

<pre class="lang-dart prettyprint-override"><code>return Container(
      width: double.infinity,
      child: Column(
</code>```

答:
Despite the fact that my previous answer solves the problem to some extent, I also wanted to address how limited SizeTransition widget is and how to solve this.

SizeTransition provides the effect of "unfolding" its content, running the animation either in horizontal or in vertical axis by rewriting alignment settings.

To achieve the same effect without breaking alignment rules, but also avoid using ScaleTransition widget as we need the "unfold/reveal" animation and not "scale up" - here is what I propose:

@override
Widget build(BuildContext context) {
  final _animation = CurvedAnimation(parent: _controller, curve: Curves.fastOutSlowIn);
  return Column(
    children: <Widget>[
      // ...,
      AnimatedBuilder(
        animation: _animation,
        builder: (_, child) => ClipRect(
          child: Align(
            alignment: Alignment.center,
            heightFactor: _animation.value,
            widthFactor: null,
            child: child,
          ),
        ),
        child: Container(
          width: 200.0,
          height: 200.0,
          color: Colors.blue,
          child: Text("test"),
        ),
      )
    ]
  );
}
```

<p>This is basically an <code>AnimatedBuilder</code> widget with the same <code>ClipRect</code> & <code>Align</code> used as in <code>SizeTransition</code>, except that it does limit alignment to one axis only.</p>

<hr>

<p>If you'd like the animation to run in both horizontal & vertical axes - assign the same <code>_animation.value</code> to <code>widthFactor</code> property:</p>

<pre class="lang-dart prettyprint-override"><code>Align(
  alignment: Alignment.center,
  heightFactor: _animation.value,
  widthFactor: _animation.value,
  child: child,
),
</code>```

This will help you achieve "reveal from center" effect without scaling up & down the content of your widget.

Body:
Please check the following code. Regardless what I tried, the SizeTransition is not centered horizontally in the Column. I tried to wrap Column in a Container and then provide infinite width. I tried to wrap SizeTransition in a Center. I tried to wrap SizeTransition in a Container which has center alignment property. I tried to wrap it in a Stack. I tried to give the container child with alignment center property etc... But none of them works...

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: AnimatedBox(),
    );
  }
}

class AnimatedBox extends StatefulWidget {
  @override
  createState() => _AnimatedBoxState();
}

class _AnimatedBoxState extends State<AnimatedBox> with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 400),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          child: Text('animate forward'),
          onPressed: () {_controller.forward();},
        ),
        RaisedButton(
          child: Text('animate reverse'),
          onPressed: () {_controller.reverse();},
        ),
        const SizedBox(height: 100.0,),
        SizeTransition(
          child: Container(
            width: 200.0,
            height: 200.0,
            color: Colors.blue,
          ),
          sizeFactor: CurvedAnimation(
            curve: Curves.fastOutSlowIn,
            parent: _controller,
          ),
        ),
      ],
    );
  }
}

For instance, the following code does not work for SizeTransition, but works for ScaleTransition. I have no idea what's wrong with SizeTransition.

return Container(
      width: double.infinity,
      child: Column(

Body:
Despite the fact that my previous answer solves the problem to some extent, I also wanted to address how limited SizeTransition widget is and how to solve this.

SizeTransition provides the effect of "unfolding" its content, running the animation either in horizontal or in vertical axis by rewriting alignment settings.

To achieve the same effect without breaking alignment rules, but also avoid using ScaleTransition widget as we need the "unfold/reveal" animation and not "scale up" - here is what I propose:

@override
Widget build(BuildContext context) {
  final _animation = CurvedAnimation(parent: _controller, curve: Curves.fastOutSlowIn);
  return Column(
    children: <Widget>[
      // ...,
      AnimatedBuilder(
        animation: _animation,
        builder: (_, child) => ClipRect(
          child: Align(
            alignment: Alignment.center,
            heightFactor: _animation.value,
            widthFactor: null,
            child: child,
          ),
        ),
        child: Container(
          width: 200.0,
          height: 200.0,
          color: Colors.blue,
          child: Text("test"),
        ),
      )
    ]
  );
}

This is basically an AnimatedBuilder widget with the same ClipRect & Align used as in SizeTransition, except that it does limit alignment to one axis only.

If you'd like the animation to run in both horizontal & vertical axes - assign the same _animation.value to widthFactor property:

Align(
  alignment: Alignment.center,
  heightFactor: _animation.value,
  widthFactor: _animation.value,
  child: child,
),

This will help you achieve "reveal from center" effect without scaling up & down the content of your widget.


问:
How to list procedures with CBAC privileges
I am looking at a set of build scripts for a Oracle 12c database that has stored procedures with Code Based Access Control.
I want to write a pre-deploy and post-deploy report to check the deployment has worked.

I would like to report on which procedures have CBAC privs. There must be  database dictionary view that has this but I cannot find it.

答:
This is new in 12c onwards.

See DBA_CODE_ROLE_PRIVS (or ALL_ or USER_ if you dont have DBA level access).


问:
Lookup formula that matches data in row and column
I need a formula to automatically lookup values andthe data is set like this:
First sheet

```<code>id1   id2   id3
data  data  data
empty empty empty
</code>```

Second sheet

```<code>id1  data1
id2  data1
id3  data1
</code>```

This is sheet is where i have id's as headers and i need to enter a formula which adds the data1 value in the empty cell from the second sheet to the first, if the id values match.

I have tried index & match so far, but either i am doing it wrong or it is the wrong way to do it.

答: I figured out what was wrong. The data in the look up vector weren't sorted in ascending order. After, i the simple LOOKUP formula worked perfectly. Regardless, thanks everyone for the tips and ideas.</p>

Body:
I need a formula to automatically lookup values andthe data is set like this:
First sheet

id1   id2   id3
data  data  data
empty empty empty

Second sheet

id1  data1
id2  data1
id3  data1

This is sheet is where i have id's as headers and i need to enter a formula which adds the data1 value in the empty cell from the second sheet to the first, if the id values match.

I have tried index & match so far, but either i am doing it wrong or it is the wrong way to do it.


问:
Adding a Business Layer to ADO .NET Entity Framework
I'm working on my first .NET project (.NET 3.5, ADO.NET and C#).  We've built our entity models and are trying to build a clean business objects layer.

We've got our basic entity model and we want to add certain business-level semantics to the default data accessors (navigation properties, etc).

For example, let's assume that we have a many-to-many relationship between Person and BankAccounts.  Let's assume that at the business layer we would like to add the ability to freeze an account.  We now want the ability to navigate from a Person to:

all their bank accounts,

their non-frozen bank accounts, and

their frozen bank accounts.

Naturally we'd like to make the nominal case the default:  If I navigate Person.BankAccounts() I'd like it to return their non-frozen accounts.  I could add the navigation properties Person.FrozenBankAccounts() and Person.AllBankAccounts().

Both approaches we've come up with seem to have a fair amount of code smell.

We can't find a way to override the entity model's methods.  So, leave Person.BankAccounts() as the accessor that returns all bank accounts.  Then we add a Person.FrozenBankAccounts() and a Person.NonFrozenBankAccounts().

Add another explicit layer to the code base that wraps all accesses to BankAccounts.

With approach 1, the problem is that the nominal business case (accessing unfrozen bank accounts) is the most unintuitive method name of the lot.

With approach 2, when we subclass the objects from the entity model layer we have to override every method to ensure that it won't return objects from the underlying layer.  So we create a BL_Person which has a BankAccounts() method that returns a collection of BL_BankAccount objects.  But in this case, all that code seems a little silly.

Is there a better approach than the two we've considered?  If there isn't a better approach, which of the two I've outlined seem like the better solution (given that we've got something like 50+ classes we need to work with)?

Note: While doing a web search, I did find an open letter to Microsoft titled ADO .NET Entity Framework Vote of No Confidence that seems to imply that there isn't a good way to add in a clear separation of concerns.

答:
You could add two new entity types that inherit from Account

- RegularAccount and FrozenAccount

and add your IsFrozen field as a inheritance condition (table per hierarchy).

Then you could delete the association from "Person" to "Account" and create two new associations:

Person to RegularAccount, name navigation property on person "Accounts".

Person to FrozenAccount, name navigation property on person "FrozenAccounts".

OwnerDisplayName: Bradley Mazurek

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: cletus

ContentLicense: CC BY-SA 3.0


问:
Change Button Color dynamically with the Integer Value
I want to change the Button color with the Integer Value. So if my Integer Value is 1 it should be green once it goes up it should change dynamically to yellow and at the end should change to red. How can i implement this.

I tried with interpolation but i can't get the value i need its changing the color but not very precise.

答:
Please let me know whether this is helpful.

```<code>yourButtonName.setBackgroundColor(colorIntVariable);
</code>```

"colorIntVariable" is a self chosen variable name for an integer created with the rgb method:
https://developer.android.com/reference/android/graphics/Color.html#rgb(int,%20int,%20int)

```<code>int colorIntVariable = rgb(0,255,0);
</code>```

Above code can be used for displaying a green object.

An example can be:

```<code>    public class MainActivity extends AppCompatActivity {

    Button yourButtonName;
    Button plusButton;
    Button minusButton;
    int red;
    int green;
    int input = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        yourButtonName = findViewById(R.id.button);

        plusButton = findViewById(R.id.plusbutton);
        minusButton = findViewById(R.id.minusbutton);

        plusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                input = input + 10;
                changeButtonColor(input);
            }
        });

        minusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                input = input - 10;
                changeButtonColor(input);
            }
        });

    }

    public void changeButtonColor(int inputValue) {

        if(inputValue <= 256) {
            green = 255;
            red = inputValue -1;
        }
        else {
            green = 255 - (inputValue - 256);
            red = 255;
        }

        int colorIntVariable = rgb(red,green,0);

        yourButtonName.setBackgroundColor(colorIntVariable);

    }
}
</code>```

Body:
Please let me know whether this is helpful.

yourButtonName.setBackgroundColor(colorIntVariable);

"colorIntVariable" is a self chosen variable name for an integer created with the rgb method:
https://developer.android.com/reference/android/graphics/Color.html#rgb(int,%20int,%20int)

int colorIntVariable = rgb(0,255,0);

Above code can be used for displaying a green object.

An example can be:

    public class MainActivity extends AppCompatActivity {

    Button yourButtonName;
    Button plusButton;
    Button minusButton;
    int red;
    int green;
    int input = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        yourButtonName = findViewById(R.id.button);

        plusButton = findViewById(R.id.plusbutton);
        minusButton = findViewById(R.id.minusbutton);

        plusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                input = input + 10;
                changeButtonColor(input);
            }
        });

        minusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                input = input - 10;
                changeButtonColor(input);
            }
        });

    }

    public void changeButtonColor(int inputValue) {

        if(inputValue <= 256) {
            green = 255;
            red = inputValue -1;
        }
        else {
            green = 255 - (inputValue - 256);
            red = 255;
        }

        int colorIntVariable = rgb(red,green,0);

        yourButtonName.setBackgroundColor(colorIntVariable);

    }
}


问:
Why am I getting a validation error even though I'm providing data?
For some reason, the backend of my app doesn't think I'm providing data, even though I am, while testing my routes.

I've looked around, but I haven't found anything that quite matches up to the problem I'm having.

I've been trying to build the backend for my app by following this tutorial series: https://www.youtube.com/playlist?list=PL55RiY5tL51q4D-B63KBnygU6opNPFk_q

Before I added validation to my models, I received 200s and 201s for my HTTP requests. Once I added validation, I began receiving error messages informing me that I'm not providing the necessary information, even though I am.

I'm using Mongoose 5.5.8, Cors 2.8.5, Body-Parser 1.19.0, and Postman 7.1.1.

I've tried using the .exec() method once, but that only gave me a worse error.

Here is my model:

```<code>const studentSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  first_name: { type: String, required: true },
  last_name: { type: String, required: true },
  preferred_name: { type: String, required: true }
});

module.exports = mongoose.model("Student", studentSchema);
</code>```

Here is my controller:

```<code>  add_student: (req, res) => {
    const student = new Student({
      _id: new mongoose.Types.ObjectId(),
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      preferred_name: req.body.preferred_name
    });
    student
      .save()
      .then(result => {
        console.log(result);
        res.status(201).json({
          message: "Student added!",
          createdStudent: {
            first_name: result.first_name,
            last_name: result.last_name,
            preferred_name: result.preferred_name
          }
        });
      })
      .catch(err => {
        console.log(err);
        res.status(422).json({
          error: err
        });
      });
  },
</code>```

Here is my route:

```<code>router.route("/")
  .post(studentController.add_student)
</code>```

And here is the data I'm trying to pass through Postman:

```<code>{
"first_name": "Steve",
"last_name": "Jones",
"preferred_name": "Stevie Boy"
}
</code>```

As you can see, I am passing data, but I keep getting errors as if there's no information there at all.

I guess I need to know how to properly provide pass data through my controller, so my app doesn't think I'm trying to pass an empty object.

答:
The problem I was having was a user (me) error. In Postman,

Where it says JSON (application/json), I had it said to text. Setting it to JSON fixed my problem.

And have no doubts, I feel plenty foolish about this!

Body:
For some reason, the backend of my app doesn't think I'm providing data, even though I am, while testing my routes.

I've looked around, but I haven't found anything that quite matches up to the problem I'm having.

I've been trying to build the backend for my app by following this tutorial series: https://www.youtube.com/playlist?list=PL55RiY5tL51q4D-B63KBnygU6opNPFk_q

Before I added validation to my models, I received 200s and 201s for my HTTP requests. Once I added validation, I began receiving error messages informing me that I'm not providing the necessary information, even though I am.

I'm using Mongoose 5.5.8, Cors 2.8.5, Body-Parser 1.19.0, and Postman 7.1.1.

I've tried using the .exec() method once, but that only gave me a worse error.

Here is my model:

const studentSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  first_name: { type: String, required: true },
  last_name: { type: String, required: true },
  preferred_name: { type: String, required: true }
});

module.exports = mongoose.model("Student", studentSchema);

Here is my controller:

  add_student: (req, res) => {
    const student = new Student({
      _id: new mongoose.Types.ObjectId(),
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      preferred_name: req.body.preferred_name
    });
    student
      .save()
      .then(result => {
        console.log(result);
        res.status(201).json({
          message: "Student added!",
          createdStudent: {
            first_name: result.first_name,
            last_name: result.last_name,
            preferred_name: result.preferred_name
          }
        });
      })
      .catch(err => {
        console.log(err);
        res.status(422).json({
          error: err
        });
      });
  },

Here is my route:

router.route("/")
  .post(studentController.add_student)

And here is the data I'm trying to pass through Postman:

{
"first_name": "Steve",
"last_name": "Jones",
"preferred_name": "Stevie Boy"
}

As you can see, I am passing data, but I keep getting errors as if there's no information there at all.

I guess I need to know how to properly provide pass data through my controller, so my app doesn't think I'm trying to pass an empty object.


问:
How do I return a map from a function in XSLT 3.0?
Let's say I have a function f:get-map() that returns a map.

How do I use the result of that function in another function?

Right now I'm doing it like this:

```<code><xsl:function name="f:get-another-map" as="map(*)">
  <xsl:variable name="result" select="f:get-map()"/>
  <xsl:map>
      <xsl:map-entry key="'key1'" select="map:get($result, 'key1')"/>
      <xsl:map-entry key="'key2'" select="map:get($result ,'key2')"/>
  </xsl:map>
</xsl:function>
</code>```

But that is rather cumbersome.
Is there a better way to do this?

答: In general to return any function call result from a function you use xsl:sequence with the select expression calling the function e.g. <xsl:sequence select="f:get-map()"/> returns the result of calling f:get-map().

Body:
Let's say I have a function f:get-map() that returns a map.

How do I use the result of that function in another function?

Right now I'm doing it like this:

<xsl:function name="f:get-another-map" as="map(*)">
  <xsl:variable name="result" select="f:get-map()"/>
  <xsl:map>
      <xsl:map-entry key="'key1'" select="map:get($result, 'key1')"/>
      <xsl:map-entry key="'key2'" select="map:get($result ,'key2')"/>
  </xsl:map>
</xsl:function>

But that is rather cumbersome.
Is there a better way to do this?


问:
Unity scrollrect viewport is not resizeable
I have a scrollrect object on a UI canvas that has a viewport object child, and the viewport object has a content object child that stores all of the items to be scrolled.

I have selected the viewport for reference. I want to resize the viewport rect relative to LevelScroller (see hierarchy) in order for there to be a margin around the scrollview, so that the scrolling items do not touch the edge of the  gray LevelScroller rect. But the viewport rect is not resizeable. Right now the result is this:

See how the button at the top (1S-Levitation) is cut off by the grey panel. I want there to be a margin between the point where it is cut off and the gray box.

I have tried adding a horizontal layout group to LevelScroller to forcibly add a margin, but this did not work. Why is the viewport not resizeable?

Any help is appreciated

答:
I believe that the viewport is not resizable because it is supposed to manage how your scroll will behave during the user interaction. As an example, you have only one cell in your content container and the user drag it down, once it is released it is supposed to move back to the top of your viewport, and if you put a margin in there it will not be capable of move entirely back to the top.

But hopefully you can do the following trick to have your margin:

Create an empty game object called Scroller and set it as the father of your LevelScroller. Then, set your LevelScroller RectTransform to stretch in both directions, and set the desired margin on the RectTransform Top, Bottom, Right and Left fields. You should have something like this:

LevelScroller as a child with 10 pixels of top and bottom margin

Then create another empty object child of your parent Scroller, and put it behind the LevelScroller. Lets call it BgImage. Now, set the RectTransform of BgImage to stretch in both directions and add an image to it. Ta daaa, you should have now your background with your margins on your viewport.

BgImage working as the background of the LevelScroller


问:
Reduce sum of digits recursively down to one digit number
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion?  I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:

```<code>class sum_of_digits
{

    static int sum_of_digit(int n)
    {
        if (n == 0)
            return 0;
        return (n % 10 + sum_of_digit(n / 10));
    }

    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num);
        System.out.println("Sum of digits in " +
                           num + " is " + result);
    }
}
</code>```

This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.

答:
You could add a clause at the end to check whether the sum is smaller than 10, if it isn't then recursively call it again with the newly calculated sum, ie.</p>

```<code>static int sum_of_digit(int n)
{
    if (n == 0)
        return 0;
    int temp = (n % 10 + sum_of_digit(n / 10));
    if (temp < 10)
        return temp;
    return sum_of_digit(temp);
}
</code>```

Body:
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion?  I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:

class sum_of_digits
{

    static int sum_of_digit(int n)
    {
        if (n == 0)
            return 0;
        return (n % 10 + sum_of_digit(n / 10));
    }

    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num);
        System.out.println("Sum of digits in " +
                           num + " is " + result);
    }
}

This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.

Body:
You could add a clause at the end to check whether the sum is smaller than 10, if it isn't then recursively call it again with the newly calculated sum, ie.

static int sum_of_digit(int n)
{
    if (n == 0)
        return 0;
    int temp = (n % 10 + sum_of_digit(n / 10));
    if (temp < 10)
        return temp;
    return sum_of_digit(temp);
}


问:
Executing unix shell commands using PHP
A text box will be used to capture the command. I've been told that I have to use the exec() function to execute UNIX shell commands.

Something like this, user types ls in the text box. The exec() function will execute the UNIX command and the command will be displayed on the web page.

What I want to know how will I get the output of the shell command and display in the web browser using PHP.

I don't know where to start since I'm very new to PHP.

I'm using Ubuntu.

答:
Use $output = system($command);

See http://php.net/system and don't forget to read the warnings about security. If you let a user pass any data to system() (or exec() etc.) it's almost as if they had a shell on your server. The same applies if you don't sanitize arguments passed to programs executed through these functions properly.

Title: Executing unix shell commands using PHP


问:
How to prevent the clipboard carriage return from becoming a line feed
I'm writing a cryptographic algorithm for educational purpose, and I need to be able to copy/paste unicode characters.

The problem is that the clipboard (not only the api) modifies the Carriage Return character (hex: 0x0d, dec: 13) into a Line Feed character (hex: 0x0a, dec: 10).

How can I prevent this behaviour ?

let $ = s => document.querySelector(s);

let cr = String.fromCharCode(0x0d);

$("#one").addEventListener("click", function (e)
{
 navigator.clipboard.writeText(cr);
});

$("#two").addEventListener("change", function (e)
{
 $("#out").textContent = "0x" + this.value.charCodeAt(0).toString(16).padStart(2, 0);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="one">copy cr to clipboard</button><br>
<textarea type="text" id="two"></textarea><br>
<div id="out"></div></code>```

you can test it by clicking the button to save the carriage return into your clipboard, then pasting it into the textarea.
Then click outside the textarea to trigger the change event.
It will display the 0x0a because the clipboard has turned the cr into lf.

PS: I had to go from guided mode to traditional because it was buggy, really annoying

答:
It is not related to Clipboard:

const $ = s => document.querySelector(s);
const cr = String.fromCharCode(0x0d);
const firstCharAsHex = v => "0x" + v.charCodeAt(0).toString(16).padStart(2, 0);

$("#one").addEventListener("click", async function (e) {
  navigator.clipboard.writeText(cr);

  const v = await navigator.clipboard.readText();
  console.log("Written: " + firstCharAsHex(v));
});

$("#two").addEventListener("paste", function (e) {
  const v = e.clipboardData.getData('text/plain');
  console.log("Being paste: " + firstCharAsHex(v));
});

$("#two").addEventListener("change", function (e) {
  const v = this.value
  console.log("After paste: " + firstCharAsHex(v));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="one">Run</button><br>
<textarea type="text" id="two"></textarea><br></code>```

Textarea  normalizes CR to LF. See specs:

For historical reasons, the element's value is normalized in three different ways for three different purposes.

The raw value is the value as it was originally set. It is not normalized.

The API value is the value used in the value IDL attribute, textLength IDL attribute, and by the maxlength and minlength content attributes. It is normalized so that line breaks use U+000A LINE FEED (LF) characters.

Finally, there is the value, as used in form submission and other processing models in this specification. It is normalized so that line breaks use U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs, and in addition, if necessary given the element's wrap attribute, additional line breaks are inserted to wrap the text at the given width.

Body:
I'm writing a cryptographic algorithm for educational purpose, and I need to be able to copy/paste unicode characters.

The problem is that the clipboard (not only the api) modifies the Carriage Return character (hex: 0x0d, dec: 13) into a Line Feed character (hex: 0x0a, dec: 10).

How can I prevent this behaviour ?

let $ = s => document.querySelector(s);

let cr = String.fromCharCode(0x0d);

$("#one").addEventListener("click", function (e)
{
 navigator.clipboard.writeText(cr);
});

$("#two").addEventListener("change", function (e)
{
 $("#out").textContent = "0x" + this.value.charCodeAt(0).toString(16).padStart(2, 0);
});

<button id="one">copy cr to clipboard</button>

<textarea type="text" id="two"></textarea>

you can test it by clicking the button to save the carriage return into your clipboard, then pasting it into the textarea.
Then click outside the textarea to trigger the change event.
It will display the 0x0a because the clipboard has turned the cr into lf.

PS: I had to go from guided mode to traditional because it was buggy, really annoying

Body:
It is not related to Clipboard:

const $ = s => document.querySelector(s);
const cr = String.fromCharCode(0x0d);
const firstCharAsHex = v => "0x" + v.charCodeAt(0).toString(16).padStart(2, 0);

$("#one").addEventListener("click", async function (e) {
  navigator.clipboard.writeText(cr);

  const v = await navigator.clipboard.readText();
  console.log("Written: " + firstCharAsHex(v));
});

$("#two").addEventListener("paste", function (e) {
  const v = e.clipboardData.getData('text/plain');
  console.log("Being paste: " + firstCharAsHex(v));
});

$("#two").addEventListener("change", function (e) {
  const v = this.value
  console.log("After paste: " + firstCharAsHex(v));
});

<button id="one">Run</button><br>
<textarea type="text" id="two"></textarea><br>

Textarea  normalizes CR to LF. See specs:

For historical reasons, the element's value is normalized in three different ways for three different purposes.

The raw value is the value as it was originally set. It is not normalized.

The API value is the value used in the value IDL attribute, textLength IDL attribute, and by the maxlength and minlength content attributes. It is normalized so that line breaks use U+000A LINE FEED (LF) characters.

Finally, there is the value, as used in form submission and other processing models in this specification. It is normalized so that line breaks use U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs, and in addition, if necessary given the element's wrap attribute, additional line breaks are inserted to wrap the text at the given width.


问:
How do I get my server to return the right Sec-WebSocket-Accept header value?
I seem to be getting the wrong hash value given the key through my webSocket. From what I can tell, the client side of the socket works, because when I have it connect to other servers, it's successful.

index.js

```<code>const http = require('http')
const cryp=require('crypto')
const port = 8080
var ourHTML=require('fs').readFile("index.html",(err,data) => {
        if(err) throw err;
        ourHTML = data.toString();
    });

const requestHandler = (request, response) => {
    //console.log(request)
    response.end(ourHTML)
}

const server = http.createServer(requestHandler)

server.on('upgrade',(req,socket)=>{
    if(req.headers['upgrade'] !== 'websocket'){
        socket.end('HTTP/1.1 400 Bad Request');
        return;
    }
    const hash=getAVal(req.headers['sec-websocket-key']);
    console.log(hash);
    socket.write([
        "HTTP/1.1 101 Web Socket Protocol Handshake",
        "Upgrade: WebSocket",
        "Connection: Upgrade",
        `Sec-WebSocket-Accept: ${hash}`
    ].join('\r\n')+'\r\n\r\n');
    //socket.end();
});

function getAVal(key){
    console.log(key);
    return cryp
    .createHash('sha1')
    .update(key+'258EAFA5-E914–47DA-95CA-C5AB0DC85B11', 'binary')
    .digest('base64');
}

server.listen(port, (err) => {
    if(err){
        return console.log("Uhh ohh,  "+err.stack,err)
    }
    console.log("server listening at "+port)
})
</code>```

index.html

```<code><html>
<head><title>Local Server</title></head>
<body><h1>Local Server Body</h1><p id="p">To Change</p></body>

<script>
console.log("here");
var ws=new WebSocket("ws://10.0.0.150:8080");
//var ws=new WebSocket("wss://echo.websocket.org");
setInterval(req,1000);

function req(){
    ws.send("tickReq");
}

ws.addEventListener('open', () => {
    ws.send("Hello");
});

ws.addEventListener('message', event => {
    document.getElementById("p").innerHTML=event.data;
});

</script>

</html>
</code>```

An example for a key and hash pair when running is:

PxsrStN1CGLK/JBYydUFjg==

QAK+TE6u+sV705GI+LpP4yKM04Y=

The top is the key given by the browser, and the bottom is what the getAVal function is returning, and it being incorrect causing this message.

Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value

答:
In your example, the base64 string

```<code>"QAK+TE6u+sV705GI+LpP4yKM04Y="
</code>```

decodes to bytes

```<code>4002BE4C4EAEFAC57BD39188F8BA4FE3228CD386
</code>```

However, the correct SHA1 hash for the string

```<code>"PxsrStN1CGLK/JBYydUFjg==258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
</code>```

is bytes

```<code>2FEA5BE3299C27C3DD290853435C7529BBBC0F0F
</code>```

and the base64 encoded form of those bytes is

```<code>"L+pb4ymcJ8PdKQhTQ1x1Kbu8Dw8="
</code>```

Which means your SHA1 hash is wrong to begin with.

Try calling digest() without an encoding specified so you can get a Buffer instead of a string, and then verify it matches the bytes above.

Then convert those bytes to base64 using Buffer.toString("base64") and verify it matches the string above.

Body:
I seem to be getting the wrong hash value given the key through my webSocket. From what I can tell, the client side of the socket works, because when I have it connect to other servers, it's successful.

index.js

const http = require('http')
const cryp=require('crypto')
const port = 8080
var ourHTML=require('fs').readFile("index.html",(err,data) => {
        if(err) throw err;
        ourHTML = data.toString();
    });

const requestHandler = (request, response) => {
    //console.log(request)
    response.end(ourHTML)
}

const server = http.createServer(requestHandler)

server.on('upgrade',(req,socket)=>{
    if(req.headers['upgrade'] !== 'websocket'){
        socket.end('HTTP/1.1 400 Bad Request');
        return;
    }
    const hash=getAVal(req.headers['sec-websocket-key']);
    console.log(hash);
    socket.write([
        "HTTP/1.1 101 Web Socket Protocol Handshake",
        "Upgrade: WebSocket",
        "Connection: Upgrade",
        `Sec-WebSocket-Accept: ${hash}`
    ].join('\r\n')+'\r\n\r\n');
    //socket.end();
});

function getAVal(key){
    console.log(key);
    return cryp
    .createHash('sha1')
    .update(key+'258EAFA5-E914–47DA-95CA-C5AB0DC85B11', 'binary')
    .digest('base64');
}

server.listen(port, (err) => {
    if(err){
        return console.log("Uhh ohh,  "+err.stack,err)
    }
    console.log("server listening at "+port)
})

index.html

<title>Local Server</title>

Local Server Body

To Change

An example for a key and hash pair when running is:

PxsrStN1CGLK/JBYydUFjg==

QAK+TE6u+sV705GI+LpP4yKM04Y=

The top is the key given by the browser, and the bottom is what the getAVal function is returning, and it being incorrect causing this message.

Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value

Body:
In your example, the base64 string

"QAK+TE6u+sV705GI+LpP4yKM04Y="

decodes to bytes

4002BE4C4EAEFAC57BD39188F8BA4FE3228CD386

However, the correct SHA1 hash for the string

"PxsrStN1CGLK/JBYydUFjg==258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

is bytes

2FEA5BE3299C27C3DD290853435C7529BBBC0F0F

and the base64 encoded form of those bytes is

"L+pb4ymcJ8PdKQhTQ1x1Kbu8Dw8="

Which means your SHA1 hash is wrong to begin with.

Try calling digest() without an encoding specified so you can get a Buffer instead of a string, and then verify it matches the bytes above.

Then convert those bytes to base64 using Buffer.toString("base64") and verify it matches the string above.


Title: How to concatenate a series of smaller size to the bottom of a pandas dataframe

Body:
I'm trying to concatenate a Series onto the right side of a dataframe with the column name 'RSI'.  However, because the Series is of shorter length than the other columns in the dataframe, I need to ensure that NaN values are appended to the top of the column and not the bottom.  Right now, I've used the following code but I can't find an argument that would allow me to have the desired output.

RSI = pd.Series(RSI)
df = pd.concat((df, RSI.rename('RSI'), axis='columns')

So far, this is my output:

      Dates  Prices   Volumes      RSI
0    2013-02-08  201.68   2893254  47.7357
1    2013-02-11  200.16   2944651  53.3967
2    2013-02-12  200.04   2461779  56.3866
3    2013-02-13  200.09   2169757  60.1845
4    2013-02-14  199.65   3294126  62.1784
5    2013-02-15  200.98   3627887  63.9720
6    2013-02-19  200.32   2998317  62.9671
7    2013-02-20  199.31   3715311  63.9232
8    2013-02-21  198.33   3923051  66.8817
9    2013-02-22  201.09   3107876  72.8258
10   2013-02-25  197.51   3845276  69.6578
11   2013-02-26  199.14   3391562  63.8458
12   2013-02-27  202.33   4185545  64.2776
13   2013-02-28  200.83   4689698  67.2445
14   2013-03-01  202.91   3308544  58.2408
15   2013-03-04  205.19   3693365  57.7058
16   2013-03-05  206.53   3807706  53.7482
17   2013-03-06  208.38   3594899  57.5396
18   2013-03-07  209.42   3884317  53.2722
19   2013-03-08  210.38   3700086  58.6824
20   2013-03-11  210.08   3048901  56.0161
21   2013-03-12  210.55   3591261  60.2066
22   2013-03-13  212.06   3355969  55.3322
23   2013-03-14  215.80   5505484  51.7492
24   2013-03-15  214.92   7935024  47.1241
25   2013-03-18  213.21   3006125  46.9102
26   2013-03-19  213.44   3198577  46.6569
27   2013-03-20  215.06   3019153  54.0822
28   2013-03-21  212.26   5830566  56.2525
29   2013-03-22  212.08   3015847  51.8359
...         ...     ...       ...      ...
1229 2017-12-26  152.83   2479017  80.1930
1230 2017-12-27  153.13   2149257  80.7444
1231 2017-12-28  154.04   2687624  56.4425
1232 2017-12-29  153.42   3327087  56.9183
1233 2018-01-02  154.25   4202503  63.6958
1234 2018-01-03  158.49   9441567  61.1962
1235 2018-01-04  161.70   7556249  61.3816
1236 2018-01-05  162.49   5195764  64.7724
1237 2018-01-08  163.47   5237523  63.0508
1238 2018-01-09  163.83   4341810  53.9559
1239 2018-01-10  164.18   4174105  54.1351
1240 2018-01-11  164.20   3794453  50.6824
1241 2018-01-12  163.14   5031886  43.0222
1242 2018-01-16  163.85   7794195  32.7428
1243 2018-01-17  168.65  11710033  39.4754
1244 2018-01-18  169.12  14259345  37.3409
1245 2018-01-19  162.37  21172488      NaN
1246 2018-01-22  162.60   8480795      NaN
1247 2018-01-23  166.25   7466232      NaN
1248 2018-01-24  165.37   5645003      NaN
1249 2018-01-25  165.47   3302520      NaN
1250 2018-01-26  167.34   3787913      NaN
1251 2018-01-29  166.80   3516995      NaN
1252 2018-01-30  163.62   4902341      NaN
1253 2018-01-31  163.70   4072830      NaN
1254 2018-02-01  162.40   4434242      NaN
1255 2018-02-02  159.03   5251938      NaN
1256 2018-02-05  152.53   8746599      NaN
1257 2018-02-06  155.34   9867678      NaN
1258 2018-02-07  153.85   6149207      NaN

However, I need it to look like this:

          Dates  Prices   Volumes      RSI
0    2013-02-08  201.68   2893254  NaN
1    2013-02-11  200.16   2944651  NaN
2    2013-02-12  200.04   2461779  NaN
3    2013-02-13  200.09   2169757  NaN
4    2013-02-14  199.65   3294126  NaN
5    2013-02-15  200.98   3627887  NaN
6    2013-02-19  200.32   2998317  NaN
7    2013-02-20  199.31   3715311  NaN
8    2013-02-21  198.33   3923051  NaN
9    2013-02-22  201.09   3107876  NaN
10   2013-02-25  197.51   3845276  NaN
11   2013-02-26  199.14   3391562  NaN
12   2013-02-27  202.33   4185545  NaN
13   2013-02-28  200.83   4689698  NaN
14   2013-03-01  202.91   3308544  NaN
15   2013-03-04  205.19   3693365  57.7058
16   2013-03-05  206.53   3807706  53.7482
17   2013-03-06  208.38   3594899  57.5396
18   2013-03-07  209.42   3884317  53.2722
19   2013-03-08  210.38   3700086  58.6824
20   2013-03-11  210.08   3048901  56.0161
21   2013-03-12  210.55   3591261  60.2066
22   2013-03-13  212.06   3355969  55.3322
23   2013-03-14  215.80   5505484  51.7492
24   2013-03-15  214.92   7935024  47.1241
25   2013-03-18  213.21   3006125  46.9102
26   2013-03-19  213.44   3198577  46.6569
27   2013-03-20  215.06   3019153  54.0822
28   2013-03-21  212.26   5830566  56.2525
29   2013-03-22  212.08   3015847  51.8359
...         ...     ...       ...      ...
1229 2017-12-26  152.83   2479017  80.1930
1230 2017-12-27  153.13   2149257  80.7444
1231 2017-12-28  154.04   2687624  56.4425
1232 2017-12-29  153.42   3327087  56.9183
1233 2018-01-02  154.25   4202503  63.6958
1234 2018-01-03  158.49   9441567  61.1962
1235 2018-01-04  161.70   7556249  61.3816
1236 2018-01-05  162.49   5195764  64.7724
1237 2018-01-08  163.47   5237523  63.0508
1238 2018-01-09  163.83   4341810  53.9559
1239 2018-01-10  164.18   4174105  54.1351
1240 2018-01-11  164.20   3794453  50.6824
1241 2018-01-12  163.14   5031886  43.0222
1242 2018-01-16  163.85   7794195  32.7428
1243 2018-01-17  168.65  11710033  39.4754
1244 2018-01-18  169.12  14259345  36.9999
1245 2018-01-19  162.37  21172488  41.1297
1246 2018-01-22  162.60   8480795  12.1231
1247 2018-01-23  166.25   7466232  39.0977
1248 2018-01-24  165.37   5645003  63.6958
1249 2018-01-25  165.47   3302520  56.4425
1250 2018-01-26  167.34   3787913  80.7444
1251 2018-01-29  166.80   3516995  61.1962
1252 2018-01-30  163.62   4902341  58.6824
1253 2018-01-31  163.70   4072830  53.7482
1254 2018-02-01  162.40   4434242  43.0222
1255 2018-02-02  159.03   5251938  61.1962
1256 2018-02-05  152.53   8746599  56.4425
1257 2018-02-06  155.34   9867678  36.0978
1258 2018-02-07  153.85   6149207  41.1311

Thanks for the help.

Body:
Another way is manipulating rsi series index to match df index from bottom up(I use only 13 rows of your sample for demo)

size_diff = df.index.size - rsi.index.size
rsi.index = df.index[size_diff:]
pd.concat([df, rsi], axis=1)

Out[1490]:
         Dates  Prices  Volumes      RSI
0   2013-02-08  201.68  2893254      NaN
1   2013-02-11  200.16  2944651      NaN
2   2013-02-12  200.04  2461779      NaN
3   2013-02-13  200.09  2169757      NaN
4   2013-02-14  199.65  3294126      NaN
5   2013-02-15  200.98  3627887  47.7357
6   2013-02-19  200.32  2998317  53.3967
7   2013-02-20  199.31  3715311  56.3866
8   2013-02-21  198.33  3923051  60.1845
9   2013-02-22  201.09  3107876  62.1784
10  2013-02-25  197.51  3845276  63.9720
11  2013-02-26  199.14  3391562  62.9671
12  2013-02-27  202.33  4185545  63.9232
13  2013-02-28  200.83  4689698  66.8817


问:
Replacing non zero values in a matrix with the marginals
I am trying to do some math with my matrix, i can write it down but i am not sure how to code it. This involves getting a column of row marginal values, then making a new matrix that has all non-zero row values replaced with the marginals, after that I would like to divide the sum of non zero new values to be the column marginals.

I can get to the row marginals but I cant seem to think of a way to repopulate.

example of what i want

```<code>import numpy as np

matrix = np.matrix([[1,3,0],[0,1,2],[1,0,4]])

matrix([[1, 3, 0],
        [0, 1, 2],
        [1, 0, 4]])

marginals = ((matrix != 0).sum(1) / matrix.sum(1))

matrix([[0.5       ],
        [0.66666667],
        [0.4       ]])
</code>```

What I want done next is a filling of the matrix based on the non zero locations of the first.

```<code>
matrix([[0.5, 0.5, 0],
        [0, 0.667, 0.667],
        [0.4, 0, 0.4]])

</code>```

Final wanted result is the new matrix column sum divided by the number of non zero occurrences in that column.

```<code>
matrix([[(0.5+0.4)/2, (0.5+0.667)/2, (0.667+0.4)/2]])

</code>```

答:
To get the final matrix we can use matrix-multiplication for efficiency -

```<code>In [84]: mask = matrix!=0

In [100]: (mask.T*marginals).T/mask.sum(0)
Out[100]: matrix([[0.45      , 0.58333334, 0.53333334]])
</code>```

Or simpler -

```<code>In [110]: (marginals.T*mask)/mask.sum(0)
Out[110]: matrix([[0.45      , 0.58333334, 0.53333334]])
</code>```

If you need that intermediate filled output too, use np.multiply for broadcasted elementwise multiplication  -

```<code>In [88]: np.multiply(mask,marginals)
Out[88]:
matrix([[0.5       , 0.5       , 0.        ],
        [0.        , 0.66666667, 0.66666667],
        [0.4       , 0.        , 0.4       ]])
</code>```

Body:
I am trying to do some math with my matrix, i can write it down but i am not sure how to code it. This involves getting a column of row marginal values, then making a new matrix that has all non-zero row values replaced with the marginals, after that I would like to divide the sum of non zero new values to be the column marginals.

I can get to the row marginals but I cant seem to think of a way to repopulate.

example of what i want

import numpy as np

matrix = np.matrix([[1,3,0],[0,1,2],[1,0,4]])

matrix([[1, 3, 0],
        [0, 1, 2],
        [1, 0, 4]])

marginals = ((matrix != 0).sum(1) / matrix.sum(1))

matrix([[0.5       ],
        [0.66666667],
        [0.4       ]])

What I want done next is a filling of the matrix based on the non zero locations of the first.

matrix([[0.5, 0.5, 0],
        [0, 0.667, 0.667],
        [0.4, 0, 0.4]])

Final wanted result is the new matrix column sum divided by the number of non zero occurrences in that column.

matrix([[(0.5+0.4)/2, (0.5+0.667)/2, (0.667+0.4)/2]])

Body:
To get the final matrix we can use matrix-multiplication for efficiency -

In [84]: mask = matrix!=0

In [100]: (mask.T*marginals).T/mask.sum(0)
Out[100]: matrix([[0.45      , 0.58333334, 0.53333334]])

Or simpler -

In [110]: (marginals.T*mask)/mask.sum(0)
Out[110]: matrix([[0.45      , 0.58333334, 0.53333334]])

If you need that intermediate filled output too, use np.multiply for broadcasted elementwise multiplication  -

In [88]: np.multiply(mask,marginals)
Out[88]:
matrix([[0.5       , 0.5       , 0.        ],
        [0.        , 0.66666667, 0.66666667],
        [0.4       , 0.        , 0.4       ]])


问:
HTML, open link click anywhere on page
I  have code for clickable background that I want to use but when I click on background its always open. How to make this code to work one per day BUT at most easiest way possible... with cookie or something else. I really need help with this. Thanks!</p>

```<code><body onclick="location.href='test.html';">
</code>```

答:
You can use localStorage.

```<code><script>
    function onBodyClick() {
        var lastOpened = localStorage.getItem('body-opened'); // You can use another identifier instead of 'body-opened'
        if (lastOpened && new Date(lastOpened).toDateString() === new Date().toDateString()) {
            return true;
        } else {
            localStorage.setItem('body-opened', new Date().toDateString());
            document.location.href = 'test.htm';
        }
    }
</script>
<body onclick="onBodyClick()"></body>
</code>```

Title: HTML, open link click anywhere on page

Body:
You can use localStorage.

<script>
    function onBodyClick() {
        var lastOpened = localStorage.getItem('body-opened'); // You can use another identifier instead of 'body-opened'
        if (lastOpened && new Date(lastOpened).toDateString() === new Date().toDateString()) {
            return true;
        } else {
            localStorage.setItem('body-opened', new Date().toDateString());
            document.location.href = 'test.htm';
        }
    }
</script>
<body onclick="onBodyClick()"></body>


问:
Spring MVC: Open link in new browser window in handler method
I have a controller that handle clicking on links. In handler method i have to do something (on db) and open clicked url in new window (something like _blank attribute in links). I use "redirect:url", but it redirect of course in the same window. Any ideas ?

```<code>@RequestMapping(value = "/open.html")
public String open(@RequestParam(value="id") Integer id) {
    Link link = linkDAO.get(id);
    linkDAO.click(id);
    return "redirect:"+link.getAddress();
}
</code>```

答:
I solved this using JavaScript and AJAX - as @Patrick suggest. Maybe it will be helpful for someone.

```<code><a href="#" onclick="openLink(${link.id},'${link.address}');">Open</a>
</code>```

openLink function:

```<code>function openLink(id, url) {
    jQuery.get('open.html?id='+id, function(data) {
      if(data == 'OK') {
        window.open(url);
      }
    }, 'text');
}
</code>```

Handler method:

```<code>@ResponseBody
@RequestMapping(value = "/open.html")
public String open(@RequestParam(value="id") Integer id) {
    Link link = linkDAO.get(id);
    linkDAO.click(id);
    return "OK";
}
</code>```

Body:
I have a controller that handle clicking on links. In handler method i have to do something (on db) and open clicked url in new window (something like _blank attribute in links). I use "redirect:url", but it redirect of course in the same window. Any ideas ?

@RequestMapping(value = "/open.html")
public String open(@RequestParam(value="id") Integer id) {
    Link link = linkDAO.get(id);
    linkDAO.click(id);
    return "redirect:"+link.getAddress();
}

Body:
I solved this using JavaScript and AJAX - as @Patrick suggest. Maybe it will be helpful for someone.

<a href="#" onclick="openLink(${link.id},'${link.address}');">Open</a>

openLink function:

function openLink(id, url) {
    jQuery.get('open.html?id='+id, function(data) {
      if(data == 'OK') {
        window.open(url);
      }
    }, 'text');
}

Handler method:

@ResponseBody
@RequestMapping(value = "/open.html")
public String open(@RequestParam(value="id") Integer id) {
    Link link = linkDAO.get(id);
    linkDAO.click(id);
    return "OK";
}


问:
How to unwrap a div and then add a div to the next item in a list on a click
I asked a question earlier (Remove a class and then add a class to the next item in a rundown when clicking a button) and while that one works, I asked the wrong type of question. Inside of removing and adding a class, I'm trying to wrap and unwrap a div inside another div and wrap a div inside the next item on a click.

What I'm trying to do is remove the div wrapping of .current around item 1 and wrap a div called .current on the next item in the rundown (item 2).

My code:

(function() {
  $("#next-item").on("click", function() {
    var curr = $('.nav-right').children('.current'); //find .current
    if (curr.next().length > 0) { // If you want to stop at last element
      curr.next().wrapInner('current'); //wrap a div around next item
      curr.contents().unwrap(); //unwrap div from previous item
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.current {
  border: 1px solid
}</code>```

<button id="next-item">next item</button>

item 1

item 2

item 3

item 4

item 5

```

JS Fiddle: https://jsfiddle.net/openbayou/wzt6bp0d/

答:
Your initial selector for finding the current item was incorrect (if it were a find() instead of children() it would have ended up matching the .current div itself, rather than the parent element you wanted; with children() it matches nothing, because .current is not a direct child of .nav-right.)

Your wrapInner was also incorrect; you need to pass the full DOM element, not just a class name.

$("#next-item").on("click", function() {
  var curr = $('.nav-right .current').parent(); //find .current's parent
  if (curr.next().length > 0) {
    curr.children('.current').contents().unwrap(); // remove .current
    curr.next().wrapInner('

'); // add it to the next element
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.current {
  border: 1px solid
}</code>```

<button id="next-item">next item</button>

item 1

item 2

item 3

item 4

item 5

```

Body:
I asked a question earlier (Remove a class and then add a class to the next item in a rundown when clicking a button) and while that one works, I asked the wrong type of question. Inside of removing and adding a class, I'm trying to wrap and unwrap a div inside another div and wrap a div inside the next item on a click.

What I'm trying to do is remove the div wrapping of .current around item 1 and wrap a div called .current on the next item in the rundown (item 2).

My code:

(function() {
  $("#next-item").on("click", function() {
    var curr = $('.nav-right').children('.current'); //find .current
    if (curr.next().length > 0) { // If you want to stop at last element
      curr.next().wrapInner('current'); //wrap a div around next item
      curr.contents().unwrap(); //unwrap div from previous item
    }
  });
});

.current {
  border: 1px solid
}

<button id="next-item">next item</button>

item 1

item 2

item 3

item 4

item 5

JS Fiddle: https://jsfiddle.net/openbayou/wzt6bp0d/

Body:
Your initial selector for finding the current item was incorrect (if it were a find() instead of children() it would have ended up matching the .current div itself, rather than the parent element you wanted; with children() it matches nothing, because .current is not a direct child of .nav-right.)

Your wrapInner was also incorrect; you need to pass the full DOM element, not just a class name.

$("#next-item").on("click", function() {
  var curr = $('.nav-right .current').parent(); //find .current's parent
  if (curr.next().length > 0) {
    curr.children('.current').contents().unwrap(); // remove .current
    curr.next().wrapInner('<div class="current"></div>'); // add it to the next element
  }
});

.current {
  border: 1px solid
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="next-item">next item</button>
<!--button to advance-->
<div class="nav-right">
  <!--list of items to rundown-->
  <div class="irl-today-item">
    <div class="current">item 1</div>
  </div>
  <!--first item-->
  <div class="irl-today-item">item 2</div>
  <div class="irl-today-item">item 3</div>
  <div class="irl-today-item">item 4</div>
  <div class="irl-today-item">item 5</div>
</div>


问:
How exactly CSS works?
Currently, I am stack with CSS. I can't understand how exactly CSS works.
If I want to apply "border: 1px solid red" to a CSS parent element then it is only applied to parent element but not other elements (children) that inside this parent. But If I apply "color: red" then the color property is applied to every single child inside the parent (Including parent itself).

Example-1:

```<code><div class="parent">
    Inside parent class
    <div class="child">Inside child class 1</div>
    <div class="child">Inside child class 2</div>
</div>
</code>```

```<code>.parent {
  border: 1px solid red;
}
</code>```

Example-2:

```<code><div class="parent">
    Inside parent class
    <div class="child">Inside child class 1</div>
    <div class="child">Inside child class 2</div>
</div>
</code>```

```<code>.parent {
  color: red;
}
</code>```

why example-1 works for the parent element, not for children.
Example-2 works fine what I expected.

答:
Some CSS properties "cascade" down to children elements, some don't. border is an example that does not cascade down.

More information in the MDN documentation.

Title: How exactly CSS works?

Body:
Currently, I am stack with CSS. I can't understand how exactly CSS works.
If I want to apply "border: 1px solid red" to a CSS parent element then it is only applied to parent element but not other elements (children) that inside this parent. But If I apply "color: red" then the color property is applied to every single child inside the parent (Including parent itself).

Example-1:

    Inside parent class

Inside child class 1

Inside child class 2

.parent {
  border: 1px solid red;
}

Example-2:

    Inside parent class

Inside child class 1

Inside child class 2

.parent {
  color: red;
}

why example-1 works for the parent element, not for children.
Example-2 works fine what I expected.


问:
In windows, how do I find out a folders sort by parameters
I am building an image viewing app in Node.js. I noticed that in Windows, the pictures in a folder can be sorted by name, size, status, type, date and tags etc, and grouped after sorting by the same list and more.

Is there a way of getting the sort parameters or maybe just retrieving the sorted list of files, matching the regular expression /\.(jpg|jpg_large|jpeg|jpe|jfif|jif|jfi|jpe|gif|png|ico|bmp|webp|svg)$/i, as an array (ex: ['c:\man.jpg', 'c:\woman.jpg'] using Powershell?

EDIT:

This article got me closer to a solution. https://cyberforensicator.com/2019/02/03/shellbags-forensics-directory-viewing-preferences/

Unfortunately it doesn't explain how to get the nodelist value for a given folder so I used an app called shellbagsview from nirsoft to get this value. In any case, if the value is found the rest is easy. I have included a sample python script which explains how this is done here.

```<code>from winreg import *

# Registry is of the form:
# HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\1375\Shell\{5C4F28B5-F869-4E84-8E60-F11DB97C5CC7}
# where 1375 is a value called the NodeList, and {5C4F28B5-F869-4E84-8E60-F11DB97C5CC7} is a value under Shell chosen based on creation date. It is a good idea to look at the registry after getting the nodelist from shellbagsview
folder_reg_path = "Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\Shell\\Bags\\1375\\Shell\\{5C4F28B5-F869-4E84-8E60-F11DB97C5CC7}"

# the size of icons used by the folder
def get_folder_icon_size(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'IconSize')
        return '%d pixels' % (value[0])

# the folder view. details, list, tiles e.t.c
def get_logical_view_mode(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'LogicalViewMode')
        logical_view_mode_dict = {1 : "Details view", 2 : "Tiles view", 3 : "Icons view", 4 : "List view", 5 : "Content view"}
        return logical_view_mode_dict[value[0]]

# folder view is based on view mode. so you can have a  logical view mode of icons view with a view mode of large icons for instance
def get_folder_view_mode(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'Mode')
        # view_mode 7 is only available on xp. A dead os
        view_mode_dict = {1 : "Medium icons", 2 : "Small icons", 3 : "List", 4 : "Details", 5 : "Thumbnail icons", 6 : "Large icons", 8 : "Content"}
        return view_mode_dict[value[0]]

# how is the folder being sorted
def get_folder_sort_by(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'Sort')
        folder_sort_dict = {"0E000000" : "Date Modified", "10000000" : "Date Accessed", "0F000000" : "Date Created", "0B000000" : "Type", "0C000000" : "Size", "0A000000" : "Name", "02000000" : "Title", "05000000" : "Tags"}
        # we get a byte value which we will hexify and get a rather long string
        # similar to : 000000000000000000000000000000000100000030f125b7ef471a10a5f102608c9eebac0c000000ffffffff
        reg_value = value[0].hex()
        # now for this string, we need to get the last 16 strings. then we now get the first 8 out of it. so we will have
        folder_sort_dict_key = (reg_value[-16:][:8]).upper()
        return folder_sort_dict[folder_sort_dict_key]

# in what order is the folder being sorted. ascending or descending???
def get_folder_sort_by_order(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'Sort')
        folder_sort_dict = {"01000000" : "Ascending", "FFFFFFFF" : "Descending"}
        # we get a byte value which we will hexify and get a rather long string
        # similar to : 000000000000000000000000000000000100000030f125b7ef471a10a5f102608c9eebac0c000000ffffffff
        reg_value = value[0].hex()
        # now for this string, we need to get the last 16 strings. then we now get the last 8 out of it. so we will have
        folder_sort_dict_key = (reg_value[-16:][-8:]).upper()
        return folder_sort_dict[folder_sort_dict_key]

icon_size = get_folder_icon_size(folder_reg_path)
logical_view_mode = get_logical_view_mode(folder_reg_path)
view_mode = get_folder_view_mode(folder_reg_path)
sorted_by = get_folder_sort_by(folder_reg_path)
sorted_by_order = get_folder_sort_by_order(folder_reg_path)
print ('The folder icon size is %s' % icon_size)
print('The folder logical view mode is %s' % logical_view_mode)
print('The folder view mode is %s' % view_mode)
print('The folder is sorted by %s in %s order' % (sorted_by, sorted_by_order))
</code>```

答:
The question itself and
the environment to run this in is unclear.

As you reference PowerShell and a RegEx to limit to specific extensions,

With this sample tree:

```<code>> tree /f a:\
A:\
└───Test
        boy.bmp
        child.ico
        girl.gif
        man.jpg
        woman.jpg
</code>```

this script:

```<code>Get-ChildItem -Path A:\Test -File |
 Where-Object Extension -match '\.(jpg|jpg_large|jpeg|jpe|jfif|jif|jfi|jpe|gif|png|ico|bmp|webp|svg)$' |
  Sort-Object Name |
   Select-Object -ExpandProperty FullName |
    ConvertTo-Json -Compress
</code>```

yields:

```<code>["A:\\Test\\boy.bmp","A:\\Test\\child.ico","A:\\Test\\girl.gif","A:\\Test\\man.jpg","A:\\Test\\woman.jpg"]
</code>```

Body:
I am building an image viewing app in Node.js. I noticed that in Windows, the pictures in a folder can be sorted by name, size, status, type, date and tags etc, and grouped after sorting by the same list and more.

Is there a way of getting the sort parameters or maybe just retrieving the sorted list of files, matching the regular expression /\.(jpg|jpg_large|jpeg|jpe|jfif|jif|jfi|jpe|gif|png|ico|bmp|webp|svg)$/i, as an array (ex: ['c:\man.jpg', 'c:\woman.jpg'] using Powershell?

EDIT:

This article got me closer to a solution. https://cyberforensicator.com/2019/02/03/shellbags-forensics-directory-viewing-preferences/

Unfortunately it doesn't explain how to get the nodelist value for a given folder so I used an app called shellbagsview from nirsoft to get this value. In any case, if the value is found the rest is easy. I have included a sample python script which explains how this is done here.

from winreg import *

# Registry is of the form:
# HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\1375\Shell\{5C4F28B5-F869-4E84-8E60-F11DB97C5CC7}
# where 1375 is a value called the NodeList, and {5C4F28B5-F869-4E84-8E60-F11DB97C5CC7} is a value under Shell chosen based on creation date. It is a good idea to look at the registry after getting the nodelist from shellbagsview
folder_reg_path = "Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\Shell\\Bags\\1375\\Shell\\{5C4F28B5-F869-4E84-8E60-F11DB97C5CC7}"

# the size of icons used by the folder
def get_folder_icon_size(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'IconSize')
        return '%d pixels' % (value[0])

# the folder view. details, list, tiles e.t.c
def get_logical_view_mode(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'LogicalViewMode')
        logical_view_mode_dict = {1 : "Details view", 2 : "Tiles view", 3 : "Icons view", 4 : "List view", 5 : "Content view"}
        return logical_view_mode_dict[value[0]]

# folder view is based on view mode. so you can have a  logical view mode of icons view with a view mode of large icons for instance
def get_folder_view_mode(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'Mode')
        # view_mode 7 is only available on xp. A dead os
        view_mode_dict = {1 : "Medium icons", 2 : "Small icons", 3 : "List", 4 : "Details", 5 : "Thumbnail icons", 6 : "Large icons", 8 : "Content"}
        return view_mode_dict[value[0]]

# how is the folder being sorted
def get_folder_sort_by(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'Sort')
        folder_sort_dict = {"0E000000" : "Date Modified", "10000000" : "Date Accessed", "0F000000" : "Date Created", "0B000000" : "Type", "0C000000" : "Size", "0A000000" : "Name", "02000000" : "Title", "05000000" : "Tags"}
        # we get a byte value which we will hexify and get a rather long string
        # similar to : 000000000000000000000000000000000100000030f125b7ef471a10a5f102608c9eebac0c000000ffffffff
        reg_value = value[0].hex()
        # now for this string, we need to get the last 16 strings. then we now get the first 8 out of it. so we will have
        folder_sort_dict_key = (reg_value[-16:][:8]).upper()
        return folder_sort_dict[folder_sort_dict_key]

# in what order is the folder being sorted. ascending or descending???
def get_folder_sort_by_order(reg_key):
    with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
        value = QueryValueEx(key, 'Sort')
        folder_sort_dict = {"01000000" : "Ascending", "FFFFFFFF" : "Descending"}
        # we get a byte value which we will hexify and get a rather long string
        # similar to : 000000000000000000000000000000000100000030f125b7ef471a10a5f102608c9eebac0c000000ffffffff
        reg_value = value[0].hex()
        # now for this string, we need to get the last 16 strings. then we now get the last 8 out of it. so we will have
        folder_sort_dict_key = (reg_value[-16:][-8:]).upper()
        return folder_sort_dict[folder_sort_dict_key]

icon_size = get_folder_icon_size(folder_reg_path)
logical_view_mode = get_logical_view_mode(folder_reg_path)
view_mode = get_folder_view_mode(folder_reg_path)
sorted_by = get_folder_sort_by(folder_reg_path)
sorted_by_order = get_folder_sort_by_order(folder_reg_path)
print ('The folder icon size is %s' % icon_size)
print('The folder logical view mode is %s' % logical_view_mode)
print('The folder view mode is %s' % view_mode)
print('The folder is sorted by %s in %s order' % (sorted_by, sorted_by_order))

Body:
The question itself and
the environment to run this in is unclear.

As you reference PowerShell and a RegEx to limit to specific extensions,

With this sample tree:

> tree /f a:\
A:\
└───Test
        boy.bmp
        child.ico
        girl.gif
        man.jpg
        woman.jpg

this script:

Get-ChildItem -Path A:\Test -File |
 Where-Object Extension -match '\.(jpg|jpg_large|jpeg|jpe|jfif|jif|jfi|jpe|gif|png|ico|bmp|webp|svg)$' |
  Sort-Object Name |
   Select-Object -ExpandProperty FullName |
    ConvertTo-Json -Compress

yields:

["A:\\Test\\boy.bmp","A:\\Test\\child.ico","A:\\Test\\girl.gif","A:\\Test\\man.jpg","A:\\Test\\woman.jpg"]


问:
HTML email - Outlook 2007+10, unrelated tables aligning
I've got a dilemma that I have never come across before that has stumped me. In a design a have built Outlook 07&10 are aligning two entirely unrelated table rows. This is a complex email layout, and so contains a lot of tables.
The content in the left column is sticking to the bottom (or top of the sibling) hr tag depicted here:

```<code><tr><td height="20"></td></tr>
<tr><!-- start of sidebar product (horizontal)-->
    <td>
        <table cellpadding="0" cellspacing="0" border="0">
            <tr>
                <td width="170">
                    <a href="" title="inline product 2" style="text-decoration: none;">
                        <!-- product Image -->
                        <img border="0" style="font-family:Arial,Helvetica,sans-serif;display:block" src="sidebar-beer-tbc.jpg" alt="South Island Marlborough Sauvignon Blanc" width="170" height="105">
                    </a>
...
</code>```

There is at least three parent tables per column (when the different sections are added up), so there should be no reason why the rendering engine is trying to align them.

Any help would be greatly appreciated, this has got me at my wit's end.

As this is for a client and contains sensitive information, I haven't made available the finished document, but here is an annotated grab of the two comparisons.
https://skitch.com/tilt/r3w65/photoshop

答:
Outlook does this when there are spans (colspan or rowspan). While other clients treat spanned rows and columns and separate in terms of layout, outlook will calculate them incorrectly. It's the result of the use of the idiotic Word layout engine in outlook -- a decision that has set email formatting back to 1995 -- but I digress.

The solution to your problem is to take the offending boxes and instead of using any spans, make it into its own complete table. So in your image, the individual drinks on the left will be in a 3x3 unspanned table, and the vertical "product TBD" sidebar would be it's own 1x4 or whatever vertical unspanned table. In general, this has solved it for me. Also, sometimes it's necessary to give these inner tables a fixed height to prevent them from becoming height="100%" and breaking the layout (again, only in outlook).

Body:
I've got a dilemma that I have never come across before that has stumped me. In a design a have built Outlook 07&10 are aligning two entirely unrelated table rows. This is a complex email layout, and so contains a lot of tables.
The content in the left column is sticking to the bottom (or top of the sibling) hr tag depicted here:

...

There is at least three parent tables per column (when the different sections are added up), so there should be no reason why the rendering engine is trying to align them.

Any help would be greatly appreciated, this has got me at my wit's end.

As this is for a client and contains sensitive information, I haven't made available the finished document, but here is an annotated grab of the two comparisons.
https://skitch.com/tilt/r3w65/photoshop