问:
How can I reduce the duplicate data from my aggregation pipeline?
I have a pipeline that works great for what I need... but I think there is some redundant data that can be removed from the pipeline.

Expected output

This is what I want the output to look like

```<code>{
  "_id": "5ecee2189fdd1b0004056936",
  "name": "Mike",
  "history": [
    {
        "_id": "5ecb263c166b8500047c1411",
        "what": "Log IN"
    },
    {
        "_id": "5ecb263c166b8500047c1422",
        "what": "Log OUT"
    }
  ]
}
</code>```

Current output

This is what the output currently looks like

```<code>{
  "docs": [
    {
      "_id": "5ecee2189fdd1b0004056936",
      "name": "Mike",
      "history": {
        "_id": "5ecb263c166b8500047c1411",
        "what": "Log IN"
      },
      "historyIndex": 0
    },
    {
      "_id": "5ecee2189fdd1b0004056936",
      "name": "Mike",
      "history": {
        "_id": "5ecb263c166b8500047c1422",
        "what": "Log OUT"
      },
      "historyIndex": 1
    }
  ]
}
</code>```

User doc

In real life there will be more users than this... of course...

```<code>{
  "_id": "5ecee2189fdd1b0004056936",
  "name": "Mike",
}
</code>```

History docs

again, to make it simple, I am keeping data short

```<code>[
  {
    "_id": "5ecb263c166b8500047c1411",
    "userId": "5ecee2189fdd1b0004056936",
    "what": "Log IN"
  },
  {
    "_id": "5ecb263c166b8500047c1422",
    "userId": "5ecee2189fdd1b0004056999",
    "what": "Log IN"
  },
  {
    "_id": "5ecb263c166b8500047c1433",
    "userId": "5ecee2189fdd1b0004056936",
    "what": "Log OUT"
  },
  {
    "_id": "5ecb263c166b8500047c1444",
    "userId": "5ecee2189fdd1b0004056999",
    "what": "Log OUT"
  }
]
</code>```

mongoose-aggregate-paginate-v2 middleware

I am also using mongoose-aggregate-paginate-v2, but I don't think that is my issue, but it definitely comes into play when the results are returned.  it needs to have the docs flattened so it can count and paginate them:

```<code>    "totalDocs": 941,
    "limit": 500,
    "page": 1,
    "totalPages": 2,
    "pagingCounter": 1,
    "hasPrevPage": false,
    "hasNextPage": true,
    "prevPage": null,
    "nextPage": 2
</code>```

Pipeline

Here is my pipeline

```<code>        var agg_match = {
            $match:
            {
                _id: mongoose.Types.ObjectId(userId)
            }
        };

        var agg_lookup = {
            $lookup: {
                from: 'it_userhistories',
                localField: '_id',
                foreignField: 'userId',
                as: 'history'
            }
        }

        var agg_unwind = {
            $unwind: {
                path: "$history",
                preserveNullAndEmptyArrays: true,
                includeArrayIndex: 'historyIndex',
            }
        }

        var agg = [
            agg_match,
            agg_lookup,
            agg_unwind,
            agg_project,
        ];

        var pageAndLimit = {
            page:page,
            limit:limit
        }

       User.aggregatePaginate(myAggregate, pageAndLimit)
</code>```

答:
You can use $map operator to do this. Following query will be helpful (I have not included the match stage in the pipeline, you can easily include it):

db.user.aggregate([
  {
    $lookup: {
      from: "history",
      localField: "_id",
      foreignField: "userId",
      as: "history"
    }
  },
  {
    $project: {
      name: 1,
      history: {
        $map: {
          input: "$history",
          as: "h",
          in: {
            _id: "$$h._id",
            what: "$$h.what"
          }
        }
      }
    }
  }
])
```

MongoPLayGroundLink

Body:
I have a pipeline that works great for what I need... but I think there is some redundant data that can be removed from the pipeline.

Expected output

This is what I want the output to look like

{
  "_id": "5ecee2189fdd1b0004056936",
  "name": "Mike",
  "history": [
    {
        "_id": "5ecb263c166b8500047c1411",
        "what": "Log IN"
    },
    {
        "_id": "5ecb263c166b8500047c1422",
        "what": "Log OUT"
    }
  ]
}

Current output

This is what the output currently looks like

{
  "docs": [
    {
      "_id": "5ecee2189fdd1b0004056936",
      "name": "Mike",
      "history": {
        "_id": "5ecb263c166b8500047c1411",
        "what": "Log IN"
      },
      "historyIndex": 0
    },
    {
      "_id": "5ecee2189fdd1b0004056936",
      "name": "Mike",
      "history": {
        "_id": "5ecb263c166b8500047c1422",
        "what": "Log OUT"
      },
      "historyIndex": 1
    }
  ]
}

User doc

In real life there will be more users than this... of course...

{
  "_id": "5ecee2189fdd1b0004056936",
  "name": "Mike",
}

History docs

again, to make it simple, I am keeping data short

[
  {
    "_id": "5ecb263c166b8500047c1411",
    "userId": "5ecee2189fdd1b0004056936",
    "what": "Log IN"
  },
  {
    "_id": "5ecb263c166b8500047c1422",
    "userId": "5ecee2189fdd1b0004056999",
    "what": "Log IN"
  },
  {
    "_id": "5ecb263c166b8500047c1433",
    "userId": "5ecee2189fdd1b0004056936",
    "what": "Log OUT"
  },
  {
    "_id": "5ecb263c166b8500047c1444",
    "userId": "5ecee2189fdd1b0004056999",
    "what": "Log OUT"
  }
]

mongoose-aggregate-paginate-v2 middleware

I am also using mongoose-aggregate-paginate-v2, but I don't think that is my issue, but it definitely comes into play when the results are returned.  it needs to have the docs flattened so it can count and paginate them:

    "totalDocs": 941,
    "limit": 500,
    "page": 1,
    "totalPages": 2,
    "pagingCounter": 1,
    "hasPrevPage": false,
    "hasNextPage": true,
    "prevPage": null,
    "nextPage": 2

Pipeline

Here is my pipeline

        var agg_match = {
            $match:
            {
                _id: mongoose.Types.ObjectId(userId)
            }
        };

        var agg_lookup = {
            $lookup: {
                from: 'it_userhistories',
                localField: '_id',
                foreignField: 'userId',
                as: 'history'
            }
        }

        var agg_unwind = {
            $unwind: {
                path: "$history",
                preserveNullAndEmptyArrays: true,
                includeArrayIndex: 'historyIndex',
            }
        }

        var agg = [
            agg_match,
            agg_lookup,
            agg_unwind,
            agg_project,
        ];

        var pageAndLimit = {
            page:page,
            limit:limit
        }

       User.aggregatePaginate(myAggregate, pageAndLimit)

Body:
You can use $map operator to do this. Following query will be helpful (I have not included the match stage in the pipeline, you can easily include it):

db.user.aggregate([
  {
    $lookup: {
      from: "history",
      localField: "_id",
      foreignField: "userId",
      as: "history"
    }
  },
  {
    $project: {
      name: 1,
      history: {
        $map: {
          input: "$history",
          as: "h",
          in: {
            _id: "$$h._id",
            what: "$$h.what"
          }
        }
      }
    }
  }
])

MongoPLayGroundLink


来源: stackexchange

问:
Global Build Events in Visual Studio
Is there a way to have a "global" build event in SV2005?  What I mean by "global" is an event that will execute for all projects without having to specify the build event for each one.

Thanks,
Kevin

答:
Here is a previous Stack Overflow question that outlines how to do it using Macros. The
answer is for Visual Studio 2008 but it will also work for Visual Studio 2005.</p>

ContentLicense: CC BY-SA 3.0

Title: Global Build Events in Visual Studio


问:
Calculate perc of each element in a list for each value in column in pandas dataframe
The df I am working on looks like this

```<code>co1   col2
A     ['1','2','er']
A     []
B     ['1','3','4','abc']
B     ['5']
C     []
</code>```

I want to calculate the % of each element in the list in col2 for each value in col1. i.e
calculate % of 1 for A, calculate % of 2 for A, calculate % of abc for B
I am looking for a solution to do this iteratively. Thanks

The link to input data (before explode) - [https://drive.google.com/file/d/1fuOBo8PK1heAtfufBlplXXfh4FiLpBCD/view?usp=sharing][1]

The link to output after explode - [https://drive.google.com/file/d/1mcArrsu3TWJC6hYZ2kIHAkAzCaHd1DLH/view?usp=sharing][2]

答:
I believe you need DataFrame.explode with DataFrame.dropna:

```<code>#changed data for better sample
print (df)
  col1           col2
0    A      [1, 2, 1]
1    A             []
2    B  [3, abc, abc]
3    B          [abc]
4    C             []

df2 = df.explode('col2').dropna(subset=['col2'])
print (df2)
  col1 col2
0    A    1
0    A    2
0    A    1
2    B    3
2    B  abc
2    B  abc
3    B  abc
</code>```

And then SeriesGroupBy.value_counts:

```<code>df2 = df2.groupby('col1')['col2'].value_counts(normalize=True).reset_index(name='%')
print (df2)
  col1 col2         %
0    A    1  0.666667
1    A    2  0.333333
2    B  abc  0.750000
3    B    3  0.250000
</code>```

EDIT:

```<code>import ast

df = pd.read_csv('beforeexplode.csv')

df['col2'] = df['col2'].apply(ast.literal_eval)
df2 = df.explode('col2').dropna(subset=['col2'])
print (df2)
     col1     col2
0    dev1  android
1    dev1  android
2    dev3     oscp
2    dev3     gpen
2    dev3      ceh
..    ...      ...
206  dev2     wcag
207  dev2    linux
207  dev2     unix
208  dev2    linux
208  dev2     unix

[460 rows x 2 columns]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The df I am working on looks like this

co1   col2
A     ['1','2','er']
A     []
B     ['1','3','4','abc']
B     ['5']
C     []

I want to calculate the % of each element in the list in col2 for each value in col1. i.e
calculate % of 1 for A, calculate % of 2 for A, calculate % of abc for B
I am looking for a solution to do this iteratively. Thanks

The link to input data (before explode) - [https://drive.google.com/file/d/1fuOBo8PK1heAtfufBlplXXfh4FiLpBCD/view?usp=sharing][1]

The link to output after explode - [https://drive.google.com/file/d/1mcArrsu3TWJC6hYZ2kIHAkAzCaHd1DLH/view?usp=sharing][2]

Body:
I believe you need DataFrame.explode with DataFrame.dropna:

#changed data for better sample
print (df)
  col1           col2
0    A      [1, 2, 1]
1    A             []
2    B  [3, abc, abc]
3    B          [abc]
4    C             []

df2 = df.explode('col2').dropna(subset=['col2'])
print (df2)
  col1 col2
0    A    1
0    A    2
0    A    1
2    B    3
2    B  abc
2    B  abc
3    B  abc

And then SeriesGroupBy.value_counts:

df2 = df2.groupby('col1')['col2'].value_counts(normalize=True).reset_index(name='%')
print (df2)
  col1 col2         %
0    A    1  0.666667
1    A    2  0.333333
2    B  abc  0.750000
3    B    3  0.250000

EDIT:

import ast

df = pd.read_csv('beforeexplode.csv')

df['col2'] = df['col2'].apply(ast.literal_eval)
df2 = df.explode('col2').dropna(subset=['col2'])
print (df2)
     col1     col2
0    dev1  android
1    dev1  android
2    dev3     oscp
2    dev3     gpen
2    dev3      ceh
..    ...      ...
206  dev2     wcag
207  dev2    linux
207  dev2     unix
208  dev2    linux
208  dev2     unix

[460 rows x 2 columns]


问:
Behavior of after() method inside a for loop in Tkinter GUI
In my sample GUI code, I want to print two different string one after another multiple times. I want some time duration between each string print on the console. I used root.after() method for this and iterate inside 'for loop' to achieve multiple time print.
Here is my code.

```<code>import tkinter as tk
from tkinter import *

def display1():
    print('hello world!')

def display2():
    print('hello there!')

def print_it():
    for i in range(2):
        root.after(7000,display1)   #to print after seven second.
        root.after(7000+5000,display2)  #to print after five second of first sentence print.

root = tk.Tk()
root.title("testing")
root.geometry('100x100')

btn = tk.Button(root,text='click it',command=print_it)
btn.pack(side = TOP)
root.mainloop()
</code>```

The problem is in spite of printing one after another, both strings are printing together and not after a given time. I cannot understand the behavior of the after() method. What am I doing wrong?

Thank you.

答: As per above answer I understood the behavior of root.after() method i.e. In the background, root.after() is added to the event loop, but with the condition that it shouldn't be executed until at least 7 seconds (for this case) from when after() was called. During those 7 seconds, any other events in the queue will be executed first. The command might be executed later than 7 seconds, depending on what's being processed already in the event queue, but no sooner.</p>

Body:
In my sample GUI code, I want to print two different string one after another multiple times. I want some time duration between each string print on the console. I used root.after() method for this and iterate inside 'for loop' to achieve multiple time print.
Here is my code.

import tkinter as tk
from tkinter import *

def display1():
    print('hello world!')

def display2():
    print('hello there!')

def print_it():
    for i in range(2):
        root.after(7000,display1)   #to print after seven second.
        root.after(7000+5000,display2)  #to print after five second of first sentence print.

root = tk.Tk()
root.title("testing")
root.geometry('100x100')

btn = tk.Button(root,text='click it',command=print_it)
btn.pack(side = TOP)
root.mainloop()

The problem is in spite of printing one after another, both strings are printing together and not after a given time. I cannot understand the behavior of the after() method. What am I doing wrong?

Thank you.


问:
Ignore spaces in redirected output in bash
I want to sort files by size in descending order, and list them next to their size in human-readable form.
So what I did is:

```<code>find $arg -type f -print -exec du -a {} + | sort -nr | head -11 | tail -10 | awk '{$1=""; print $0}' | xargs du -h
</code>```

And output:

```<code>3.7G    /path/to/file.iso
400M    /path/to/file2.iso
du: cannot access '/path/to/friends': No such file or directory
</code>```

Because the full name of friends in this example is:

```<code>/path/to/friends\ 1_1.mp4
</code>```

How can I deal with these issues?
And also is the better way to do the job?

答:
Almost all utilities in GNU coreutils package have an option for changing line terminator to NUL (either -z or -0), you can use them to avoid dealing with spaces, special characters, etc in input lines. And the sort utility from that package can sort human-readable numbers as well; so, you don't even need xargs and the second du here.

```<code>find "$arg" -type f -exec du -0ha {} + \
| sort -zhr  \
| head -zn11 \
| tail -zn10 \
| tr '\0' '\n'
</code>```

Body:
I want to sort files by size in descending order, and list them next to their size in human-readable form.
So what I did is:

find $arg -type f -print -exec du -a {} + | sort -nr | head -11 | tail -10 | awk '{$1=""; print $0}' | xargs du -h

And output:

3.7G    /path/to/file.iso
400M    /path/to/file2.iso
du: cannot access '/path/to/friends': No such file or directory

Because the full name of friends in this example is:

/path/to/friends\ 1_1.mp4

How can I deal with these issues?
And also is the better way to do the job?

Body:
Almost all utilities in GNU coreutils package have an option for changing line terminator to NUL (either -z or -0), you can use them to avoid dealing with spaces, special characters, etc in input lines. And the sort utility from that package can sort human-readable numbers as well; so, you don't even need xargs and the second du here.

find "$arg" -type f -exec du -0ha {} + \
| sort -zhr  \
| head -zn11 \
| tail -zn10 \
| tr '\0' '\n'


问:
How to achieve independent cloned TADODataSet?
The scenarios is like this:

We have some SQL table. We are performing an SQL query on this table and we have results in TADOQuery object.

```<code>var
  qryOryginal, qryClone: TADOQuery;

begin
  //setup all the things here
  qryOryginal.Active := True;
  qryClone.Clone(qryOryginal, ltBatchOptimistic);
  qryOryginal.Delete; //delete in qryOryginal casues that qryClone deletes its record too!
end;
</code>```

So, after cloning the DataSet my qryClone should hold and independent data(at least I thought so). However, performing Delete on qryOryginal causes the same operation on the qryClone. I don't want that.

Any ideas?

I know I could store the data elsewhere, in TClientDataSet perhaps but I would like to try the above solution first.

Thanks in advance for your time.

答:
Or second way, use Devexpress dxMemData. Very useful and easy-to-use component.

```<code>var
  MD: TdxMemData;
  SP: TADOStoredProc;
...
...
  // and after opening stored procedure:
  MD.Close;
  MD.Open;
  MD.LoadFromDataset(SP);
</code>```

Body:
The scenarios is like this:

We have some SQL table. We are performing an SQL query on this table and we have results in TADOQuery object.

var
  qryOryginal, qryClone: TADOQuery;

begin
  //setup all the things here
  qryOryginal.Active := True;
  qryClone.Clone(qryOryginal, ltBatchOptimistic);
  qryOryginal.Delete; //delete in qryOryginal casues that qryClone deletes its record too!
end;

So, after cloning the DataSet my qryClone should hold and independent data(at least I thought so). However, performing Delete on qryOryginal causes the same operation on the qryClone. I don't want that.

Any ideas?

I know I could store the data elsewhere, in TClientDataSet perhaps but I would like to try the above solution first.

Thanks in advance for your time.

Body:
Or second way, use Devexpress dxMemData. Very useful and easy-to-use component.

var
  MD: TdxMemData;
  SP: TADOStoredProc;
...
...
  // and after opening stored procedure:
  MD.Close;
  MD.Open;
  MD.LoadFromDataset(SP);


问:
Equivalent version of SHA256 ComputeHash (from C#) for React Native/JS
I'm trying to build an equivalent version of SHA256 ComputeHash (from C#, the EXACT same output from the below sample), to React Native/JavaScript.
This is the following C#:

```<code>public static string Hash(string input)
{
    if (string.IsNullOrWhiteSpace(input)) return "";

    using (SHA256 hasher = SHA256.Create())
    {
        // Convert the input string to a byte array and compute the hash.
        byte[] data = hasher.ComputeHash(Encoding.Unicode.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("X2"));
        }

        // Return the hexadecimal string.
        return $"0x{sBuilder.ToString().ToLower()}";
    }
}
</code>```

I tried the following, but it doesn't generate the same Hash:

```<code>import * as Crypto from 'expo-crypto';

const hash = await Crypto.digestStringAsync(
    Crypto.CryptoDigestAlgorithm.SHA256,
    "StringIWantToHash"
);
</code>```

Would anyone know, either what's wrong with the JavaScript, or if there is an exact equivalent version of the C# one?

答:
Solution 1: Use UTF8 instead of Unicode

Well, this is an Encoding problem.

Encoding.Unicode is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else). http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx (see this answer)

You should be using Encoding.UTF8.GetBytes instead.

Using js-sha256 library like this:

const jssha = require('js-sha256')

function hash(input)
{
    const hashString = "0x" + jssha.sha256(input)
    return hashString;
}

const hashResult = hash("StringIWantToHash")
// Output: 0x29c506d0d69a16e413d63921b7de79525c43715931d8d93127dbeb46eacda2f9
```

<p>We can achieve pretty similar in C# just using <strong>UTF8 encoding</strong>:</p>

<pre class="lang-cs prettyprint-override"><code>public static string Hash(string input)
{
    if (string.IsNullOrWhiteSpace(input)) return "";

    using (SHA256 hasher = SHA256.Create())
    {
        // Convert the input string to a byte array and compute the hash.
        byte[] data = hasher.ComputeHash(Encoding.UTF8.GetBytes(input)); // Note that UTF8 here

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("X2"));
        }

        // Return the hexadecimal string.
        return $"0x{sBuilder.ToString().ToLower()}";
    }
}

static void Main()
{
    var hashResult = Hash("StringIWantToHash");
    // Output: 0x29c506d0d69a16e413d63921b7de79525c43715931d8d93127dbeb46eacda2f9
}
</code>```

Also, I believe that other JS/React Native libraries that help to compute SHA256 hash use UTF8 encoding too, so I think you can use any other crypto libraries for that.

Solution 2: What if you need to use Unicode?

In that case, you need to manually represent C# encoding in JS code.

While you are using Unicode encoding, after every single byte in the string goes '0' byte if it is a plain Latin character. For other symbols (with more than 255 number) Unicode required 2 bytes for that.

var input = "StringIWantToHash";
var encodedInput = Encoding.Unicode.GetBytes(input);
// Output: [83, 0, 116, 0, 114, 0, 105, 0, 110, 0, ...]
```

<p>So we need to represent that in our JS code:</p>

<pre class="lang-js prettyprint-override"><code>const jssha = require('js-sha256')

function hash(input)
{
    var bytes = [];
    for (var i = 0; i < input.length; i++)
    {
        const code = input.charCodeAt(i);
        bytes = bytes.concat([code & 0xff, code / 256 >>> 0]);
    }

    const hashString = "0x" + jssha.sha256(bytes)
    return hashString;
}

const hashResult = hash("StringIWantToHash")
// Output: 0x029dbc4b54b39bed6d684175b2d76cc5622c60fe91f0bde9865b977d0d9a531d
</code>```

Body:
I'm trying to build an equivalent version of SHA256 ComputeHash (from C#, the EXACT same output from the below sample), to React Native/JavaScript.
This is the following C#:

public static string Hash(string input)
{
    if (string.IsNullOrWhiteSpace(input)) return "";

    using (SHA256 hasher = SHA256.Create())
    {
        // Convert the input string to a byte array and compute the hash.
        byte[] data = hasher.ComputeHash(Encoding.Unicode.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("X2"));
        }

        // Return the hexadecimal string.
        return $"0x{sBuilder.ToString().ToLower()}";
    }
}

I tried the following, but it doesn't generate the same Hash:

import * as Crypto from 'expo-crypto';

const hash = await Crypto.digestStringAsync(
    Crypto.CryptoDigestAlgorithm.SHA256,
    "StringIWantToHash"
);

Would anyone know, either what's wrong with the JavaScript, or if there is an exact equivalent version of the C# one?

Body:
Solution 1: Use UTF8 instead of Unicode

Well, this is an Encoding problem.

Encoding.Unicode is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else). http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx (see this answer)

You should be using Encoding.UTF8.GetBytes instead.

Using js-sha256 library like this:

const jssha = require('js-sha256')

function hash(input)
{
    const hashString = "0x" + jssha.sha256(input)
    return hashString;
}

const hashResult = hash("StringIWantToHash")
// Output: 0x29c506d0d69a16e413d63921b7de79525c43715931d8d93127dbeb46eacda2f9

We can achieve pretty similar in C# just using UTF8 encoding:

public static string Hash(string input)
{
    if (string.IsNullOrWhiteSpace(input)) return "";

    using (SHA256 hasher = SHA256.Create())
    {
        // Convert the input string to a byte array and compute the hash.
        byte[] data = hasher.ComputeHash(Encoding.UTF8.GetBytes(input)); // Note that UTF8 here

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("X2"));
        }

        // Return the hexadecimal string.
        return $"0x{sBuilder.ToString().ToLower()}";
    }
}

static void Main()
{
    var hashResult = Hash("StringIWantToHash");
    // Output: 0x29c506d0d69a16e413d63921b7de79525c43715931d8d93127dbeb46eacda2f9
}

Also, I believe that other JS/React Native libraries that help to compute SHA256 hash use UTF8 encoding too, so I think you can use any other crypto libraries for that.

Solution 2: What if you need to use Unicode?

In that case, you need to manually represent C# encoding in JS code.

While you are using Unicode encoding, after every single byte in the string goes '0' byte if it is a plain Latin character. For other symbols (with more than 255 number) Unicode required 2 bytes for that.

var input = "StringIWantToHash";
var encodedInput = Encoding.Unicode.GetBytes(input);
// Output: [83, 0, 116, 0, 114, 0, 105, 0, 110, 0, ...]

So we need to represent that in our JS code:

const jssha = require('js-sha256')

function hash(input)
{
    var bytes = [];
    for (var i = 0; i < input.length; i++)
    {
        const code = input.charCodeAt(i);
        bytes = bytes.concat([code & 0xff, code / 256 >>> 0]);
    }

    const hashString = "0x" + jssha.sha256(bytes)
    return hashString;
}

const hashResult = hash("StringIWantToHash")
// Output: 0x029dbc4b54b39bed6d684175b2d76cc5622c60fe91f0bde9865b977d0d9a531d


问:
Add `if` condition in gatsby jsx
I want to add  elements in gatsby template file in some cases.

I am developing document site using gatsby, the document made by markdown file.
Here is md files, and gatsby template. How can I add  elements if the document has pinned=true condition??

markdown

```<code>---
title: "doc title"
date: "2020-06-01"
tags: ["some","tags"]
pinned: TRUE
---

document body.
</code>```

template file

```<code>import React from "react"
import { graphql } from "gatsby"

export default class DocsList extends React.Component {
  render() {
    const posts = this.props.data.allMarkdownRemark.edges
    return (
    <div>
      {posts.map(({ node }) => {
        const title = node.frontmatter.title || node.fields.slug
        const tags = node.frontmatter.tags || node.fields.slug
        const ispinned = node.frontmatter.pinned || node.fields.slug
        return(
        <p>{title}</p>
        <p>{(tags || []).map(tags => (<span className="tags" key={tags}><FaHashtag />{tags}</span>))}</p>

        // if the document has `pinned=true` attribute, show <span> tag below
        <p>{if {ispinned===true ? `<span>This is PINNED item</span>` }}</p>
        )
        })}
    </div>
        )
    }
}

export const query = graphql`
query docssListQuery($skip: Int!, $limit: Int!) {
  allMarkdownRemark(
    filter: {
      fields: { collection: { eq: "manuals" } }
      frontmatter: { published: { ne: false } }
    }
    sort: { fields: [frontmatter___date], order: DESC }
    limit: $limit
    skip: $skip
  ) {
    edges {
      node {
        id
        fields {
          slug
        }
        frontmatter {
          title
          date
          tags
          pinned
        }
        excerpt
        timeToRead
      }
    }
  }
}
`;
</code>```

答:
You should use conditional rendering. Change your code:

```<code>// if the document has `pinned=true` attribute, show <span> tag below
<p>{if {ispinned===true ? `<span>This is PINNED item</span>` }}</p>
</code>```

to

```<code>// if the document has `pinned=true` attribute, show <span> tag below
<p>{ispinned ? `<span>This is PINNED item</span>`: null }</p>
</code>```

Title: Add `if` condition in gatsby jsx

Body:
I want to add  elements in gatsby template file in some cases.

I am developing document site using gatsby, the document made by markdown file.
Here is md files, and gatsby template. How can I add  elements if the document has pinned=true condition??

markdown

---
title: "doc title"
date: "2020-06-01"
tags: ["some","tags"]
pinned: TRUE
---

document body.

template file

import React from "react"
import { graphql } from "gatsby"

export default class DocsList extends React.Component {
  render() {
    const posts = this.props.data.allMarkdownRemark.edges
    return (

      {posts.map(({ node }) => {
        const title = node.frontmatter.title || node.fields.slug
        const tags = node.frontmatter.tags || node.fields.slug
        const ispinned = node.frontmatter.pinned || node.fields.slug
        return(

{title}

{(tags || []).map(tags => (<FaHashtag />{tags}))}

        // if the document has `pinned=true` attribute, show  tag below

{if {ispinned===true ? `<span>This is PINNED item</span>` }}

        )
        })}

        )
    }
}

export const query = graphql`
query docssListQuery($skip: Int!, $limit: Int!) {
  allMarkdownRemark(
    filter: {
      fields: { collection: { eq: "manuals" } }
      frontmatter: { published: { ne: false } }
    }
    sort: { fields: [frontmatter___date], order: DESC }
    limit: $limit
    skip: $skip
  ) {
    edges {
      node {
        id
        fields {
          slug
        }
        frontmatter {
          title
          date
          tags
          pinned
        }
        excerpt
        timeToRead
      }
    }
  }
}
`;

Body:
You should use conditional rendering. Change your code:

// if the document has `pinned=true` attribute, show <span> tag below
<p>{if {ispinned===true ? `<span>This is PINNED item</span>` }}</p>

to

// if the document has `pinned=true` attribute, show <span> tag below
<p>{ispinned ? `<span>This is PINNED item</span>`: null }</p>


问:
What if I pass a non existing resource pool in vertica?
What if I pass a non existing resource pool in vertica?

Will it use the default resource pool then, if it doesn't finds that. I just need to confirm..

As in the log it shows this but it doesn't crashes and keeps running?

Could not find configured Resource Pool: my_resource_pool

答:
It will fall to the general resource pool.

In an running session, you can verify that by the command:
SHOW resource_pool;

After the fact , you can identify transaction_id and statement_id of the queries of that session in query_requests, and find the matching row(s) in query_consumption.


问:
Passing hash reference to multiple functions in Perl
I have following code in Perl where a hash reference is passed from main function to func1 and then to func2. In func2 hash is updated. I want to access the updated hash in main function. Also there is a while loop in main function and i am expecting the hash should be updated during every iteration. The code might not look logical, but i have just written the skeleton of the code. I always get empty hash when i try to print the hash in main function</p>

```<code>sub main {
      my %hash1;
      while (some condition)
      {
        my $i=0;
        if($i==0)
        {
          func1($i,\%hash1);
          $i=1;
        }
        else
        {
          func1($i,\%hash1);
          $i=0;
        }
      }
      foreach my $a (keys %hash1)
      {
        print "$hash1{$a}";
      }
}
sub func1
{
my ($i,$hash1)=@_;
----
if($i==0)
{
   func2($hash1);
}

}

sub func2
{
my ($hash2)=@_;
$hash2->{key1}=1;
$hash2->{key2}=2;
}
</code>```

答:
Ah, I see. You think it's not printing anything as a result of the hash's being empty. But it's really not printing anything because you're not giving it anything to run. You're giving it stuff to compile, but nothing to run.

sub main means nothing in Perl. In order to get that to run, you have to put somewhere on your mainline main(); Then provided that you comment out the --- on line 25, you'll get the output you expect.

This is why printing stuff out yourself is either 1) a bit more typing, or 2) not reliable. You saw nothing and thought our hash was empty. When really, the code never even got to the declaration. So, here's a hint, on the command line:

```<code> cpan Smart::Comments
</code>```

And then, in your code:

```<code>use Smart::Comments;
...

### %hash1
</code>```

That way an empty hash looks like this:

```<code>### %hash1: {}
</code>```

And the one that you expect, looks like this:

```<code>### %hash1: {
###           key1 => 1,
###           key2 => 2
###         }
</code>```

Without calling the main sub, your output looks like this:

(yes, it is blank)

Otherwise, there is nothing wrong with your passing the hash.

Body:
I have following code in Perl where a hash reference is passed from main function to func1 and then to func2. In func2 hash is updated. I want to access the updated hash in main function. Also there is a while loop in main function and i am expecting the hash should be updated during every iteration. The code might not look logical, but i have just written the skeleton of the code. I always get empty hash when i try to print the hash in main function

sub main {
      my %hash1;
      while (some condition)
      {
        my $i=0;
        if($i==0)
        {
          func1($i,\%hash1);
          $i=1;
        }
        else
        {
          func1($i,\%hash1);
          $i=0;
        }
      }
      foreach my $a (keys %hash1)
      {
        print "$hash1{$a}";
      }
}
sub func1
{
my ($i,$hash1)=@_;
----
if($i==0)
{
   func2($hash1);
}

}

sub func2
{
my ($hash2)=@_;
$hash2->{key1}=1;
$hash2->{key2}=2;
}

Body:
Ah, I see. You think it's not printing anything as a result of the hash's being empty. But it's really not printing anything because you're not giving it anything to run. You're giving it stuff to compile, but nothing to run.

sub main means nothing in Perl. In order to get that to run, you have to put somewhere on your mainline main(); Then provided that you comment out the --- on line 25, you'll get the output you expect.

This is why printing stuff out yourself is either 1) a bit more typing, or 2) not reliable. You saw nothing and thought our hash was empty. When really, the code never even got to the declaration. So, here's a hint, on the command line:

 cpan Smart::Comments

And then, in your code:

use Smart::Comments;
...

### %hash1

That way an empty hash looks like this:

### %hash1: {}

And the one that you expect, looks like this:

### %hash1: {
###           key1 => 1,
###           key2 => 2
###         }

Without calling the main sub, your output looks like this:

(yes, it is blank)

Otherwise, there is nothing wrong with your passing the hash.


问:
SwiftUI: Overlap between views in VStack
I learned to create this HTMLStringView to show html strings in my app:

```<code>struct HTMLStringView: UIViewRepresentable {
    let htmlContent: String

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.loadHTMLString(htmlContent, baseURL: nil)
    }
}
</code>```

I found that there is a height: 112 overlap between the ZStack and whatever view below it. As zIndex = 1, if I want to show the HTMLStringView below the ZStack, I will have to put a Rectangle of height 112 in between. As shown in the code below:

```<code>ScrollView{

                            VStack(spacing:0){

                                ZStack{

                                    ZStack (alignment: .leading){
                                        UrlImageView(urlString: thisItem.cover_img, imageWidth: self.expandedScreen_shown ? UIScreen.main.bounds.width : self.cardWidth, imageHeight: self.maxCardHeight)
                                    }.offset(y: self.expandedScreen_shown ? 0 : 0)
                                        .clipped()
                                        .background(Color.white)
                                        .foregroundColor(Color.green)
                                        .edgesIgnoringSafeArea(.top)

                                    VStack (alignment: .leading){
                                        Spacer()

                                        Text("\(thisItem.title)")
                                            .font(.title)
                                            .foregroundColor(Color.white)
                                            .padding(.leading, 23)
                                            .padding(.trailing, 23)
                                            .padding(.top, 20)
                                            .padding(.bottom, 10)

                                        Text("\(thisItem.author) | \(thisItem.source)")
                                            .font(.body)
                                            .foregroundColor(Color.white)
                                            .padding(.leading, 23)
                                            .padding(.trailing, 23)
                                            .padding(.bottom, 20)
                                    }

                                }.frame(height: self.maxCardHeight * 0.5)
                                    .zIndex(1)

                                Rectangle()
                                    .fill(Color.white)
                                    .frame(height: 112)

                                HTMLStringView(htmlContent: "<p>Hello World!</p>")
                                    .padding()
                                    .background(Color.white)
                                    .frame(height: 300)
                                    .border(Color.green)

                            }
</code>```

I am currently using iPhone 11 as my emulator, and the overlap height changes when I switch to emulators with other screen sizes. Does anyone know why there is an overlap? If I cannot get rid of it, what proportion is it with respect to the screen size?

Thanks in advance!

答:
I have the following test code that shows there is no problem with
 expanding the view that is set to be invisible initially.

So my answer is, no it is not a problem with your expanding view that is set to be invisible initially.
 The problem must be related to something else in your code.

I would look closely at the

```<code> ZStack{...}
 .frame(height: self.maxHeight)
 .zIndex(1)
</code>```

especially the "self.maxHeight" and the height of the Rectangle.

As a test replace "self.maxHeight" with say 50, and see what happens.

Another edit.

```<code>class Item {
var title = "title"
var author = "author"
var source = "source"
var cover_img = "cover_img"
}

struct ContentView: View {

@State var expandedScreen_shown = false
@State var maxHeight: CGFloat = UIScreen.main.bounds.height/2
@State var cardWidth = CGFloat(UIScreen.main.bounds.width)
@State var maxCardHeight = CGFloat(444)

func itemView(_ thisItem: Item) -> some View {
    VStack (alignment: .leading) {
        Text(thisItem.title)
            .font(.title)
            .foregroundColor(Color.white)
            .padding(.leading, 23)
            .padding(.trailing, 23)
            .padding(.top, 20)
            .padding(.bottom, 10)

        Text("\(thisItem.author) | \(thisItem.source)")
            .font(.body)
            .foregroundColor(Color.white)
            .padding(.leading, 23)
            .padding(.trailing, 23)
            .padding(.bottom, 20)
    }
}

func imageView(_ thisItem: Item) -> some View {
    VStack {
        ZStack {
            ZStack (alignment: .leading) {
                UrlImageView(urlString: thisItem.cover_img, imageWidth: self.expandedScreen_shown ? UIScreen.main.bounds.width : self.cardWidth, imageHeight: self.maxCardHeight)
            }.frame(width: self.expandedScreen_shown ? UIScreen.main.bounds.width : self.cardWidth, height: self.maxCardHeight)
                .offset(y: self.expandedScreen_shown ? 0 : 0)
                .clipped()
                .background(Color.blue)
                .foregroundColor(Color.green)
                .edgesIgnoringSafeArea(.top)

            self.itemView(thisItem)

        }.frame(height: self.maxCardHeight * 0.5)
            .zIndex(1)
    }
}

var body: some View {
    ScrollView {
        VStack (spacing:0) {

            imageView(Item())

            Rectangle()
                .fill(Color.red)
                .frame(height: 112)

            HTMLStringView(htmlContent: "<p>Hello World!</p>")
                .padding()
                .background(Color.white)
                .frame(height: 300)
                .border(Color.green)
        }
    }
}

}
</code>```

Body:
I learned to create this HTMLStringView to show html strings in my app:

struct HTMLStringView: UIViewRepresentable {
    let htmlContent: String

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.loadHTMLString(htmlContent, baseURL: nil)
    }
}

I found that there is a height: 112 overlap between the ZStack and whatever view below it. As zIndex = 1, if I want to show the HTMLStringView below the ZStack, I will have to put a Rectangle of height 112 in between. As shown in the code below:

ScrollView{

                            VStack(spacing:0){

                                ZStack{

                                    ZStack (alignment: .leading){
                                        UrlImageView(urlString: thisItem.cover_img, imageWidth: self.expandedScreen_shown ? UIScreen.main.bounds.width : self.cardWidth, imageHeight: self.maxCardHeight)
                                    }.offset(y: self.expandedScreen_shown ? 0 : 0)
                                        .clipped()
                                        .background(Color.white)
                                        .foregroundColor(Color.green)
                                        .edgesIgnoringSafeArea(.top)

                                    VStack (alignment: .leading){
                                        Spacer()

                                        Text("\(thisItem.title)")
                                            .font(.title)
                                            .foregroundColor(Color.white)
                                            .padding(.leading, 23)
                                            .padding(.trailing, 23)
                                            .padding(.top, 20)
                                            .padding(.bottom, 10)

                                        Text("\(thisItem.author) | \(thisItem.source)")
                                            .font(.body)
                                            .foregroundColor(Color.white)
                                            .padding(.leading, 23)
                                            .padding(.trailing, 23)
                                            .padding(.bottom, 20)
                                    }

                                }.frame(height: self.maxCardHeight * 0.5)
                                    .zIndex(1)

                                Rectangle()
                                    .fill(Color.white)
                                    .frame(height: 112)

                                HTMLStringView(htmlContent: "
Hello World!
")
                                    .padding()
                                    .background(Color.white)
                                    .frame(height: 300)
                                    .border(Color.green)

                            }

I am currently using iPhone 11 as my emulator, and the overlap height changes when I switch to emulators with other screen sizes. Does anyone know why there is an overlap? If I cannot get rid of it, what proportion is it with respect to the screen size?

Thanks in advance!

Body:
I have the following test code that shows there is no problem with
 expanding the view that is set to be invisible initially.

So my answer is, no it is not a problem with your expanding view that is set to be invisible initially.
 The problem must be related to something else in your code.

I would look closely at the

 ZStack{...}
 .frame(height: self.maxHeight)
 .zIndex(1)

especially the "self.maxHeight" and the height of the Rectangle.

As a test replace "self.maxHeight" with say 50, and see what happens.

Another edit.

class Item {
var title = "title"
var author = "author"
var source = "source"
var cover_img = "cover_img"
}

struct ContentView: View {

@State var expandedScreen_shown = false
@State var maxHeight: CGFloat = UIScreen.main.bounds.height/2
@State var cardWidth = CGFloat(UIScreen.main.bounds.width)
@State var maxCardHeight = CGFloat(444)

func itemView(_ thisItem: Item) -> some View {
    VStack (alignment: .leading) {
        Text(thisItem.title)
            .font(.title)
            .foregroundColor(Color.white)
            .padding(.leading, 23)
            .padding(.trailing, 23)
            .padding(.top, 20)
            .padding(.bottom, 10)

        Text("\(thisItem.author) | \(thisItem.source)")
            .font(.body)
            .foregroundColor(Color.white)
            .padding(.leading, 23)
            .padding(.trailing, 23)
            .padding(.bottom, 20)
    }
}

func imageView(_ thisItem: Item) -> some View {
    VStack {
        ZStack {
            ZStack (alignment: .leading) {
                UrlImageView(urlString: thisItem.cover_img, imageWidth: self.expandedScreen_shown ? UIScreen.main.bounds.width : self.cardWidth, imageHeight: self.maxCardHeight)
            }.frame(width: self.expandedScreen_shown ? UIScreen.main.bounds.width : self.cardWidth, height: self.maxCardHeight)
                .offset(y: self.expandedScreen_shown ? 0 : 0)
                .clipped()
                .background(Color.blue)
                .foregroundColor(Color.green)
                .edgesIgnoringSafeArea(.top)

            self.itemView(thisItem)

        }.frame(height: self.maxCardHeight * 0.5)
            .zIndex(1)
    }
}

var body: some View {
    ScrollView {
        VStack (spacing:0) {

            imageView(Item())

            Rectangle()
                .fill(Color.red)
                .frame(height: 112)

            HTMLStringView(htmlContent: "<p>Hello World!</p>")
                .padding()
                .background(Color.white)
                .frame(height: 300)
                .border(Color.green)
        }
    }
}

}


问:
PCA - taking difference with mean
What is the intuition behind number 1 and 2 when it comes to considering mean? And how will this affect performance and accuracy?

Number 1:

```<code>    pca = decomposition.PCA(n_components=4)
    X_centered = X - X.mean(axis=0)
    pca.fit(X_centered)
    X_pca = pca.transform(X_centered)
</code>```

Number 2:

```<code>    pca = decomposition.PCA(n_components=4)
    pca.fit(X)
    X_pca = pca.transform(X)
</code>```

Thanks in advance

答: It will be the same. In a way, PCA find a set of basis vectors, which are orthogonal to each and maximize the variance in a set of points projections onto them. PCA therefore has rotation and translation symmetry. Therefore you will have identical PCA results whenever you shift your matrix (which is what subtraction of the mean essentially does) to not.</p>

Title: PCA - taking difference with mean

Body:
What is the intuition behind number 1 and 2 when it comes to considering mean? And how will this affect performance and accuracy?

Number 1:

    pca = decomposition.PCA(n_components=4)
    X_centered = X - X.mean(axis=0)
    pca.fit(X_centered)
    X_pca = pca.transform(X_centered)

Number 2:

    pca = decomposition.PCA(n_components=4)
    pca.fit(X)
    X_pca = pca.transform(X)

Thanks in advance


问:
how to use django model object in django templates?
I am not able to use the Django model object in Django templates. I want to iterate using the model user in the template and then play with the  ActivityPeriod(model) of that user. Please check my code for the clarity:

Here is my code:

views.py

```<code>from .models import User,ActivityPeriod

def call_response(request):
    user = User.objects.all()
    return render(request, "Test/list.html", {"users":user ,"activityperiod":ActivityPeriod})
</code>```

Test/list.html

```<code>{% for user in users %}
    'real_name': {{ user.real_name}}},
    'activity_periods': {% with activity=activityperiod.objects.get(id =user) %}
    {{ activity.start_time }}
    {% endwith %}
{% endfor %}
</code>```

But i am getting an error:
Could not parse the remainder: '(id' from 'activityperiod.objects.get(id'

What is the correct way? Can anyone please share it with me.

答:
Django template don't understand the filter action of Model. This part shoud be in view.

```<code>activity=activityperiod.objects.get(id =user)
</code>```

You should prepare your data and manipulate them before sending to template (a dictionary may help you). And remember that result of  action "User.objects.all()" is a list.

Body:
I am not able to use the Django model object in Django templates. I want to iterate using the model user in the template and then play with the  ActivityPeriod(model) of that user. Please check my code for the clarity:

Here is my code:

views.py

from .models import User,ActivityPeriod

def call_response(request):
    user = User.objects.all()
    return render(request, "Test/list.html", {"users":user ,"activityperiod":ActivityPeriod})

Test/list.html

{% for user in users %}
    'real_name': {{ user.real_name}}},
    'activity_periods': {% with activity=activityperiod.objects.get(id =user) %}
    {{ activity.start_time }}
    {% endwith %}
{% endfor %}

But i am getting an error:
Could not parse the remainder: '(id' from 'activityperiod.objects.get(id'

What is the correct way? Can anyone please share it with me.

Body:
Django template don't understand the filter action of Model. This part shoud be in view.

activity=activityperiod.objects.get(id =user)

You should prepare your data and manipulate them before sending to template (a dictionary may help you). And remember that result of  action "User.objects.all()" is a list.


问:
Open a view programmatically with tab controller from storyboard
I have a storyboard which has following views (scenes):

Login screen

TabBarController with 4 tabs ( Library, Workflow, Settings & downloads

Based on user login by clicking on the button (Sign in), I programatically load tab bar controller with always first tab with following code:

```<code>         LibraryWebViewContoller *lbc = [self.storyboard instantiateViewControllerWithIdentifier:@"docovaMainTabBarController"];
         [self presentViewController:lbc animated:YES completion:nil];
</code>```

What I want do is be able to open different tabs programmatically with TabBarController from storyboard. So far I am able to open the tab bar controller with first tab but no luck in opening others as it always seem to load the TabBarController with first tab selected.

答:
Swift 5</p>

```<code>let storyboard = UIStoryboard(name: "TabBarController", bundle: .main)
let tabbarController = storyboard.instantiateInitialViewController()
tabbarController?.modalPresentationStyle = .fullScreen
self.present(tabbarController!, animated: true, completion: nil)
</code>```

Body:
I have a storyboard which has following views (scenes):

Login screen

TabBarController with 4 tabs ( Library, Workflow, Settings & downloads

Based on user login by clicking on the button (Sign in), I programatically load tab bar controller with always first tab with following code:

         LibraryWebViewContoller *lbc = [self.storyboard instantiateViewControllerWithIdentifier:@"docovaMainTabBarController"];
         [self presentViewController:lbc animated:YES completion:nil];

What I want do is be able to open different tabs programmatically with TabBarController from storyboard. So far I am able to open the tab bar controller with first tab but no luck in opening others as it always seem to load the TabBarController with first tab selected.

Body:
Swift 5

let storyboard = UIStoryboard(name: "TabBarController", bundle: .main)
let tabbarController = storyboard.instantiateInitialViewController()
tabbarController?.modalPresentationStyle = .fullScreen
self.present(tabbarController!, animated: true, completion: nil)


问:
Pulumi - 'AWS_PROXY' currently only supports Lambda function
I want to create API Gateway connected to Lambda function with Alias, I have IntegrationRouteTargetProvider which is providing integration routes to the API. I got the URI from the lambda so I think it is correct. Also I checked number of SO questions and also in the documentation is arn:aws:apigateway:{region}:{subdomain.service|service}:path|action/{service_api}.

My uri is

arn:aws:apigateway:eu-central-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-central-1:051069080387:function:deploy-test-4-lambda/invocations.

However when I'm trying to create the api I get error:

Unable to put integration on 'ANY' for resource at path '/': Integrations of type 'AWS_PROXY' currently only supports Lambda function and Firehose stream invocations.

Here is my IntegrationRouteTargetProvider:

```<code>export class AliasLambdaProvider implements IntegrationRouteTargetProvider {
    target(name: string, parent: pulumi.Resource): pulumi.Input<IntegrationTarget> {
        return {
            type: "aws_proxy",
            uri: 'arn:aws:apigateway:eu-central-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-central-1:051069080387:function:deploy-test-4-lambda/invocations',
        };
    }
}
</code>```

and than using it when creating API

```<code>return new API(name, {
        routes: [
            {
                path: "/",
                target: new AliasLambdaProvider()
            }
        ],
        stageName: name + "-stage"
    }, { provider });
</code>```

答:
You're using:

type: "aws_proxy"

Which means everything is passed to the lambda and headers need to be handled at the lambda. Integration is disabled for AWS_Proxy type, thus the error. However, if you wanted to define integration methods/mapping templates etc, use:

type: "aws"

Body:
I want to create API Gateway connected to Lambda function with Alias, I have IntegrationRouteTargetProvider which is providing integration routes to the API. I got the URI from the lambda so I think it is correct. Also I checked number of SO questions and also in the documentation is arn:aws:apigateway:{region}:{subdomain.service|service}:path|action/{service_api}.

My uri is

arn:aws:apigateway:eu-central-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-central-1:051069080387:function:deploy-test-4-lambda/invocations.

However when I'm trying to create the api I get error:

Unable to put integration on 'ANY' for resource at path '/': Integrations of type 'AWS_PROXY' currently only supports Lambda function and Firehose stream invocations.

Here is my IntegrationRouteTargetProvider:

export class AliasLambdaProvider implements IntegrationRouteTargetProvider {
    target(name: string, parent: pulumi.Resource): pulumi.Input<IntegrationTarget> {
        return {
            type: "aws_proxy",
            uri: 'arn:aws:apigateway:eu-central-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-central-1:051069080387:function:deploy-test-4-lambda/invocations',
        };
    }
}

and than using it when creating API

return new API(name, {
        routes: [
            {
                path: "/",
                target: new AliasLambdaProvider()
            }
        ],
        stageName: name + "-stage"
    }, { provider });


问:
Typescript is giving me an error: Expected 0 arguments, but got 1
I want to define the interface the proper way but I am having trouble because it is expecting an argument even though the argument is empty.

I am using useContext and I defined the interface like this:

```<code>    //react-auth0-spa.tsx
    interface Auth0Context {
        ......
        loginWithRedirect:  () => void; //I know this is the problem but I don't know what to define.
        ......
     }
</code>```

in the provider, the value is :

```<code> //react-auth0-spa.tsx
 <Auth0Context.Provider
     value=({
  ....
  loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p)
   ....
   })
>
</code>```

now, I import the context to other the other file like so:
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()

and this is where the error occurs

```<code>///components/NavBar.tsx
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()
<div>
      {!isAuthenticated && (
        <button onClick={() => loginWithRedirect({})}>Log in</button> //Expected 0 arguments, but got 1
      )}
</div>
</code>```

so the problem is loginWithRedirect is expecting 1 argument, but () => loginWithRedirect({}) is an empty object. The problem can be solved by using any inside the interface but what should I put if I want to define it explicitly?

I tried loginWithRedirect:  ({}) => void but now loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p) is giving me error like this Type '{}' is not assignable to type 'string'.ts(2322)

source code without typescript is https://github.com/auth0-samples/auth0-react-samples/tree/master/01-Login/src

Please help.

答:
Problem in the first place is:

You provided signature of a function like this in the interface:

loginWithRedirect:  () => void;

which means no argument and whenever you'll define that function you will obey this signature but in contrary you are passing argument to the function while giving it's definition.

Solution

Why not doing like this?

```<code>//react-auth0-spa.tsx
    interface Auth0Context {
        ......
        loginWithRedirect:  (p: object) => void;
        ......
     }
</code>```

Body:
I want to define the interface the proper way but I am having trouble because it is expecting an argument even though the argument is empty.

I am using useContext and I defined the interface like this:

    //react-auth0-spa.tsx
    interface Auth0Context {
        ......
        loginWithRedirect:  () => void; //I know this is the problem but I don't know what to define.
        ......
     }

in the provider, the value is :

 //react-auth0-spa.tsx
 <Auth0Context.Provider
     value=({
  ....
  loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p)
   ....
   })
>

now, I import the context to other the other file like so:
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()

and this is where the error occurs

///components/NavBar.tsx
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()

      {!isAuthenticated && (
        <button onClick={() => loginWithRedirect({})}>Log in</button> //Expected 0 arguments, but got 1
      )}

so the problem is loginWithRedirect is expecting 1 argument, but () => loginWithRedirect({}) is an empty object. The problem can be solved by using any inside the interface but what should I put if I want to define it explicitly?

I tried loginWithRedirect:  ({}) => void but now loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p) is giving me error like this Type '{}' is not assignable to type 'string'.ts(2322)

source code without typescript is https://github.com/auth0-samples/auth0-react-samples/tree/master/01-Login/src

Please help.

Body:
Problem in the first place is:

You provided signature of a function like this in the interface:

loginWithRedirect:  () => void;

which means no argument and whenever you'll define that function you will obey this signature but in contrary you are passing argument to the function while giving it's definition.

Solution

Why not doing like this?

//react-auth0-spa.tsx
    interface Auth0Context {
        ......
        loginWithRedirect:  (p: object) => void;
        ......
     }


问:
Remote linux server to remote linux server large sparse files copy - How To?
I have two twins CentOS 5.4 servers with VMware Server installed  on each.

What is the most reliable and fast method for copying virtual machines files from one server to the other, assuming that I always use sparse file for my vmware virtual machines?

The vm's files are a pain to copy since they are very large (50 GB) but since they are sparse files I think something can be done to improve the speed of the copy.

答:
You could have a look at http://www.barricane.com/virtsync

(Disclaimer: I am the author.)

ContentLicense: CC BY-SA 2.5


问:
Django JSONResponse is returning a string and not JSON
I am using a Django view to return a JSON object. However when I use the method below, I get a string representation of the dictionary and not a JSON object.

```<code>def api_dataset_index(request):
    upload_file = request.FILES.get('file')
    if upload_file:
        config_str = upload_file.read().decode("utf-8")
        d = Dataset.from_yaml(config_str)
        return JsonResponse(model_to_dict(d))
</code>```

Response - "{\"id\": 31, \"name\": \"effort\", \"description\": \"Expressions of customer effort or ease.\", \"multilabeled\": false}"

Am I doing something wrong here? or is JSONResponse supposed to return a string?

Edit -

A string is a valid json representation. However, the content-type for the django.http method "JsonResponse" is being sent as a string rather than as an object. If the structure being passed to the JsonResponse() method is a list, then the encoding is done properly, that is, the client receives it as a json object and not just as a string.

Edit2

Turns out the issue I encountered was on client side code.

答:
Try this:

```<code>import json

def getObjects():
   objects = ...
   return JsonResponse(json.loads(objects))
</code>```

You should already be sure the method is returned a json not a String

Body:
I am using a Django view to return a JSON object. However when I use the method below, I get a string representation of the dictionary and not a JSON object.

def api_dataset_index(request):
    upload_file = request.FILES.get('file')
    if upload_file:
        config_str = upload_file.read().decode("utf-8")
        d = Dataset.from_yaml(config_str)
        return JsonResponse(model_to_dict(d))

Response - "{\"id\": 31, \"name\": \"effort\", \"description\": \"Expressions of customer effort or ease.\", \"multilabeled\": false}"

Am I doing something wrong here? or is JSONResponse supposed to return a string?

Edit -

A string is a valid json representation. However, the content-type for the django.http method "JsonResponse" is being sent as a string rather than as an object. If the structure being passed to the JsonResponse() method is a list, then the encoding is done properly, that is, the client receives it as a json object and not just as a string.

Edit2

Turns out the issue I encountered was on client side code.

Body:
Try this:

import json

def getObjects():
   objects = ...
   return JsonResponse(json.loads(objects))

You should already be sure the method is returned a json not a String


问:
Setting a variable via echo somtimes adds a random ' at the end
I have a bash script with the following functionality:

```<code># usage: setOutput <name> <value>
function setOutput {
  echo "##vso[task.setvariable variable=$1]$2"
}

setOutput environment "dev"
</code>```

This normally sets the variable correctly as ENVIRONMENT=dev - however, sometimes this randomly appends a ' at the end, i.e. ENVIRONMENT=dev'

I tried re-running the same commit on the pipeline multiple times, and sometimes it works, sometimes it doesn't. Any ideas?

答:
Base on the fact that @Hugh Lin - MSFT could not reproduce the issue, I looked a littel closer and found out, what was actually going wrong:

In the beginning of my script, I used:

```<code>set -ex
</code>```

This lead to there beeing two echos:

```<code>+echo '##vso[task.setvariable variable=key]value'
##vso[task.setvariable variable=key]value
</code>```

Depending on the order of the two (since the first is written to stderr, the second one to stdout), sometimes the value was set to the correct value, and somtimes to the debug echo one. And since that one has the addition ' at the end, so does the exported output.

My suggestion: Only process stdout for these echo commands, not stderr, or add a special filter for set -x. I removed the debug output and now it works.

Body:
I have a bash script with the following functionality:

# usage: setOutput <name> <value>
function setOutput {
  echo "##vso[task.setvariable variable=$1]$2"
}

setOutput environment "dev"

This normally sets the variable correctly as ENVIRONMENT=dev - however, sometimes this randomly appends a ' at the end, i.e. ENVIRONMENT=dev'

I tried re-running the same commit on the pipeline multiple times, and sometimes it works, sometimes it doesn't. Any ideas?

Body:
Base on the fact that @Hugh Lin - MSFT could not reproduce the issue, I looked a littel closer and found out, what was actually going wrong:

In the beginning of my script, I used:

set -ex

This lead to there beeing two echos:

+echo '##vso[task.setvariable variable=key]value'
##vso[task.setvariable variable=key]value

Depending on the order of the two (since the first is written to stderr, the second one to stdout), sometimes the value was set to the correct value, and somtimes to the debug echo one. And since that one has the addition ' at the end, so does the exported output.

My suggestion: Only process stdout for these echo commands, not stderr, or add a special filter for set -x. I removed the debug output and now it works.


问:
save scraped data to database python
I scraped data and saved the scraped data to the five lists and I created the table with five rows, now i do not know how to save my scraped data to the database.

my code is:

```<code>import requests
from bs4 import BeautifulSoup
import re
import mysql.connector

url = 'https://www.ebay.com/b/Cars-Trucks/6001?_fsrp=0&_sacat=6001&LH_BIN=1&LH_ItemCondition=3000%7C1000%7C2500&rt=nc&_stpos=95125&Model%2520Year=2020%7C2019%7C2018%7C2017%7C2016%7C2015'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
car_titles =[]
title = soup.find_all('h3', class_='s-item__title', limit = 20)
for title_of_car in title:
    car_titles.append(title_of_car.text)

car_brands = []
brands = soup.find_all('span', class_='s-item__dynamic s-item__dynamicAttributes1', limit = 20)
for brand in brands:
    brand = re.sub(r'Make: ','', brand.text)
    car_brands.append(brand)

car_models = []
models = soup.find_all('span', class_='s-item__dynamic s-item__dynamicAttributes2', limit = 20)
for model in models:
    model = re.sub(r'Model: ', '', model.text)
    car_models.append(model)

car_transmissions = []
transmissions = soup.find_all('span', class_='s-item__dynamic s-item__dynamicAttributes3', limit = 20)
for transmission in transmissions:
    transmission = re.sub(r'Transmission: ', '', transmission.text)
    car_transmissions.append(transmission)

car_prices = []
char_list = ['\$', '\,', '\.']
prices = soup.find_all('span', class_='s-item__price', limit = 20)
for price in prices:
    price = re.sub('|'.join(char_list), '', price.text)
    car_prices.append(int(price))
</code>```

答:
First get connected to mysql database by

```<code>import mysql.connector

config = {
  'user': 'username',
  'password': 'password',
  'host': '127.0.0.1',
  'database': 'dbname',
  'raise_on_warnings': True
}

cnx = mysql.connector.connect(**config)

# create cursor to execute mysql commands
cursor = cnx.cursor()

# Now create table like this one
cursor.execute("CREATE TABLE car_titles (title VARCHAR(255))")

# insert data to table like this one
for row in car_titles:
    cursor.execute("INSERT INTO car_titles (title) VALUES (%s)", row)

cnx.close()
</code>```

Mainly you have to use sql query to create table and insert data. So learn using mysql with python

Then create table

Title: save scraped data to database python

Body:
I scraped data and saved the scraped data to the five lists and I created the table with five rows, now i do not know how to save my scraped data to the database.

my code is:

import requests
from bs4 import BeautifulSoup
import re
import mysql.connector

url = 'https://www.ebay.com/b/Cars-Trucks/6001?_fsrp=0&_sacat=6001&LH_BIN=1&LH_ItemCondition=3000%7C1000%7C2500&rt=nc&_stpos=95125&Model%2520Year=2020%7C2019%7C2018%7C2017%7C2016%7C2015'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
car_titles =[]
title = soup.find_all('h3', class_='s-item__title', limit = 20)
for title_of_car in title:
    car_titles.append(title_of_car.text)

car_brands = []
brands = soup.find_all('span', class_='s-item__dynamic s-item__dynamicAttributes1', limit = 20)
for brand in brands:
    brand = re.sub(r'Make: ','', brand.text)
    car_brands.append(brand)

car_models = []
models = soup.find_all('span', class_='s-item__dynamic s-item__dynamicAttributes2', limit = 20)
for model in models:
    model = re.sub(r'Model: ', '', model.text)
    car_models.append(model)

car_transmissions = []
transmissions = soup.find_all('span', class_='s-item__dynamic s-item__dynamicAttributes3', limit = 20)
for transmission in transmissions:
    transmission = re.sub(r'Transmission: ', '', transmission.text)
    car_transmissions.append(transmission)

car_prices = []
char_list = ['\$', '\,', '\.']
prices = soup.find_all('span', class_='s-item__price', limit = 20)
for price in prices:
    price = re.sub('|'.join(char_list), '', price.text)
    car_prices.append(int(price))

Body:
First get connected to mysql database by

import mysql.connector

config = {
  'user': 'username',
  'password': 'password',
  'host': '127.0.0.1',
  'database': 'dbname',
  'raise_on_warnings': True
}

cnx = mysql.connector.connect(**config)

# create cursor to execute mysql commands
cursor = cnx.cursor()

# Now create table like this one
cursor.execute("CREATE TABLE car_titles (title VARCHAR(255))")

# insert data to table like this one
for row in car_titles:
    cursor.execute("INSERT INTO car_titles (title) VALUES (%s)", row)

cnx.close()

Mainly you have to use sql query to create table and insert data. So learn using mysql with python

Then create table


问:
Count and foreach yield different results
I've been using a method for splitting collections into batches form this answer - https://stackoverflow.com/a/17598878/1012739:

```<code>public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int size) {
    using (IEnumerator<T> enumerator = source.GetEnumerator())
        while (enumerator.MoveNext())
            yield return TakeIEnumerator(enumerator, size);
}

private static IEnumerable<T> TakeIEnumerator<T>(IEnumerator<T> source, int size) {
    int i = 0;
    do yield return source.Current;
    while (++i < size && source.MoveNext());
}
</code>```

When iterating over the results of Batch<T> one gets the expected number of collections, but when calling Count or ToList the outer collection length is reported:

```<code>var collection = new int[10];
var count = 0;
foreach(var batch in collection.Batch(2))
    ++count;
Assert.AreEqual(5, count); // Passes
// But
Assert.AreEqual(5, collection.Batch(2).Count());        // Fails
Assert.AreEqual(5, collection.Batch(2).ToList().Count); // Fails
</code>```

How does this work and is the a way to fix it?

答:
Your TakeIEnumerator<T> method is dependent upon the position of the enumerator (source), and thus is timing dependent... on itself. If the results are iterated by collating the "outer" results first, i.e.

var batches = source.Batch(24).ToList();
// then iterate in any way
```

<p>then by definition, <code>source</code> is exhausted, and you'll get N items in <code>batches</code>, where <code>N</code> is the number from <code>source</code>, and all the batches will be empty because there <em>is no more data</em>. If, however, the results are iterated depth first, i.e.</p>

<pre class="lang-cs prettyprint-override"><code>foreach (var batch in source) {
    foreach (var item in batch) {...}
}
</code>```

then you are looking at the open cursor. Ultimately, this approach is inherently brittle and dangerous. IMO your batch method should create buffers of computed data, perhaps a List<T> or similar. This will allocate, but: it'll be reliable. For example:

private static IEnumerable<T> TakeIEnumerator<T>(IEnumerator<T> source, int size) {
    var buffer = new List<T>(size);
    int i = 0;
    do buffer.Add(source.Current);
    while (++i < size && source.MoveNext())
    return buffer;
}
```

Body:
I've been using a method for splitting collections into batches form this answer - https://stackoverflow.com/a/17598878/1012739:

public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int size) {
    using (IEnumerator<T> enumerator = source.GetEnumerator())
        while (enumerator.MoveNext())
            yield return TakeIEnumerator(enumerator, size);
}

private static IEnumerable<T> TakeIEnumerator<T>(IEnumerator<T> source, int size) {
    int i = 0;
    do yield return source.Current;
    while (++i < size && source.MoveNext());
}

When iterating over the results of Batch<T> one gets the expected number of collections, but when calling Count or ToList the outer collection length is reported:

var collection = new int[10];
var count = 0;
foreach(var batch in collection.Batch(2))
    ++count;
Assert.AreEqual(5, count); // Passes
// But
Assert.AreEqual(5, collection.Batch(2).Count());        // Fails
Assert.AreEqual(5, collection.Batch(2).ToList().Count); // Fails

How does this work and is the a way to fix it?

Body:
Your TakeIEnumerator<T> method is dependent upon the position of the enumerator (source), and thus is timing dependent... on itself. If the results are iterated by collating the "outer" results first, i.e.

var batches = source.Batch(24).ToList();
// then iterate in any way

then by definition, source is exhausted, and you'll get N items in batches, where N is the number from source, and all the batches will be empty because there is no more data. If, however, the results are iterated depth first, i.e.

foreach (var batch in source) {
    foreach (var item in batch) {...}
}

then you are looking at the open cursor. Ultimately, this approach is inherently brittle and dangerous. IMO your batch method should create buffers of computed data, perhaps a List<T> or similar. This will allocate, but: it'll be reliable. For example:

private static IEnumerable<T> TakeIEnumerator<T>(IEnumerator<T> source, int size) {
    var buffer = new List<T>(size);
    int i = 0;
    do buffer.Add(source.Current);
    while (++i < size && source.MoveNext())
    return buffer;
}


问:
how to fetch text from cdata section of xml files
```<code><text>
    <![CDATA[
        <img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_1.jpg" width="600" />
        <img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_2.jpg" width="600" />
    ]]>
</text>
</description>
</code>```

this is my rss feed i want to fetch description from this by using sax parser .but am unable to do this so please help and suggest me all the possible way to do this
thanx in advance

答:
CDATA just tells the parser not to treat angle brackets as XML tags. You get the content just like any other character data inside a tag. Since you didn't mention anything here's Python:</p>

```<code>import xml.sax
from cStringIO import StringIO

class Handler(xml.sax.handler.ContentHandler):
    def characters(self, content):
        print content

rss = '<text><![CDATA[<img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_1.jpg" width="600" /><img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_2.jpg" width="600" />]]></text>'

xml.sax.parse(StringIO(rss), Handler())
</code>```

Body:
<text>
    <![CDATA[

    ]]>
</text>
</description>

this is my rss feed i want to fetch description from this by using sax parser .but am unable to do this so please help and suggest me all the possible way to do this
thanx in advance

Body:
CDATA just tells the parser not to treat angle brackets as XML tags. You get the content just like any other character data inside a tag. Since you didn't mention anything here's Python:

import xml.sax
from cStringIO import StringIO

class Handler(xml.sax.handler.ContentHandler):
    def characters(self, content):
        print content

rss = '<text><![CDATA[<img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_1.jpg" width="600" /><img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_2.jpg" width="600" />]]></text>'

xml.sax.parse(StringIO(rss), Handler())


答:
What about

```<code>library("anytime")
anytime(try$time)
</code>```

you can also get the date from the timestamps anydate(try$time)

and if you want UTC, you can do
anytime(try$time, asUTC = TRUE)

Title: Convert Unix timestamp into datetime

Body:
I have the following data frame

> head(try)
     creates       time
1  128.29508 1417392072
3  236.98361 1417392072
7   98.45902 1417392072
9  157.44068 1417392131
10 227.38333 1417392131
11 242.03390 1417392131

> str(try)
'data.frame':   102968 obs. of  2 variables:
 $ creates: num  128.3 237 98.5 157.4 227.4 ...
 $ time   : Factor w/ 26418 levels "1417392071","1417392072",..: 2 2 2 3 3 3 3 3 5 5 ...

I am unable to convert the UNIX timestamp into datetime using the following methods I tried

> head(as.POSIXlt(as.numeric(try$time),origin="1970-01-01",tz="GMT"))
[1] "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:03 UTC" "1970-01-01 00:00:03 UTC"
[6] "1970-01-01 00:00:03 UTC"

> head(as.POSIXct(as.character(try$time),tz="GMT"))

Error in as.POSIXlt.character(x, tz, ...) :
        character string is not in a standard unambiguous format

> head(as.POSIXlt(as.POSIXct(as.vector(as.numeric(try$time)),origin="1970-01-01")))
[1] "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:03 UTC" "1970-01-01 00:00:03 UTC"
[6] "1970-01-01 00:00:03 UTC"

I'm not sure what I'm doing incorrectly here.

Body:
What about

library("anytime")
anytime(try$time)

you can also get the date from the timestamps anydate(try$time)

and if you want UTC, you can do
anytime(try$time, asUTC = TRUE)


问:
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.

I know how to do that without using a function ,for example for any n numbers I have the following program:

```<code>#include<stdio.h>

int main()
{

    int n, i;
    float sum = 0, x;

    printf("Enter number of elements:  ");
    scanf("%d", &n);
    printf("\n\n\nEnter %d elements\n\n", n);
    for(i = 0; i < n; i++)
    {
        scanf("%f", &x);
        sum += x;
    }
    printf("\n\n\nAverage of the entered numbers is =  %f", (sum/n));

    return 0;
}

</code>```

Or this one which do that using arrays:

```<code>#include <iostream>
using namespace std;

int main()
{
    int n, i;
    float num[100], sum=0.0, average;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 100 || n <= 0)
    {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;

    return 0;
}

</code>```

But is it possible to use functions?if yes then how? thank you so much for helping.

答:
As an alternative to using fundamental types to store your values C++ provides std::vector to handle numeric storage (with automatic memory management) instead of plain old arrays, and it provides many tools, like std::accumulate. Using what C++ provides can substantially reduce your function to:

```<code>double avg (std::vector<int>& i)
{
    /* return sum of elements divided by the number of elements */
    return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
</code>```

In fact a complete example can require only a dozen or so additional lines, e.g.

```<code>#include <iostream>
#include <vector>
#include <numeric>

double avg (std::vector<int>& i)
{
    /* return sum of elements divided by the number of elements */
    return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}

int main (void) {

    int n;                                          /* temporary integer */
    std::vector<int> v {};                          /* vector of int */

    while (std::cin >> n)                           /* while good integer read */
        v.push_back(n);                             /* add to vector */

    std::cout << "\naverage: " << avg(v) << '\n';   /* output result */
}
</code>```

Above, input is taken from stdin and it will handle as many integers as you would like to enter (or redirect from a file as input). The std::accumulate simply sums the stored integers in the vector and then to complete the average, you simply divide by the number of elements (with a cast to double to prevent integer-division).

Example Use/Output

```<code>$ ./bin/accumulate_vect
10
20
34
done

average: 21.3333
</code>```

(note: you can enter any non-integer (or manual EOF) to end input of values, "done" was simply used above, but it could just as well be 'q' or "gorilla" -- any non-integer)

It is good to work both with plain-old array (because there is a lot of legacy code out there that uses them), but equally good to know that new code written can take advantage of the nice containers and numeric routines C++ now provides (and has for a decade or so).

Body:
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.

I know how to do that without using a function ,for example for any n numbers I have the following program:

#include<stdio.h>

int main()
{

    int n, i;
    float sum = 0, x;

    printf("Enter number of elements:  ");
    scanf("%d", &n);
    printf("\n\n\nEnter %d elements\n\n", n);
    for(i = 0; i < n; i++)
    {
        scanf("%f", &x);
        sum += x;
    }
    printf("\n\n\nAverage of the entered numbers is =  %f", (sum/n));

    return 0;
}

Or this one which do that using arrays:

#include <iostream>
using namespace std;

int main()
{
    int n, i;
    float num[100], sum=0.0, average;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 100 || n <= 0)
    {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;

    return 0;
}

But is it possible to use functions?if yes then how? thank you so much for helping.

Body:
As an alternative to using fundamental types to store your values C++ provides std::vector to handle numeric storage (with automatic memory management) instead of plain old arrays, and it provides many tools, like std::accumulate. Using what C++ provides can substantially reduce your function to:

double avg (std::vector<int>& i)
{
    /* return sum of elements divided by the number of elements */
    return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}

In fact a complete example can require only a dozen or so additional lines, e.g.

#include <iostream>
#include <vector>
#include <numeric>

double avg (std::vector<int>& i)
{
    /* return sum of elements divided by the number of elements */
    return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}

int main (void) {

    int n;                                          /* temporary integer */
    std::vector<int> v {};                          /* vector of int */

    while (std::cin >> n)                           /* while good integer read */
        v.push_back(n);                             /* add to vector */

    std::cout << "\naverage: " << avg(v) << '\n';   /* output result */
}

Above, input is taken from stdin and it will handle as many integers as you would like to enter (or redirect from a file as input). The std::accumulate simply sums the stored integers in the vector and then to complete the average, you simply divide by the number of elements (with a cast to double to prevent integer-division).

Example Use/Output

$ ./bin/accumulate_vect
10
20
34
done

average: 21.3333

(note: you can enter any non-integer (or manual EOF) to end input of values, "done" was simply used above, but it could just as well be 'q' or "gorilla" -- any non-integer)

It is good to work both with plain-old array (because there is a lot of legacy code out there that uses them), but equally good to know that new code written can take advantage of the nice containers and numeric routines C++ now provides (and has for a decade or so).


问:
draft.js: making editor content multipage
I have a difficult problem to solve.

Here is my sample project

Basically I want to create a editable book-like container and since each book page is another container, I can't figure how to make an editor transition from one page to another, once the page is filled with text.

Here is what I'm trying to achieve:

My first thought was to use a shared state for multiple editor instances, but as you can see in the example code, it doesn't work as expected and same text appears in two pages.

How can I achieve a multi-container transition when using draft.js?

答:
The logic in general is to listen to changes of the first editor, count characters / word / lines (or more advanced calculation, if the editor has scroll for example) and finally focus the second editor if needed.

This answer covers, listen, dummy calculation and focus on the next editor.
This answer doesn't cover the calculation itself nor dynamic number of pages nor moving back from second editor when deleting content etc. But I believe that it's a direction to your final goal.

Listen

First of all, I moved the state creation and handling back to the Editor component itself. What "interests" the parent component ("App") is to get notified when its content changed.

But now, App needs to access the ("draft-js") editor in order to call focus. This will solve by creating "ref" in App and propagate it using forwardRef.

```<code>const editorRef = React.useRef();

const Editor = React.forwardRef((props, ref) => {
  return <MyEditor name="editor-2" forwardRef={ref} />;
});

...

return (
  ...
  <Editor ref={editorRef} />
)
</code>```

and in Editor.js

```<code>function MyEditor({ onChange, forwardRef }) {
  ...
  return (
    <Editor
      ref={forwardRef}
  )
});
</code>```

Next thing is to add onChange to Editor so App get notified when the content has been changed.

```<code><Editor
  ref={forwardRef}
  stripPastedStyles
  editorState={editorState}
  onChange={editorState => {
    setEditorState(editorState);
    onChange && onChange(editorState); // <---
  }}
/>
</code>```

Handle the change and focus

The first editor is now

```<code><MyEditor name="editor-1" onChange={onEditorChange} />
</code>```

and onEditorChange is

```<code>const onEditorChange = editorState => {
  const text = editorState.getCurrentContent().getPlainText();
  if (text.length >= 5) {
    setTimeout(() => {
      editorRef.current.focus();
    });
  }
};
</code>```

Currently it checks if the content's length is 5. You probably want to calculate it in a more sophisticated way.

The last question is, why setTimeout? Well, the simple answer is that without it, "draft-js" throw an error. I believe that it's something with their implementation of release / delete / clear global variables or something.

And the most important part, the code and live demo :)

https://codesandbox.io/s/young-shape-t6kcc?file=/src/App.js

Body:
The logic in general is to listen to changes of the first editor, count characters / word / lines (or more advanced calculation, if the editor has scroll for example) and finally focus the second editor if needed.

This answer covers, listen, dummy calculation and focus on the next editor.
This answer doesn't cover the calculation itself nor dynamic number of pages nor moving back from second editor when deleting content etc. But I believe that it's a direction to your final goal.

Listen

First of all, I moved the state creation and handling back to the Editor component itself. What "interests" the parent component ("App") is to get notified when its content changed.

But now, App needs to access the ("draft-js") editor in order to call focus. This will solve by creating "ref" in App and propagate it using forwardRef.

const editorRef = React.useRef();

const Editor = React.forwardRef((props, ref) => {
  return <MyEditor name="editor-2" forwardRef={ref} />;
});

...

return (
  ...
  <Editor ref={editorRef} />
)

and in Editor.js

function MyEditor({ onChange, forwardRef }) {
  ...
  return (
    <Editor
      ref={forwardRef}
  )
});

Next thing is to add onChange to Editor so App get notified when the content has been changed.

<Editor
  ref={forwardRef}
  stripPastedStyles
  editorState={editorState}
  onChange={editorState => {
    setEditorState(editorState);
    onChange && onChange(editorState); // <---
  }}
/>

Handle the change and focus

The first editor is now

<MyEditor name="editor-1" onChange={onEditorChange} />

and onEditorChange is

const onEditorChange = editorState => {
  const text = editorState.getCurrentContent().getPlainText();
  if (text.length >= 5) {
    setTimeout(() => {
      editorRef.current.focus();
    });
  }
};

Currently it checks if the content's length is 5. You probably want to calculate it in a more sophisticated way.

The last question is, why setTimeout? Well, the simple answer is that without it, "draft-js" throw an error. I believe that it's something with their implementation of release / delete / clear global variables or something.

And the most important part, the code and live demo :)

https://codesandbox.io/s/young-shape-t6kcc?file=/src/App.js


问:
Build fails with Nuget package errors when solution is build in Azure Dev ops
We have recently decided to Implement CICD in the project ,using Azure Dev ops. We use TFS for the code check in and have the code repository in Azure Dev Ops.
Attaching the configurations we made for the project in Dev Ops pipeline.

答:
Open your project in Visual Studio locally, delete all packages or packages.config file. Then right click the solution/project, select manage nuget packagesand install the packages. Now you should see the packages.config file generated. Build the project locally to see whether it is successful. If the build is successful, check in the project (don't check in the packages) with packages.config file to DevOps, and use Nuget restore and Visual Studio Build tasks to build your project.

In addition, it seems you are using a self-hosted agent. Try to go to your agent machine, clean the folder F:\Build\Agent3\_work, and check build agent to make sure you are using the latest version.


问:
Other keys not working when using keydown event for arrow keys in KnockoutJs
I have the following binding on a div:

```<code><div class="my-class" tabindex="0" data-bind="event:{keydown:function(data, event){onKeyDown(event)}}">
</div>
</code>```

On document load, I bring focus to the div using:

```<code>$('.my-class').focus();
</code>```

I do the following inside script to handle up and down arrow keys whenever the div is in focus:

```<code>onKeyDown(event) {
    if (event.keyCode == 40 || event.keyCode == 38) {
        // My logic
    }

    return true;
}
</code>```

The up and down arrow keys work fine on the div. The problem now is that whenever the div is in focus, the keys other than up and down arrows does not work. How can I fix this?

答:
The value true returned from onKeyDown is not received by Knockout since there's no return statement in the keydown binding inside HTML.

Change the HTML to the following and it should work:

```<code><div class="my-class" tabindex="0" data-bind="event:{keydown:function(data, event){return onKeyDown(event)}}">
</div>
</code>```

Body:
I have the following binding on a div:

On document load, I bring focus to the div using:

$('.my-class').focus();

I do the following inside script to handle up and down arrow keys whenever the div is in focus:

onKeyDown(event) {
    if (event.keyCode == 40 || event.keyCode == 38) {
        // My logic
    }

    return true;
}

The up and down arrow keys work fine on the div. The problem now is that whenever the div is in focus, the keys other than up and down arrows does not work. How can I fix this?

Body:
The value true returned from onKeyDown is not received by Knockout since there's no return statement in the keydown binding inside HTML.

Change the HTML to the following and it should work:

<div class="my-class" tabindex="0" data-bind="event:{keydown:function(data, event){return onKeyDown(event)}}">
</div>


问:
Using private endpoints across Azure Subscription
If the two VNETs are peered, can a client in one VNET sitting in one Azure Subscription use Private Endpoint to a resource in another VNET setting in separate Azure Subscription? </p>

<p>Essentially, I am asking if Private Endpoints can be used across Azure subscriptions? </p>

答:
Of course Yes. You can see the description here:

The private endpoint can be reached from the same virtual network,
  regionally peered VNets, globally peered VNets and on premises using
  private VPN or ExpressRoute connections.

From this, it means the private endpoint can be reached from the globally peered VNets. And here is also a description for the global peering of VNet:

The ability to transfer data between virtual networks across Azure
  subscriptions, Azure Active Directory tenants, deployment models, and
  Azure regions.

So finally, the conclusion according to the two descriptions is that the private endpoint can be accessed across different subscriptions.

Body:
If the two VNETs are peered, can a client in one VNET sitting in one Azure Subscription use Private Endpoint to a resource in another VNET setting in separate Azure Subscription?

Essentially, I am asking if Private Endpoints can be used across Azure subscriptions?


问:
WSO2 analytics server database is growing
I am using WSO2 API Manager along with it's analytics server. I configured MySQL as it's database.
After a year of PROD use, I found that there are couple of tables from Analytics module, which consumes most of the DB space, around 95%.

Would like to know the significance of these tables. As well the challenges if we delete those tables.

Table names are

```<code>+--------------------------------+------------------------------------------------------+------------+
| Database                       | Table                                                | Size in MB |
+--------------------------------+------------------------------------------------------+------------+
| wso2_analytics_event_store     | anx___7lsekeca_                                      |     665.03 |
| wso2_analytics_event_store     | anx___7lmnf2xa_                                      |     638.00 |
| wso2_analytics_event_store     | anx___7lqcf_8o_                                      |     636.14 |
| wso2_analytics_event_store     | anx___7lmk3tr0_                                      |     398.13 |
| analytics_processed_data_store | anx___7lpteea4_                                      |     282.75 |
| analytics_processed_data_store | anx___7lsn7ita_                                      |     249.97 |
| wso2_analytics_event_store     | anx___7lsgqyce_                                      |     209.25 |
| wso2_analytics_event_store     | anx___7lmno15m_                                      |     207.25 |
| wso2_analytics_event_store     | anx___7lver1fy_                                      |     191.16 |
</code>```

答:
You can enable data purging for analytics tables. See below section taken from the docs.

Ref: https://docs.wso2.com/display/AM220/Purging+Analytics+Data

Body:
I am using WSO2 API Manager along with it's analytics server. I configured MySQL as it's database.
After a year of PROD use, I found that there are couple of tables from Analytics module, which consumes most of the DB space, around 95%.

Would like to know the significance of these tables. As well the challenges if we delete those tables.

Table names are

+--------------------------------+------------------------------------------------------+------------+
| Database                       | Table                                                | Size in MB |
+--------------------------------+------------------------------------------------------+------------+
| wso2_analytics_event_store     | anx___7lsekeca_                                      |     665.03 |
| wso2_analytics_event_store     | anx___7lmnf2xa_                                      |     638.00 |
| wso2_analytics_event_store     | anx___7lqcf_8o_                                      |     636.14 |
| wso2_analytics_event_store     | anx___7lmk3tr0_                                      |     398.13 |
| analytics_processed_data_store | anx___7lpteea4_                                      |     282.75 |
| analytics_processed_data_store | anx___7lsn7ita_                                      |     249.97 |
| wso2_analytics_event_store     | anx___7lsgqyce_                                      |     209.25 |
| wso2_analytics_event_store     | anx___7lmno15m_                                      |     207.25 |
| wso2_analytics_event_store     | anx___7lver1fy_                                      |     191.16 |