问:
AWS Signature v4 key value store KVS in C#
I'm trying to integrate "Signing AWS Requests with Signature Version 4" in C#. Unfortunately, Amazon has not given much detail into implementation in C#. I've tried my luck in implementing. But its throwing this error Message

"The remote server returned an error: (403) Forbidden.

Note: I've got this working on Postman. But not able to make it work in C#.
Error receiving: Message = "The remote server returned an error: (403) Forbidden.

I've used this documentation for signing https://docs.amazonaws.cn/en_us/general/latest/gr/sigv4_signing.html

```<code>    public WebRequest RequestPost(string canonicalUri, string canonicalQueriString, string jsonString)
    {
        string hashedRequestPayload = CreateRequestPayload(jsonString);

        string authorization = Sign(hashedRequestPayload, "PUT", canonicalUri, canonicalQueriString);
        string requestDate = DateTime.ParseExact(DateTime.UtcNow.ToString(), "YYYYMMDD'T'HHMMSS'Z'", CultureInfo.InvariantCulture).ToString();

        WebRequest webRequest = WebRequest.Create(canonicalUri + canonicalQueriString);

        webRequest.Method = "PUT";
        webRequest.ContentType = ContentType;
        webRequest.Headers.Add("X-Amz-date", requestDate);
        webRequest.Headers.Add("Authorization", authorization);
        webRequest.Headers.Add("x-amz-content-sha256", hashedRequestPayload);
        webRequest.ContentLength = jsonString.Length;

        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(jsonString);

        Stream newStream = webRequest.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        using (WebResponse response = webRequest.GetResponse())
        {
            StreamReader responseReader = new StreamReader(response.GetResponseStream());
            var responseJson = responseReader.ReadToEnd();
        }

        return webRequest;
    }

    const string RegionName = "eu-west-1"; //This is the regionName
    const string ServiceName = "execute-api";
    const string Algorithm = "AWS4-HMAC-SHA256";
    const string ContentType = "application/json";
    const string Host = "<hostname>";
    const string SignedHeaders = "content-type;host;x-amz-content-sha256;x-amz-date";

    private static string CreateRequestPayload(string jsonString)
    {
        //Here should be JSON object of the model we are sending with POST request
        //var jsonToSerialize = new { Data = String.Empty };

        //We parse empty string to the serializer if we are makeing GET request
        //string requestPayload = new JavaScriptSerializer().Serialize(jsonToSerialize);
        string hashedRequestPayload = HexEncode(Hash(ToBytes(jsonString)));

        return hashedRequestPayload;
    }

    private static string Sign(string hashedRequestPayload, string requestMethod, string canonicalUri, string canonicalQueryString)
    {
        var currentDateTime = DateTime.UtcNow;
        var accessKey = "";
        var secretKey = "";

        var dateStamp = currentDateTime.ToString("yyyyMMdd");
        //var requestDate = currentDateTime.ToString("YYYYMMDD'T'HHMMSS'Z");
        var requestDate = DateTime.ParseExact(currentDateTime.ToString(), "YYYYMMDD'T'HHMMSS'Z'", CultureInfo.InvariantCulture);
        var credentialScope = string.Format("{0}/{1}/{2}/aws4_request", dateStamp, RegionName, ServiceName);

        var headers = new SortedDictionary<string, string> {
        { "content-type", ContentType },
        { "host", Host  },
        { "x-amz-date", requestDate.ToString() }
    };

        string canonicalHeaders = string.Join("\n", headers.Select(x => x.Key.ToLowerInvariant() + ":" + x.Value.Trim())) + "\n";

        // Task 1: Create a Canonical Request For Signature Version 4
        string canonicalRequest = requestMethod + "\n" + canonicalUri + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\n" + SignedHeaders + "\n" + hashedRequestPayload;
        string hashedCanonicalRequest = HexEncode(Hash(ToBytes(canonicalRequest)));

        // Task 2: Create a String to Sign for Signature Version 4
        string stringToSign = Algorithm + "\n" + requestDate + "\n" + credentialScope + "\n" + hashedCanonicalRequest;

        // Task 3: Calculate the AWS Signature Version 4
        byte[] signingKey = GetSignatureKey(secretKey, dateStamp, RegionName, ServiceName);
        string signature = HexEncode(HmacSha256(stringToSign, signingKey));

        // Task 4: Prepare a signed request
        // Authorization: algorithm Credential=access key ID/credential scope, SignedHeadaers=SignedHeaders, Signature=signature

        string authorization = string.Format("{0} Credential={1}/{2}/{3}/{4}/aws4_request, SignedHeaders={5}, Signature={6}",
        Algorithm, accessKey, dateStamp, RegionName, ServiceName, SignedHeaders, signature);

        return authorization;
    }

    private static byte[] GetSignatureKey(string key, string dateStamp, string regionName, string serviceName)
    {
        byte[] kDate = HmacSha256(dateStamp, ToBytes("AWS4" + key));
        byte[] kRegion = HmacSha256(regionName, kDate);
        byte[] kService = HmacSha256(serviceName, kRegion);
        return HmacSha256("aws4_request", kService);
    }

    private static byte[] ToBytes(string str)
    {
        return Encoding.UTF8.GetBytes(str.ToCharArray());
    }

    private static string HexEncode(byte[] bytes)
    {
        return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
    }

    private static byte[] Hash(byte[] bytes)
    {
        return SHA256.Create().ComputeHash(bytes);
    }

    private static byte[] HmacSha256(string data, byte[] key)
    {
        return new HMACSHA256(key).ComputeHash(ToBytes(data));
    }
</code>```

答: Would you be willing to use the HttpClient instead of WebRequest? In that case I have created a NuGet package called AwsSignatureVersion4 which has been verified to work with the AWS API Gateway.

Body:
I'm trying to integrate "Signing AWS Requests with Signature Version 4" in C#. Unfortunately, Amazon has not given much detail into implementation in C#. I've tried my luck in implementing. But its throwing this error Message

"The remote server returned an error: (403) Forbidden.

Note: I've got this working on Postman. But not able to make it work in C#.
Error receiving: Message = "The remote server returned an error: (403) Forbidden.

I've used this documentation for signing https://docs.amazonaws.cn/en_us/general/latest/gr/sigv4_signing.html

    public WebRequest RequestPost(string canonicalUri, string canonicalQueriString, string jsonString)
    {
        string hashedRequestPayload = CreateRequestPayload(jsonString);

        string authorization = Sign(hashedRequestPayload, "PUT", canonicalUri, canonicalQueriString);
        string requestDate = DateTime.ParseExact(DateTime.UtcNow.ToString(), "YYYYMMDD'T'HHMMSS'Z'", CultureInfo.InvariantCulture).ToString();

        WebRequest webRequest = WebRequest.Create(canonicalUri + canonicalQueriString);

        webRequest.Method = "PUT";
        webRequest.ContentType = ContentType;
        webRequest.Headers.Add("X-Amz-date", requestDate);
        webRequest.Headers.Add("Authorization", authorization);
        webRequest.Headers.Add("x-amz-content-sha256", hashedRequestPayload);
        webRequest.ContentLength = jsonString.Length;

        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(jsonString);

        Stream newStream = webRequest.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        using (WebResponse response = webRequest.GetResponse())
        {
            StreamReader responseReader = new StreamReader(response.GetResponseStream());
            var responseJson = responseReader.ReadToEnd();
        }

        return webRequest;
    }

    const string RegionName = "eu-west-1"; //This is the regionName
    const string ServiceName = "execute-api";
    const string Algorithm = "AWS4-HMAC-SHA256";
    const string ContentType = "application/json";
    const string Host = "<hostname>";
    const string SignedHeaders = "content-type;host;x-amz-content-sha256;x-amz-date";

    private static string CreateRequestPayload(string jsonString)
    {
        //Here should be JSON object of the model we are sending with POST request
        //var jsonToSerialize = new { Data = String.Empty };

        //We parse empty string to the serializer if we are makeing GET request
        //string requestPayload = new JavaScriptSerializer().Serialize(jsonToSerialize);
        string hashedRequestPayload = HexEncode(Hash(ToBytes(jsonString)));

        return hashedRequestPayload;
    }

    private static string Sign(string hashedRequestPayload, string requestMethod, string canonicalUri, string canonicalQueryString)
    {
        var currentDateTime = DateTime.UtcNow;
        var accessKey = "";
        var secretKey = "";

        var dateStamp = currentDateTime.ToString("yyyyMMdd");
        //var requestDate = currentDateTime.ToString("YYYYMMDD'T'HHMMSS'Z");
        var requestDate = DateTime.ParseExact(currentDateTime.ToString(), "YYYYMMDD'T'HHMMSS'Z'", CultureInfo.InvariantCulture);
        var credentialScope = string.Format("{0}/{1}/{2}/aws4_request", dateStamp, RegionName, ServiceName);

        var headers = new SortedDictionary<string, string> {
        { "content-type", ContentType },
        { "host", Host  },
        { "x-amz-date", requestDate.ToString() }
    };

        string canonicalHeaders = string.Join("\n", headers.Select(x => x.Key.ToLowerInvariant() + ":" + x.Value.Trim())) + "\n";

        // Task 1: Create a Canonical Request For Signature Version 4
        string canonicalRequest = requestMethod + "\n" + canonicalUri + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\n" + SignedHeaders + "\n" + hashedRequestPayload;
        string hashedCanonicalRequest = HexEncode(Hash(ToBytes(canonicalRequest)));

        // Task 2: Create a String to Sign for Signature Version 4
        string stringToSign = Algorithm + "\n" + requestDate + "\n" + credentialScope + "\n" + hashedCanonicalRequest;

        // Task 3: Calculate the AWS Signature Version 4
        byte[] signingKey = GetSignatureKey(secretKey, dateStamp, RegionName, ServiceName);
        string signature = HexEncode(HmacSha256(stringToSign, signingKey));

        // Task 4: Prepare a signed request
        // Authorization: algorithm Credential=access key ID/credential scope, SignedHeadaers=SignedHeaders, Signature=signature

        string authorization = string.Format("{0} Credential={1}/{2}/{3}/{4}/aws4_request, SignedHeaders={5}, Signature={6}",
        Algorithm, accessKey, dateStamp, RegionName, ServiceName, SignedHeaders, signature);

        return authorization;
    }

    private static byte[] GetSignatureKey(string key, string dateStamp, string regionName, string serviceName)
    {
        byte[] kDate = HmacSha256(dateStamp, ToBytes("AWS4" + key));
        byte[] kRegion = HmacSha256(regionName, kDate);
        byte[] kService = HmacSha256(serviceName, kRegion);
        return HmacSha256("aws4_request", kService);
    }

    private static byte[] ToBytes(string str)
    {
        return Encoding.UTF8.GetBytes(str.ToCharArray());
    }

    private static string HexEncode(byte[] bytes)
    {
        return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
    }

    private static byte[] Hash(byte[] bytes)
    {
        return SHA256.Create().ComputeHash(bytes);
    }

    private static byte[] HmacSha256(string data, byte[] key)
    {
        return new HMACSHA256(key).ComputeHash(ToBytes(data));
    }


来源: stackexchange

问:
How do I implement a list comprehension using map and filter?
Both map and filter can be implemented using list comprehension:

```<code>map f xs    = [f x | x <- xs]
filter p xs = [x | x <- xs, p x]
</code>```

I'd like to show that the converse holds as well using the following example:

```<code>[expr | p <- s]
</code>```

I've got so far:

```<code>map (\p -> expr) s
</code>```

But this works only when pattern matching with p succeeds on all elements of s. In a way, I first want to filter s using a pattern matching on p. Naturally, I tried looking into this question but I haven't been able to find a solution which didn't use list comprehension or LambdaCase.

答:
Yes, you cannot do pattern matching on a lambda without either using \x -> case x of... (or LambdaCase to shorten it); your example:

[2*x | (x,2) <- [(1,2), (3,4)]]
```

<p>would have to be implemented as:</p>

<pre class="lang-hs prettyprint-override"><code>map (\(x,_) -> 2*x) $ filter (\(_,y) -> y == 2) [(1,2), (3,4)]
</code>```

Or, using LambdaCase:

map (\(x,_) -> 2*x) $ filter (\case (_,2) -> True; _ -> False) [(1,2), (3,4)]
```

<p>Also, for a point-free version:</p>

<pre class="lang-hs prettyprint-override"><code>map ((2*) . fst) $ filter ((==2) . snd) [(1,2), (3,4)]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Both map and filter can be implemented using list comprehension:

map f xs    = [f x | x <- xs]
filter p xs = [x | x <- xs, p x]

I'd like to show that the converse holds as well using the following example:

[expr | p <- s]

I've got so far:

map (\p -> expr) s

But this works only when pattern matching with p succeeds on all elements of s. In a way, I first want to filter s using a pattern matching on p. Naturally, I tried looking into this question but I haven't been able to find a solution which didn't use list comprehension or LambdaCase.

Body:
Yes, you cannot do pattern matching on a lambda without either using \x -> case x of... (or LambdaCase to shorten it); your example:

[2*x | (x,2) <- [(1,2), (3,4)]]

would have to be implemented as:

map (\(x,_) -> 2*x) $ filter (\(_,y) -> y == 2) [(1,2), (3,4)]

Or, using LambdaCase:

map (\(x,_) -> 2*x) $ filter (\case (_,2) -> True; _ -> False) [(1,2), (3,4)]

Also, for a point-free version:

map ((2*) . fst) $ filter ((==2) . snd) [(1,2), (3,4)]


问:
Regex for ignoring first and last character
Trying to obfuscate an email to this format:

```<code>a***@******m
</code>```

Meaning I need a regex to match everything except first and last character, as well as @.
I can use [^@] for everything but how do I ignore the last and first characters in a String? Anchors seem like the way to go but what is the exact syntax?

答:
How about using a lookahead:

```<code>(?!^|.$)[^@\s]
</code>```

See this demo at regex101

I also added white space to the characters that won't be replaced.

Body:
Trying to obfuscate an email to this format:

a***@******m

Meaning I need a regex to match everything except first and last character, as well as @.
I can use [^@] for everything but how do I ignore the last and first characters in a String? Anchors seem like the way to go but what is the exact syntax?

Body:
How about using a lookahead:

(?!^|.$)[^@\s]

See this demo at regex101

I also added white space to the characters that won't be replaced.


问:
How would I return all null values from a left join?
I am trying to left join two tables (A and B) together and would like to return all values that have a column in table B marked as null in mySQL.

The two tables I am joining are both very large and I am running into an issue where my connection will timeout after 6000 seconds due to the DBMS settings; is there a way to make this query run more efficiently?

Another bit of information: Even if I limit the query to 10 rows, it will still timeout and give me the error code listed below.

```<code>select *
from Table_A a
left join Table_B b
on a.field_X = b.field_X
where b.Field_X is null;
</code>```

I am experiencing the following error code: "Error Code 2013. Lost Connection to MySQL server during query."

Side note: I am a new SQL user and may need to ask for clarification on some answers. Thank you in advance!

答:
Try the other way around, and reduce your SELECT fields if you can:

```<code>select Table_B.Field_X
from Table_B b
left join Table_A a
on a.field_X = b.field_X
where a.Field_X is null;
</code>```

Let SQL do its work they way it likes to do it :)  To have a standard left join (where you are looking for rows that do NOT match on the right) is highly optimised if you have the correct indexes

Body:
I am trying to left join two tables (A and B) together and would like to return all values that have a column in table B marked as null in mySQL.

The two tables I am joining are both very large and I am running into an issue where my connection will timeout after 6000 seconds due to the DBMS settings; is there a way to make this query run more efficiently?

Another bit of information: Even if I limit the query to 10 rows, it will still timeout and give me the error code listed below.

select *
from Table_A a
left join Table_B b
on a.field_X = b.field_X
where b.Field_X is null;

I am experiencing the following error code: "Error Code 2013. Lost Connection to MySQL server during query."

Side note: I am a new SQL user and may need to ask for clarification on some answers. Thank you in advance!

Body:
Try the other way around, and reduce your SELECT fields if you can:

select Table_B.Field_X
from Table_B b
left join Table_A a
on a.field_X = b.field_X
where a.Field_X is null;

Let SQL do its work they way it likes to do it :)  To have a standard left join (where you are looking for rows that do NOT match on the right) is highly optimised if you have the correct indexes


问:
Screen scraping web page after delay
I'm trying to scrape a web page using C#, however after the page loads, it executes some JavaScript which loads more elements into the DOM which I need to scrape. A standard scraper simply grabs the html of the page on load and doesn't pick up the DOM changes made via JavaScript. How do I put in some sort of functionality to wait for a second or two and then grab the source?

Here is my current code:

private string ScrapeWebpage(string url, DateTime? updateDate)
{
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    Stream responseStream = null;
    StreamReader reader = null;
    string html = null;
    try
    {
        //create request (which supports http compression)
        request = (HttpWebRequest)WebRequest.Create(url);
        request.Pipelined = true;
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
        if (updateDate != null)
            request.IfModifiedSince = updateDate.Value;
        //get response.
        response = (HttpWebResponse)request.GetResponse();
        responseStream = response.GetResponseStream();
        if (response.ContentEncoding.ToLower().Contains("gzip"))
            responseStream = new GZipStream(responseStream,
                CompressionMode.Decompress);
        else if (response.ContentEncoding.ToLower().Contains("deflate"))
            responseStream = new DeflateStream(responseStream,
                CompressionMode.Decompress);
        //read html.
        reader = new StreamReader(responseStream, Encoding.Default);
        html = reader.ReadToEnd();
    }
    catch
    {
        throw;
    }
    finally
    {
        //dispose of objects.
        request = null;
        if (response != null)
        {
            response.Close();
            response = null;
        }
        if (responseStream != null)
        {
            responseStream.Close();
            responseStream.Dispose();
        }
        if (reader != null)
        {
            reader.Close();
            reader.Dispose();
        }
    }
    return html;
}
```

Here's a sample URL:

http://www.realtor.com/realestateandhomes-search/geneva_ny#listingType-any/pg-4

You'll see when the page first loads it says 134 listings found, then after a second it says 187 properties found.

答: You would need to execute the javascript yourself to get this functionality. Currently, your code only receives whatever the server replies with at the URL you request. The rest of the listings are "showing up" because the browser downloads, parses, and executes the accompanying javascript.</p>

Title: Screen scraping web page after delay

Body:
I'm trying to scrape a web page using C#, however after the page loads, it executes some JavaScript which loads more elements into the DOM which I need to scrape. A standard scraper simply grabs the html of the page on load and doesn't pick up the DOM changes made via JavaScript. How do I put in some sort of functionality to wait for a second or two and then grab the source?

Here is my current code:

private string ScrapeWebpage(string url, DateTime? updateDate)
{
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    Stream responseStream = null;
    StreamReader reader = null;
    string html = null;
    try
    {
        //create request (which supports http compression)
        request = (HttpWebRequest)WebRequest.Create(url);
        request.Pipelined = true;
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
        if (updateDate != null)
            request.IfModifiedSince = updateDate.Value;
        //get response.
        response = (HttpWebResponse)request.GetResponse();
        responseStream = response.GetResponseStream();
        if (response.ContentEncoding.ToLower().Contains("gzip"))
            responseStream = new GZipStream(responseStream,
                CompressionMode.Decompress);
        else if (response.ContentEncoding.ToLower().Contains("deflate"))
            responseStream = new DeflateStream(responseStream,
                CompressionMode.Decompress);
        //read html.
        reader = new StreamReader(responseStream, Encoding.Default);
        html = reader.ReadToEnd();
    }
    catch
    {
        throw;
    }
    finally
    {
        //dispose of objects.
        request = null;
        if (response != null)
        {
            response.Close();
            response = null;
        }
        if (responseStream != null)
        {
            responseStream.Close();
            responseStream.Dispose();
        }
        if (reader != null)
        {
            reader.Close();
            reader.Dispose();
        }
    }
    return html;
}

Here's a sample URL:

http://www.realtor.com/realestateandhomes-search/geneva_ny#listingType-any/pg-4

You'll see when the page first loads it says 134 listings found, then after a second it says 187 properties found.

ContentLicense: CC BY-SA 3.0


问:
How to convert this API get() result into JSON object?
API endpoint returning an observable. When I am trying to retrieve any property of the returned object, it is showing that the property does not exist on type {}

This is the endpoint result

```<code>{
  "base": "EUR",
  "date": "2018-04-08",
  "rates": {
    "CAD": 1.565,
    "CHF": 1.1798,
    "GBP": 0.87295,
    "SEK": 10.2983,
    "EUR": 1.092,
    "USD": 1.2234,
  }
}
</code>```

service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ConvertResultModel } from './converter/convert-result-model';

@Injectable({
  providedIn: 'root'
})
export class ServiceProviderService {
  private baseUrl = 'https://api.exchangeratesapi.io/latest';
  constructor(private http: HttpClient) { }
  getLatest():Observable<ConvertResultModel>{
    return this.http.get<ConvertResultModel>(this.baseUrl);
  }
}
</code>```

converter.component.ts

```<code>import { ServiceProviderService } from './../service-provider.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-converter',
  templateUrl: './converter.component.html',
  styleUrls: ['./converter.component.css']
})
export class ConverterComponent implements OnInit {

  constructor(private serviceProvider: ServiceProviderService) { }
  private resultSet = {};
  ngOnInit()
  {
    this.serviceProvider.getLatest().subscribe(data => this.resultSet = data);
    console.log(this.resultSet.base);
  }
}
</code>```

convert-result-model.ts

```<code>export interface ConvertResultModel {
  base: number;
  date: string;
  rates: any[];
}
</code>```

ERROR in src/app/converter/converter.component.ts(17,32): error TS2339: Property 'base' does not exist on type '{}'.

答:
Its all about type checking in typescript. Which is something good but sometimes you don't want to define type of everything.

So you may want to replace

```<code>private resultSet = {};
</code>```

With something like

```<code>private resultSet:any = {};
// or
//private resultSet:any = null;
</code>```

Or define a class or interface and set type of resultSet to that class or interface. Something like:

```<code>public interface ResultSet{
  base: String;
  // etc
}
</code>```

and then

```<code>private resultSet:ResultSet= {} as ResultSet;
// or
//private resultSet:ResultSet= null;
</code>```

But my suggestion is try to practice using power of typescript which helps you catch some errors in compile time instead of runtime

Body:
API endpoint returning an observable. When I am trying to retrieve any property of the returned object, it is showing that the property does not exist on type {}

This is the endpoint result

{
  "base": "EUR",
  "date": "2018-04-08",
  "rates": {
    "CAD": 1.565,
    "CHF": 1.1798,
    "GBP": 0.87295,
    "SEK": 10.2983,
    "EUR": 1.092,
    "USD": 1.2234,
  }
}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ConvertResultModel } from './converter/convert-result-model';

@Injectable({
  providedIn: 'root'
})
export class ServiceProviderService {
  private baseUrl = 'https://api.exchangeratesapi.io/latest';
  constructor(private http: HttpClient) { }
  getLatest():Observable<ConvertResultModel>{
    return this.http.get<ConvertResultModel>(this.baseUrl);
  }
}

converter.component.ts

import { ServiceProviderService } from './../service-provider.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-converter',
  templateUrl: './converter.component.html',
  styleUrls: ['./converter.component.css']
})
export class ConverterComponent implements OnInit {

  constructor(private serviceProvider: ServiceProviderService) { }
  private resultSet = {};
  ngOnInit()
  {
    this.serviceProvider.getLatest().subscribe(data => this.resultSet = data);
    console.log(this.resultSet.base);
  }
}

convert-result-model.ts

export interface ConvertResultModel {
  base: number;
  date: string;
  rates: any[];
}

ERROR in src/app/converter/converter.component.ts(17,32): error TS2339: Property 'base' does not exist on type '{}'.

Body:
Its all about type checking in typescript. Which is something good but sometimes you don't want to define type of everything.

So you may want to replace

private resultSet = {};

With something like

private resultSet:any = {};
// or
//private resultSet:any = null;

Or define a class or interface and set type of resultSet to that class or interface. Something like:

public interface ResultSet{
  base: String;
  // etc
}

and then

private resultSet:ResultSet= {} as ResultSet;
// or
//private resultSet:ResultSet= null;

But my suggestion is try to practice using power of typescript which helps you catch some errors in compile time instead of runtime


答:
If the tool or language you use supports lookarounds, you can use:

```<code>(?<!^)[^@](?!$)
</code>```

Demo: https://regex101.com/r/5Tbaq7/1

Title: Regex for ignoring first and last character

Body:
If the tool or language you use supports lookarounds, you can use:

(?<!^)[^@](?!$)

Demo: https://regex101.com/r/5Tbaq7/1


问:
Why is my powershell DSC failing with the message "An item with the same key has already been added"
We have a powershell DSC that is being executed to bring a vmss to a desired state.
It was working until we added some more parameters, and then it broke.

I removed everything except the parameters from the script and it still doesn't work.
The full error is

The DSC Extension received an incorrect input: An error occurred while
  executing script or module 'IISInstall.ps1':  An item with the same
  key has already been added..

Please correct the input and retry executing the extension.

We even added logging in the DSC to try to troubleshoot.
It doesn't even seem to make it into the body of the DSC.

What am I doing wrong?

答:
The parameter was called $instanceName. We wanted to use it to add a custom header to IIS to track which instance a response came from.

Turns out if you use $instanceName that steps on the internals of DSC in some way and it will never deploy correctly!

As soon as you remove $instanceName from the parameter list, it will work.


问:
Group data based on unique ID and then pasting it onto the same row
I have a subset of my data :

```<code>a3 <- structure(list(Employee.Number = c("10034", "10034", "10034"),
               Employee.Full.Name = c("Wayne, Bruce", "Wayne, Bruce",
                                      "Wayne, Bruce"), Case.No = c("78582", "87758", "87758"),
               Diagnoses.No = c("1", "2", "1"), Diagnosis.Medical.Code.Code = c("151.9",
                                                                                "285.9", "V70-V82"), Diagnosis.Medical.Code.Description = c("Stomach, unspecified",
                                                                                "Anemia, unspecified", "Tummy AChe"
                                                                                )), row.names = c(NA, -3L), class = "data.frame")

</code>```

How would I go about grouping the Case.No and if the "Diagnoses.No" equals 2 (the actual data has numbers >2), then the last 3 columns will be pasted onto the column of the same Case.no with the Diagnoses.No with 1 with the original column removed?

Desired results:

```<code>
10034  Wayne, Bruce  78582  1  151.9    Stomach, unspecified   NA

10034  Wayne, Bruce  87758  1  V70-V82  Tummy AChe 2  285.9    Anemia, unspecified
</code>```

答:
If I understand correctly, the OP wants to reshape multiple value columns from long to wide format.

One possible approach is to use the reshape() function in base R:

```<code>reshape(a3, v.names = c("Diag.MC.Code", "Diag.MC.Descr"), timevar = "Diag.No",
        idvar = c("Emp.No", "Emp.Full.Name", "Case.No"), direction = "wide")
</code>```

```<code>  Emp.No Emp.Full.Name Case.No Diag.MC.Code.1      Diag.MC.Descr.1 Diag.MC.Code.2     Diag.MC.Descr.2
1  10034  Wayne, Bruce   78582          151.9 Stomach, unspecified           <NA>                <NA>
2  10034  Wayne, Bruce   87758        V70-V82           Tummy AChe          285.9 Anemia, unspecified
</code>```

Please, note that column names have been renamed (shortened) to make the result table fit on the page.

Data

```<code>a3 <- structure(list(Emp.No = c("10034", "10034", "10034"), Emp.Full.Name = c("Wayne, Bruce",
"Wayne, Bruce", "Wayne, Bruce"), Case.No = c("78582", "87758",
"87758"), Diag.No = c("1", "2", "1"), Diag.MC.Code = c("151.9",
"285.9", "V70-V82"), Diag.MC.Descr = c("Stomach, unspecified",
"Anemia, unspecified", "Tummy AChe")), row.names = c(NA, -3L), class = "data.frame")

# abbreviate column names to make result table fit on page
a3 <- setNames(a3, c("Emp.No", "Emp.Full.Name", "Case.No", "Diag.No",
                     "Diag.MC.Code", "Diag.MC.Descr"))
</code>```

Body:
I have a subset of my data :

a3 <- structure(list(Employee.Number = c("10034", "10034", "10034"),
               Employee.Full.Name = c("Wayne, Bruce", "Wayne, Bruce",
                                      "Wayne, Bruce"), Case.No = c("78582", "87758", "87758"),
               Diagnoses.No = c("1", "2", "1"), Diagnosis.Medical.Code.Code = c("151.9",
                                                                                "285.9", "V70-V82"), Diagnosis.Medical.Code.Description = c("Stomach, unspecified",
                                                                                "Anemia, unspecified", "Tummy AChe"
                                                                                )), row.names = c(NA, -3L), class = "data.frame")

How would I go about grouping the Case.No and if the "Diagnoses.No" equals 2 (the actual data has numbers >2), then the last 3 columns will be pasted onto the column of the same Case.no with the Diagnoses.No with 1 with the original column removed?

Desired results:

10034  Wayne, Bruce  78582  1  151.9    Stomach, unspecified   NA

10034  Wayne, Bruce  87758  1  V70-V82  Tummy AChe 2  285.9    Anemia, unspecified

Body:
If I understand correctly, the OP wants to reshape multiple value columns from long to wide format.

One possible approach is to use the reshape() function in base R:

reshape(a3, v.names = c("Diag.MC.Code", "Diag.MC.Descr"), timevar = "Diag.No",
        idvar = c("Emp.No", "Emp.Full.Name", "Case.No"), direction = "wide")

  Emp.No Emp.Full.Name Case.No Diag.MC.Code.1      Diag.MC.Descr.1 Diag.MC.Code.2     Diag.MC.Descr.2
1  10034  Wayne, Bruce   78582          151.9 Stomach, unspecified           <NA>                <NA>
2  10034  Wayne, Bruce   87758        V70-V82           Tummy AChe          285.9 Anemia, unspecified

Please, note that column names have been renamed (shortened) to make the result table fit on the page.

Data

a3 <- structure(list(Emp.No = c("10034", "10034", "10034"), Emp.Full.Name = c("Wayne, Bruce",
"Wayne, Bruce", "Wayne, Bruce"), Case.No = c("78582", "87758",
"87758"), Diag.No = c("1", "2", "1"), Diag.MC.Code = c("151.9",
"285.9", "V70-V82"), Diag.MC.Descr = c("Stomach, unspecified",
"Anemia, unspecified", "Tummy AChe")), row.names = c(NA, -3L), class = "data.frame")

# abbreviate column names to make result table fit on page
a3 <- setNames(a3, c("Emp.No", "Emp.Full.Name", "Case.No", "Diag.No",
                     "Diag.MC.Code", "Diag.MC.Descr"))


问:
Alexa responding before data is returned
I'm new to promises, async/await, and Alexa/lambda so bear with me.

My function is returning prior to the data being returned. I had a similar issue where I was getting an error, but have since edited my function quite a bit and therefore asking a new question. I'm now no longer getting an error, but instead my data is being returned first, then the promise is executing.

I've tried re-writing the promise/function after reading many, many SO, google, and amazon developer forums. Nothing seems to be working for me.

```<code>const IntentRequest = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest';
    },
    async handle(handlerInput) {
        const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
        let responseData, promise;

         checkAuthenticationStatus(handlerInput,function(json){
            console.log('waited!')
            if(json.error) {
                return handlerInput.responseBuilder.speak(messages.NO_ACCESS).withSimpleCard('Unauthorized Request', messages.NO_ACCESS).getResponse();
            } else if(json.noerror && json.noerror.okay == 'true'){
                console.log('starting to get intent data')
                const url = new URL(json.noerror.okay.path);
                promise = new Promise((resolve, reject) => {
                    console.log('start promise')
                   return httpsGetIntent(handlerInput, url).then((resultData) => {
                        console.log(resultData)
                        responseData = resultData;
                        resolve(responseData)
                        console.log('inside promise, no error, prior to return data')
                    })

            }).then((result) => { console.log('result', result)})
                return handlerInput.responseBuilder.speak('Test').getResponse();
            }

        });
        console.log('response data', responseData)

        let result = await promise;
        return result;

    },
};
</code>```

Out of my many console.logs() added for debugging, they print as follows:
- 'response data'
- 'waited!'
- 'starting to get intent data'
- 'start promise'
- resultData
- 'inside promise, no error, prior to return data'

答:
Almost_Ashleigh, based on your own answer, some ideas in which I have :

made the assumption that httpsGetIntent() returns a Promsie that delivers resultData.

promisified checkAuthenticationStatus() by writing the adaptor checkAuthenticationStatusAsync().

consolidated the .speak() commands into  final .then() and .catch() clauses.

allowed specific errors to be tailored by decorating with a .title property, which is used in the final .catch() as a cardTitle. Any undecorated errors will default to 'Sorry' (or whatever you want).

```<code>// in a suitable scope ...
function checkAuthenticationStatusAsync(handlerInput) {
    return new Promise((resolve, reject) {
        checkAuthenticationStatus(handlerInput, (json) => {
            if (json.error || !json.noerror || json.noerror.okay !== 'true') {
                let err = new Error(messages.NO_ACCESS); // or maybe a separate error message per error case?
                err.title = 'Unauthorized Request';
                reject(err);
            } else {
                resolve(json);
            }
        });
    });
}

// ... and ...
const IntentRequest = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest';
    },
    handle(handlerInput) {
        return checkAuthenticationStatusAsync(handlerInput)
        .then((json) => httpsGetIntent(handlerInput, new URL(json.noerror.okay.path)))
        .then((resultData) => {
            if (resultData) {
                // success path ends here
                return handlerInput.responseBuilder.speak(resultData.response.outputSpeech.text).getResponse();
            } else {
                throw new Error('No result data returned'); // throws to the .catch() below
            }
        })
        .catch(err => {
            // all errors end up here.
            return handlerInput.responseBuilder.speak(err.message).withSimpleCard(err.title || 'Sorry', err.message).getResponse();
            throw err; // to keep handle's caller informed
        });
    },
};
</code>```

Note, this is a way, not necessarily the way, to write the code. Please feel free to raid for ideas.

Body:
I'm new to promises, async/await, and Alexa/lambda so bear with me.

My function is returning prior to the data being returned. I had a similar issue where I was getting an error, but have since edited my function quite a bit and therefore asking a new question. I'm now no longer getting an error, but instead my data is being returned first, then the promise is executing.

I've tried re-writing the promise/function after reading many, many SO, google, and amazon developer forums. Nothing seems to be working for me.

const IntentRequest = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest';
    },
    async handle(handlerInput) {
        const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
        let responseData, promise;

         checkAuthenticationStatus(handlerInput,function(json){
            console.log('waited!')
            if(json.error) {
                return handlerInput.responseBuilder.speak(messages.NO_ACCESS).withSimpleCard('Unauthorized Request', messages.NO_ACCESS).getResponse();
            } else if(json.noerror && json.noerror.okay == 'true'){
                console.log('starting to get intent data')
                const url = new URL(json.noerror.okay.path);
                promise = new Promise((resolve, reject) => {
                    console.log('start promise')
                   return httpsGetIntent(handlerInput, url).then((resultData) => {
                        console.log(resultData)
                        responseData = resultData;
                        resolve(responseData)
                        console.log('inside promise, no error, prior to return data')
                    })

            }).then((result) => { console.log('result', result)})
                return handlerInput.responseBuilder.speak('Test').getResponse();
            }

        });
        console.log('response data', responseData)

        let result = await promise;
        return result;

    },
};

Out of my many console.logs() added for debugging, they print as follows:
- 'response data'
- 'waited!'
- 'starting to get intent data'
- 'start promise'
- resultData
- 'inside promise, no error, prior to return data'

Body:
Almost_Ashleigh, based on your own answer, some ideas in which I have :

made the assumption that httpsGetIntent() returns a Promsie that delivers resultData.

promisified checkAuthenticationStatus() by writing the adaptor checkAuthenticationStatusAsync().

consolidated the .speak() commands into  final .then() and .catch() clauses.

allowed specific errors to be tailored by decorating with a .title property, which is used in the final .catch() as a cardTitle. Any undecorated errors will default to 'Sorry' (or whatever you want).

// in a suitable scope ...
function checkAuthenticationStatusAsync(handlerInput) {
    return new Promise((resolve, reject) {
        checkAuthenticationStatus(handlerInput, (json) => {
            if (json.error || !json.noerror || json.noerror.okay !== 'true') {
                let err = new Error(messages.NO_ACCESS); // or maybe a separate error message per error case?
                err.title = 'Unauthorized Request';
                reject(err);
            } else {
                resolve(json);
            }
        });
    });
}

// ... and ...
const IntentRequest = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest';
    },
    handle(handlerInput) {
        return checkAuthenticationStatusAsync(handlerInput)
        .then((json) => httpsGetIntent(handlerInput, new URL(json.noerror.okay.path)))
        .then((resultData) => {
            if (resultData) {
                // success path ends here
                return handlerInput.responseBuilder.speak(resultData.response.outputSpeech.text).getResponse();
            } else {
                throw new Error('No result data returned'); // throws to the .catch() below
            }
        })
        .catch(err => {
            // all errors end up here.
            return handlerInput.responseBuilder.speak(err.message).withSimpleCard(err.title || 'Sorry', err.message).getResponse();
            throw err; // to keep handle's caller informed
        });
    },
};

Note, this is a way, not necessarily the way, to write the code. Please feel free to raid for ideas.


问:
What is the correct way to pass data to a running thread
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

```<code>C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?
</code>```

So what is the correct way to pass data to a running thread in C# and Java?

答:
Well, it depends a lot on the work that the thread is supposed to do.
For example, you can have a thread waiting for a Event (e.g. ManualResetEvent) and a shared queue where you put work items (can be data structures to be processed, or more clever commands following a Command pattern). Somebody adds new work to the queue ad signals the event, so the trhread awakes, gets work from the queue and start performing its task.

You can encapsulate this code inside a custom queue, where any thread that calls the Deque methods stops until somebody calls Add(item).

On the other hand, maybe you want to rely on .NET ThreadPool class to issue tasks to execute by the threads on the pool.

Does this example help a bit?

Body:
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?

So what is the correct way to pass data to a running thread in C# and Java?


问:
Needing help debugging
I'm creating my program on w3school which it does not provide any debugging tools at all, I basically finished my project on there but later found out I had 80+ errors that needs fixing which I'm given super generic answers so I can't seem to figure out what exactly the issue is. I'm a super newbie at HTML and unlike java where eclipse at least tells you where exactly the error is at and gives you a little better info I have no idea what the errors mean. I am also using w3school file upload method to debug my program. Also my program is basically just a tv schedule having the days, time, and each shows broken down

I've tried googling some answers but its not really helping

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<title>Tv Schedule</title>
</head>
<body>

 <table>
 <table cellpadding="0" cellspacing="0"/>
<thead>
    <tr>
        <th style="background-color:white">
        <th style="background-color:black;color:white">Monday</th>
        <th style="background-color:black;color:white">Tuesday</th>
        <th style="background-color:black;color:white">Wednesday</th>
        <th style="background-color:black;color:white">Thursday</th>
        <th style="background-color:black;color:white">Friday</th>
        <th style="background-color:black;color:white">Saturday</th>
        <th style="background-color:black;color:white">Sunday</th>
    </tr>
    </thead>
<tbody>
    <tr>
        <th>12:00pm</th>
        <th rowspan="4" style="background-color:purple">Ben & Jerry's show</th>
        <th rowspan="2" style="background-color:yellow">The Happy Mile</th>
        <th rowspan="3" colspan="3" style="background-color:teal">That Yesterday Show</th>
        <th rowspan="4" style="background-color:lime">Let them Running Cat</th>
        <th rowspan="4" style="background-color:red">Run Talk</th>
    </tr>
    <tr>
        <th style="background-color:white;color:white">12:30pm</th>
        </tr>
    <tr>
    <th>1:00pm</th>
        <th rowspan="2" style="background-color:green">The Laptop Conspiracy</th>
      <tr>
        <th style="background-color:white;color:white">1:30pm</th>
        <th rowspan="3" colspan="2" style="background-color:tan">Cat Street</th>
        <th style="background-color:royalblue">Slept News</th>
    </tr>
    <tr>
         <th>2:00pm</th>
        <th rowspan="2" colspan="2" style="background-color:Turquoise">Slept</th>
        <th rowspan="2" colspan="3" style="background-color:RosyBrown">Adultsnado 4</th>
    </tr>
    <tr>
        <th style="background-color:white;color:white">2:30pm</th>
    </tr>
    <tr>
        <th>3:00pm</th>
        <th colspan="5" style="background-color:SandyBrown">Citizen Yang</th>
        <th rowspan="3" style="background-color:aqua">Slept</th>
        <th rowspan="5" style="background-color:burlywood">Computer Wars</th>
    </tr>
    <tr>
        <th style="background-color:white;color:white">3:30pm</th>
        <th rowspan="2" style="background-color:lightsteelblue">Lionnado 4</th>
        <th rowspan="3" colspan="2" style="background-color:Olive">Citizen Moong</th>
       <th rowspan="2" colspan="2" style="background-color:Moccasin ">Dr. LongestRun</th>
    </tr>
    <tr>
        <th>4:00pm</th>
    </tr>
    <tr>
        <th style="background-color:white;color:white">4:30pm</th>
        <th rowspan="2" style="background-color:linen">The N/A part II</th>
        <th style="background-color:cornsilk">Back to the Season</th>
        <th colspan="2" style="background-color:MediumSpringGreen">Running Year</th>
    </tr>
    <tr>
        <th>5:00pm</th>
        <th rowspan="3" style="background-color:MediumOrchid ">WWII Battle Obsession</th>
        <th colspan="4" style="background-color:lightyellow">The Fat Running Theory</th>
    </tr>
    <tr>
        <th style="background-color:white;color:white">5:30pm</th>
        <th rowspan="2" style="background-color:indianred">Rebel without a computer</th>
        <th colspan="2" style="background-color:limegreen">Fighting Tomorrow</th>
        <th colspan="3" style="background-color:gold">Episode XVI - The Laptop Run</th>
    </tr>
    <tr>
        <th>6:00pm</th>
        <th style="background-color:mistyrose">Spam TV</th>
        <th colspan="3" style="background-color:indianred">The Lion</th>
        <th style="background-color:mintcream">Running Yer</th>
    </tr>
    <tr>
        <th style="background-color:white;color:white">6:30pm</th>
        <th rowspan="3" colspan="5" style="background-color:honeydew">Give God Money</th>
        <th rowspan="5" colspan="2" style="background-color:Fuchsia">Skinny Karaoke</th>
    </tr>
    <tr>
        <th>7:00pm</th>
    </tr>
    <tr>
        <th style="background-color:white;color:white">7:30pm</th>
    </tr>
    <tr>
        <th>8:00pm</th>
        <th rowspan="4" style="background-color:lavender">Eye of Thailand</th>
        <th style="background-color:orange">Slept News</th>
        <th style="background-color:orchid">Happy gossip</th>
    </tr>
    <tr>
        <th style="background-color:white;color:white">8:30pm</th>
        <th rowspan="3" colspan="2" style="background-color:DarkKhaki">Skinny Today</th>
        <th style="background-color:orange">Slept News</th>
        <th style="background-color:orchid">Happy gossip</th>
    </tr>
    <tr>
        <th>9:00pm</th>
        <th rowspan="2" colspan="3" style="background-color:Aquamarine">Soon Slept</th>
        <th rowspan="5" style="background-color:brown">America's Got Laptop</th>
    </tr>
    <tr>
        <th style="background-color:white;color:white">9:30pm</th>
    </tr>
    <tr>
        <th>10:00pm</th>
        <th rowspan="3" colspan="5" style="background-color:chocolate">Don't run there</th>
        <th  rowspan="3" style="background-color:violet">North Fillory Fighting
    </tr>
    <tr>
        <th style="background-color:white;color:white">10:30pm</th>
    </tr>
    <tr>
        <th>11:00pm</th>
    </tr>
        <th style="background-color:white;color:white">11:30pm</th>
        <th colspan="2" style="background-color:crimson">Captain Zeloous and Adult lads</th>
        <th style="background-color:yellowgreen">Grand Theft Computer</th>
        <th style="background-color:gray">Zealous Rerun</th>
        <th colspan="3" style="background-color:dodgerblue">Pay-Per-Download</th>
    </tr>
</tbody>
</code>```

I only get these types of errors,
-document type does not allow element "table" here

-document type does not allow element "th" here

答:
You are missing the head and body tags. You need those for valid html. Your table must be contained in the body tag.

```<code><html>
    <head>
    </head>
    <body>
        <table>
            <!--All your table stuff-->
        </table>
    </body>
</html>
</code>```

Also make sure you have all your closing tags. I noticed some missing 	 tags.

UPDATE: The xmlns attribute is required in XHTML, which you are using. You need to add said attribute to your html tag:

```<code><html xmlns="http://www.w3.org/1999/xhtml">
    <!--head,body,etc-->
</html>
</code>```

This can be found on w3Schools

The source of most of the problems you're facing is missing tags. When writing in any markup or programming language, make sure you have the same number of opening tags/braces/groupings as you do closing groupings at the same time as you go along. This problem can otherwise be harder to spot in code and can have some of the worst results.

Title: Needing help debugging

Body:
I'm creating my program on w3school which it does not provide any debugging tools at all, I basically finished my project on there but later found out I had 80+ errors that needs fixing which I'm given super generic answers so I can't seem to figure out what exactly the issue is. I'm a super newbie at HTML and unlike java where eclipse at least tells you where exactly the error is at and gives you a little better info I have no idea what the errors mean. I am also using w3school file upload method to debug my program. Also my program is basically just a tv schedule having the days, time, and each shows broken down

I've tried googling some answers but its not really helping

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Tv Schedule</title>

        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday
        Sunday

        12:00pm
        Ben & Jerry's show
        The Happy Mile
        That Yesterday Show
        Let them Running Cat
        Run Talk

        12:30pm

    1:00pm
        The Laptop Conspiracy

        1:30pm
        Cat Street
        Slept News

         2:00pm
        Slept
        Adultsnado 4

        2:30pm

        3:00pm
        Citizen Yang
        Slept
        Computer Wars

        3:30pm
        Lionnado 4
        Citizen Moong
       Dr. LongestRun

        4:00pm

        4:30pm
        The N/A part II
        Back to the Season
        Running Year

        5:00pm
        WWII Battle Obsession
        The Fat Running Theory

        5:30pm
        Rebel without a computer
        Fighting Tomorrow
        Episode XVI - The Laptop Run

        6:00pm
        Spam TV
        The Lion
        Running Yer

        6:30pm
        Give God Money
        Skinny Karaoke

        7:00pm

        7:30pm

        8:00pm
        Eye of Thailand
        Slept News
        Happy gossip

        8:30pm
        Skinny Today
        Slept News
        Happy gossip

        9:00pm
        Soon Slept
        America's Got Laptop

        9:30pm

        10:00pm
        Don't run there
        North Fillory Fighting

        10:30pm

        11:00pm

        11:30pm
        Captain Zeloous and Adult lads
        Grand Theft Computer
        Zealous Rerun
        Pay-Per-Download

I only get these types of errors,
-document type does not allow element "table" here

-document type does not allow element "th" here

Body:
You are missing the head and body tags. You need those for valid html. Your table must be contained in the body tag.

<html>
    <head>
    </head>
    <body>
        <table>
            <!--All your table stuff-->
        </table>
    </body>
</html>

Also make sure you have all your closing tags. I noticed some missing </th> tags.

UPDATE: The xmlns attribute is required in XHTML, which you are using. You need to add said attribute to your html tag:

<html xmlns="http://www.w3.org/1999/xhtml">
    <!--head,body,etc-->
</html>

This can be found on w3Schools

The source of most of the problems you're facing is missing tags. When writing in any markup or programming language, make sure you have the same number of opening tags/braces/groupings as you do closing groupings at the same time as you go along. This problem can otherwise be harder to spot in code and can have some of the worst results.


问:
How to manage endless variations of a question with LUIS?
The bot will ask the following:

-"How many people will stay in the apartment? And how many rooms do the apartment have?"

If the user replies the following:

-"3 people will stay in my 2 bedroom apartment."

Then it´s easy to extract the information I need by the use of 1 Simple Entity with 2 Roles (AmountOfPeople and RoomsInApartment).

However, the user can reply to the questions in many different ways. For e.g:

-"3 people and one dog will stay in my 2 bedroom apartment."

Or

-"3 people will stay in my friend´s 2 bedroom cottage."

Or

-"3 people will not stay in my 2 bedroom apartment."

In these cases there are so much more information that needs to be taken into account. I just care about how many people will stay, which animals will stay is just noise. And if they will stay in their friend´s place I need to extract that info so I can take some action in my bot. The problem is that there are endless of variations of how the user can reply to the bot´s question in this situation.

I have gone through all the LUIS documentation on Microsofts site, however it only covers very simple utterances, so I dont find much guidance there.

I have made my best try to put this up in LUIS. See the pictures below (Here I use 1 Simple Enttiy and 7 Roles).

i´m not sure if this is the correct approach? I´m I really supposed to label every word with a enttiy as I am doing?

答:
A couple of suggestions:

No you do not need to label every word in an utterance with an entity. You should only label the significant parts such as the number of people, how many rooms there are, and the accommodation type. From these you an infer and relay to the user information e.g. if you're using Accomodation:AmountPersons then you know you're talking about people, so you only need to extract the number, not the subject and action.

Investigate patterns to simplify your variations.

Start simple then build on what you have later:

I don't know if in your scenario that additional "beings" such as pets is critical but I would start by stripping it right back to only supporting the base scenario - which is people staying.

Is the room type critical for your scenario? Presumably people are booking a room rather than sleeping on a couch. ;-) Again I would just go with accomodation type (apartment, cottage etc).

Break up your bot's question into two parts - first ask how many people are staying, then where they are staying. This will make your life easier in terms of adding utterances and patterns, again you can build on this functionality later if you want to support users entering one line.

I'm not sure if LUIS alone is the best tool for this, the Bot Framework supports dialogs and waterfall dialogs seem perfect for what you want. There is a sample project available in C# and NodeJS which should give you something to build from.


问:
Can not integrate my app with a text editor in django
Although I have tried several richtext editors like tinymce, but I am not being able to make it work, no error appears, the page loads normally, a field appears to be filled, but without any editing option.

Try to use several ways I could find in google, but none was able to help me

```<code>----base.html

<head>
...

<!-- Tinymce Text-Editor (Must be in Head Tag) -->
  <script src="{% static '/tinymce/js/tinymce/tinymce.min.js' %}"></script>
  <script type="text/javascript" src="{% static 'js/custom.js' %}" ></script>
...

</head>
</code>```

```<code>---post_form.html

{% extends "blog/base.html" %}
<!-- {% load crispy_forms_tags %} -->
{% block content %}
    <div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Blog Post</legend>
                <!-- {{ form|crispy }} -->
                {{ form.as_p }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Post</button>
            </div>
        </form>
    </div>
{% endblock content %}
</code>```

```<code>---- models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from simple_history.models import HistoricalRecords
from tinymce.models import HTMLField

class Post(models.Model):
    title = models.CharField(max_length = 100)
    versao = models.CharField(max_length=10, default=1)
    # content = models.TextField()
    content = HTMLField()
    resumo_das_mudancas = models.TextField(default='Não houve mudanças')
    date_posted = models.DateTimeField(default = timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs ={'pk':self.pk})

.....

</code>```

```<code>------settings.py

...

INSTALLED_APPS = [
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'django.contrib.contenttypes',
    'django.contrib.auth',
    'django.contrib.flatpages',
    'simple_history',
    'blog.apps.BlogConfig',
    'users.apps.UsersConfig',
    'django.contrib.admin',
    'django.contrib.sessions',
    'django.contrib.messages',
    'crispy_forms',
    'storages',
    'tinymce',
    ]

</code>```

There are no error messages, it just does not wor, can you help me?

答:
Django CKEditor works very well for me. Here's an example what I had to do:

requirements.txt

```<code>django-ckeditor==5.6.1
</code>```

settings.py

```<code>INSTALLED_APPS = [
   ...
   'ckeditor'
]

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Custom',
        'toolbar_Custom': [
            ['Bold', 'Italic', 'Underline'],
            ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
            ['Link', 'Unlink'],
            ['RemoveFormat', 'Source']
        ],
        'height': 300,
        'width': 600
    }
}
</code>```

models.py

```<code>class ExampleModel(models.Model):
    ....
    example_field = models.TextField(null=True, blank=True)
</code>```

admin.py

```<code>from ckeditor.widgets import CKEditorWidget

class ExampleForm(forms.ModelForm):
    class Meta:
        model = ExampleModel
        fields = '__all__'
        widgets = {'example_field': CKEditorWidget()}

class ExampleAdmin(admin.ModelAdmin):
    form = ExampleForm
</code>```

Body:
Although I have tried several richtext editors like tinymce, but I am not being able to make it work, no error appears, the page loads normally, a field appears to be filled, but without any editing option.

Try to use several ways I could find in google, but none was able to help me

----base.html

...

...

---post_form.html

{% extends "blog/base.html" %}

{% block content %}

        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Blog Post</legend>

                {{ form.as_p }}
            </fieldset>

                <button class="btn btn-outline-info" type="submit">Post</button>

        </form>

{% endblock content %}

---- models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from simple_history.models import HistoricalRecords
from tinymce.models import HTMLField

class Post(models.Model):
    title = models.CharField(max_length = 100)
    versao = models.CharField(max_length=10, default=1)
    # content = models.TextField()
    content = HTMLField()
    resumo_das_mudancas = models.TextField(default='Não houve mudanças')
    date_posted = models.DateTimeField(default = timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs ={'pk':self.pk})

.....

------settings.py

...

INSTALLED_APPS = [
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'django.contrib.contenttypes',
    'django.contrib.auth',
    'django.contrib.flatpages',
    'simple_history',
    'blog.apps.BlogConfig',
    'users.apps.UsersConfig',
    'django.contrib.admin',
    'django.contrib.sessions',
    'django.contrib.messages',
    'crispy_forms',
    'storages',
    'tinymce',
    ]

There are no error messages, it just does not wor, can you help me?

Body:
Django CKEditor works very well for me. Here's an example what I had to do:

requirements.txt

django-ckeditor==5.6.1

settings.py

INSTALLED_APPS = [
   ...
   'ckeditor'
]

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Custom',
        'toolbar_Custom': [
            ['Bold', 'Italic', 'Underline'],
            ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
            ['Link', 'Unlink'],
            ['RemoveFormat', 'Source']
        ],
        'height': 300,
        'width': 600
    }
}

models.py

class ExampleModel(models.Model):
    ....
    example_field = models.TextField(null=True, blank=True)

admin.py

from ckeditor.widgets import CKEditorWidget

class ExampleForm(forms.ModelForm):
    class Meta:
        model = ExampleModel
        fields = '__all__'
        widgets = {'example_field': CKEditorWidget()}

class ExampleAdmin(admin.ModelAdmin):
    form = ExampleForm


问:
merge same keys data into one map with unique keys elixir
I have this json

```<code>[
  %{
    "159.69.136.31" => [
      %{"2015" => ["4"]},
      %{"2016" => []},
      %{"2017" => ["9"]},
      %{"2018" => []},
      %{"2019" => ["05"]}
    ]
  },
  %{
    "94.130.139.38" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => ["5", "8"]},
      %{"2019" => []}
    ]
  },
  %{
    "94.130.217.56" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => []},
      %{"2019" => []}
    ]
  }
]
</code>```

and I want to make it something like

```<code>[
  %{"2015" => ["4"]},
  %{"2016" => []},
  %{"2017" => ["9"]},
  %{"2018" => ["5", "8"]},
  %{"2019" => ["05"]}
]
</code>```

Basically, it's merging the same year's keys and the data available on the map. I have tried this solution with different approaches but it didn't work Elixir: Merge list with same map keys to one map

Update: years and IPs are constant
Update little bit more info about this..

```<code>years = ["2015", "2016", "2017", "2018", "2019"]
servers = [@seaweedfs_new, @seaweedfs_old, @seaweedfs_oldest]

  Enum.map(servers, fn server ->
    type = seaweefs_type(server)
    attribute = seaweedfs_attribute(server)
    url = "http://" <> server <> ":8888" <> "/#{camera.exid}/snapshots/recordings/"
    year_values =
      Enum.map(years, fn year ->
        final_url = url <> year <> "/"
        %{
          "#{year}" => request_from_seaweedfs(final_url, type, attribute)
        }
      end)
    %{
      "#{server}" => year_values
    }
  end)
</code>```

This is how I am getting year values and making them to the server object. If there is a possibility to break it down while even getting year values?

"#{year}" => request_from_seaweedfs(final_url, type, attribute) this request basically returns such as "2015"  => ["1", "2", "3"], is there any possiblity to merge years a head before going to into servers?

Body:
I have this json

[
  %{
    "159.69.136.31" => [
      %{"2015" => ["4"]},
      %{"2016" => []},
      %{"2017" => ["9"]},
      %{"2018" => []},
      %{"2019" => ["05"]}
    ]
  },
  %{
    "94.130.139.38" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => ["5", "8"]},
      %{"2019" => []}
    ]
  },
  %{
    "94.130.217.56" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => []},
      %{"2019" => []}
    ]
  }
]

and I want to make it something like

[
  %{"2015" => ["4"]},
  %{"2016" => []},
  %{"2017" => ["9"]},
  %{"2018" => ["5", "8"]},
  %{"2019" => ["05"]}
]

Basically, it's merging the same year's keys and the data available on the map. I have tried this solution with different approaches but it didn't work Elixir: Merge list with same map keys to one map

Update: years and IPs are constant
Update little bit more info about this..

years = ["2015", "2016", "2017", "2018", "2019"]
servers = [@seaweedfs_new, @seaweedfs_old, @seaweedfs_oldest]

  Enum.map(servers, fn server ->
    type = seaweefs_type(server)
    attribute = seaweedfs_attribute(server)
    url = "http://" <> server <> ":8888" <> "/#{camera.exid}/snapshots/recordings/"
    year_values =
      Enum.map(years, fn year ->
        final_url = url <> year <> "/"
        %{
          "#{year}" => request_from_seaweedfs(final_url, type, attribute)
        }
      end)
    %{
      "#{server}" => year_values
    }
  end)

This is how I am getting year values and making them to the server object. If there is a possibility to break it down while even getting year values?

"#{year}" => request_from_seaweedfs(final_url, type, attribute) this request basically returns such as "2015"  => ["1", "2", "3"], is there any possiblity to merge years a head before going to into servers?

Body:
To answer your first question, how to make Y from X, here's a quick-and-dirty solution:

data = [
  %{
    "159.69.136.31" => [
      %{"2015" => ["4"]},
      %{"2016" => []},
      %{"2017" => ["9"]},
      %{"2018" => []},
      %{"2019" => ["05"]}
    ]
  },
  %{
    "94.130.139.38" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => ["5", "8"]},
      %{"2019" => []}
    ]
  },
  %{
    "94.130.217.56" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => []},
      %{"2019" => []}
    ]
  }
]

code:

data
|> Enum.map(&Map.values/1)
|> List.flatten
|> Enum.map(fn year_map -> year_map |> Map.to_list |> hd end)
|> Enum.reduce(%{}, fn {year, year_data}, acc ->
  Map.update(acc, year, year_data, &[&1 | year_data])
end)
|> Enum.map(fn {year, year_data} ->
  {year, List.flatten(year_data) |> Enum.reject(&is_nil/1)}
end)
|> IO.inspect

returns:

[
  {"2015", ["4"]},
  {"2016", []},
  {"2017", ["9"]},
  {"2018", ["5", "8"]},
  {"2019", ["05"]}
]

Insert more IO.inspects in the pipeline and functions to see what transformations are going on.


问:
Server Error '/" Application C# asp.net

Parser Error Description: An error
  occurred during the parsing of a
  resource required to service this
  request. Please review the following
  specific parse error details and
  modify your source file appropriately.

Parser Error Message: Could not load
  type 'SafeNet_WebPage.admin.project'.

Source Error:

```<code>Line 1:  <%@ Page Language="C#" AutoEventWireup="false" CodeBehind="project.aspx.cs" Inherits="SafeNet_WebPage.admin.project" %>
Line 2:
Line 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code>```

This project.aspx are locating in one folder with other news.aspx and when I load news it s all ok, it does what it make to do, but when i load project i get this?

答: Double check that the code behind class is named SafeNet_WebPage.admin.project as this is what it's looking for and can't find. Also make sure it's built and deployed properly.

Title: Server Error '/" Application C# asp.net

Body:
Parser Error Description: An error
  occurred during the parsing of a
  resource required to service this
  request. Please review the following
  specific parse error details and
  modify your source file appropriately.

Parser Error Message: Could not load
  type 'SafeNet_WebPage.admin.project'.

Source Error:

Line 1:  <%@ Page Language="C#" AutoEventWireup="false" CodeBehind="project.aspx.cs" Inherits="SafeNet_WebPage.admin.project" %>
Line 2:
Line 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

This project.aspx are locating in one folder with other news.aspx and when I load news it s all ok, it does what it make to do, but when i load project i get this?


问:
Triple variable stacked line/area graph in R
I'm trying to generate a stacked line/area graph utilizing the ggplot and geom_area functions. I have my data loaded into R correctly from what I can tell. Every time I generate the plot, the graph is empty (even though the axis looks correct except for the months being organized in alpha).

I've tried utilizing the data.frame function to define my variables but was unable to generate my plot. I've also looked around Stack Overflow and other websites, but no one seems to have the issue of no errors but still an empty plot.

Here's my data set:

Here's the code I'm using currently:

```<code>ggplot(OHV, aes(x=Month)) +
  geom_area(aes(y=A+B+Unknown, fill="A")) +
  geom_area(aes(y=B, fill="B")) +
  geom_area(aes(y=Unknown, fill="Unknown"))
</code>```

Here's the output at the end:

I have zero error messages, simply just no data being plotted on my graph.

答:
Your dates are being interpreted as a factor. You must transform them.

```<code>ibrary(tidyverse)
set.seed(1)
df <- data.frame(Month = seq(lubridate::ymd('2018-01-01'),
                             lubridate::ymd('2018-12-01'), by = '1 month'),
                 Unknow = sample(17, replace = T, size = 12),
                 V1 = floor(runif(12, min = 35, max = 127)),
                 V2 = floor(runif(12, min = 75, max = 275)))

df <- df %>%
  dplyr::mutate(Month = format(Month, '%b')) %>%
  tidyr::gather(key = "Variable", value = "Value", -Month)

ggplot2::ggplot(df) +
  geom_area(aes(x = Month, y = Value, fill = Variable),
            position = 'stack')

</code>```

Note that I used tidyr::gather to be able to stack the areas in an easier way.

Now assuming your year of analysis is 2018, you need to transform the date of your data frame to something continuous, in the interpretation of r.

```<code>df2 <- df %>%
  dplyr::mutate(Month = paste0("2018-", Month, "-01"),
                Month = lubridate::parse_date_time(Month,"y-b-d"),
                Month = as.Date(Month))

library(scales)
ggplot2::ggplot(df2) +
  geom_area(aes(x = Month, y = Value, fill = Variable),
            position = 'stack') +
  scale_x_date(labels = scales::date_format("%b"))
</code>```

Body:
I'm trying to generate a stacked line/area graph utilizing the ggplot and geom_area functions. I have my data loaded into R correctly from what I can tell. Every time I generate the plot, the graph is empty (even though the axis looks correct except for the months being organized in alpha).

I've tried utilizing the data.frame function to define my variables but was unable to generate my plot. I've also looked around Stack Overflow and other websites, but no one seems to have the issue of no errors but still an empty plot.

Here's my data set:

Here's the code I'm using currently:

ggplot(OHV, aes(x=Month)) +
  geom_area(aes(y=A+B+Unknown, fill="A")) +
  geom_area(aes(y=B, fill="B")) +
  geom_area(aes(y=Unknown, fill="Unknown"))

Here's the output at the end:

I have zero error messages, simply just no data being plotted on my graph.

Body:
Your dates are being interpreted as a factor. You must transform them.

ibrary(tidyverse)
set.seed(1)
df <- data.frame(Month = seq(lubridate::ymd('2018-01-01'),
                             lubridate::ymd('2018-12-01'), by = '1 month'),
                 Unknow = sample(17, replace = T, size = 12),
                 V1 = floor(runif(12, min = 35, max = 127)),
                 V2 = floor(runif(12, min = 75, max = 275)))

df <- df %>%
  dplyr::mutate(Month = format(Month, '%b')) %>%
  tidyr::gather(key = "Variable", value = "Value", -Month)

ggplot2::ggplot(df) +
  geom_area(aes(x = Month, y = Value, fill = Variable),
            position = 'stack')

Note that I used tidyr::gather to be able to stack the areas in an easier way.

Now assuming your year of analysis is 2018, you need to transform the date of your data frame to something continuous, in the interpretation of r.

df2 <- df %>%
  dplyr::mutate(Month = paste0("2018-", Month, "-01"),
                Month = lubridate::parse_date_time(Month,"y-b-d"),
                Month = as.Date(Month))

library(scales)
ggplot2::ggplot(df2) +
  geom_area(aes(x = Month, y = Value, fill = Variable),
            position = 'stack') +
  scale_x_date(labels = scales::date_format("%b"))


问:
API Gateway sign request with AWS SDK for .NET
I have an API in API Gateway whose Authorization type I have set to AWS_IAM to have API Gateway verify the signature on requests.

And restrict the API endpoint to only specific IAM users.

Now the problem is how can I consume this API from .NET? I cannot create/compute the signature by myself. Does the AWS SDK for .NET offer any helper or utility method/class to have the signature computed which I can attach as the HTTP header to my HTTP request?

Or can the API Gateway SDK for .NET make signed requests to my restricted API Gateway endpoint?

答: I've created a NuGet package called AwsSignatureVersion4 which has been verified to work with the AWS API Gateway. Would love to hear what you think of it!</p>


问:
Discord Bot - AttributeError: 'Client' object has no attribute 'commands'
I'm attempting to create a new Discord bot, and an issue occurs when trying to create a message that is announced to all Discord Servers the bot is currently in.

I have attempted to solve the problem to no avail, this includes looking it up, reading documentation, and of course trying new code.

import discord
import asyncio
from discord.ext import commands
from discord.ext.commands import Bot

TOKEN = [REDACTED]

# client = discord.Client()

client = Bot("!")

@client.event
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    if message.content.startswith('!hello'):
        @client.command(pass_context=True)
        async def broadcast(ctx, *, msg):
                for server in bot.guilds:
                    for channel in server.channels:
                        try:
                            await channel.send(msg)
                        except Exception:
                            continue
                        else:
                            break
```

I expect the program to send my message to all servers the bot is currently in.

Ex: !hello Hi there, this is an announcement!

Should trigger the message following !hello to be broadcasted on every server there is.

EDIT: After some help, I'm still having an issue! The error now is that nothing appears even after doing the command, and if I do it again, it comes up with an error: "Command broadcast is already registered."

答:
Why would you use a client.command inside of a client.event like that?

Just use command instead:

```<code>@client.command(pass_context=True)
async def hello(ctx, *, msg):
    for server in client.servers:
        for channel in server.channels:
            try:
                await client.send_message(channel, msg)
            except Exception:
                continue
            else:
                break
</code>```

This will send the message to the first channel in guild where the bot has permission to send messages.

For future references consider upgrading to the latest API version since old ones are NOT supported and you will get a hard time getting help. For the new API the code would look like this:

```<code>@client.command()
async def hello(ctx, *, msg):
    for server in bot.guilds:
        for channel in server.channels:
            try:
                await channel.send(msg)
            except Exception:
                continue
            else:
                break
</code>```

Edit: As per comment from Patrick your specific error indicates that you're using Client instead of Bot , if so just use @bot.command instead.

Body:
I'm attempting to create a new Discord bot, and an issue occurs when trying to create a message that is announced to all Discord Servers the bot is currently in.

I have attempted to solve the problem to no avail, this includes looking it up, reading documentation, and of course trying new code.

import discord
import asyncio
from discord.ext import commands
from discord.ext.commands import Bot

TOKEN = [REDACTED]

# client = discord.Client()

client = Bot("!")

@client.event
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    if message.content.startswith('!hello'):
        @client.command(pass_context=True)
        async def broadcast(ctx, *, msg):
                for server in bot.guilds:
                    for channel in server.channels:
                        try:
                            await channel.send(msg)
                        except Exception:
                            continue
                        else:
                            break

I expect the program to send my message to all servers the bot is currently in.

Ex: !hello Hi there, this is an announcement!

Should trigger the message following !hello to be broadcasted on every server there is.

EDIT: After some help, I'm still having an issue! The error now is that nothing appears even after doing the command, and if I do it again, it comes up with an error: "Command broadcast is already registered."

Body:
Why would you use a client.command inside of a client.event like that?

Just use command instead:

@client.command(pass_context=True)
async def hello(ctx, *, msg):
    for server in client.servers:
        for channel in server.channels:
            try:
                await client.send_message(channel, msg)
            except Exception:
                continue
            else:
                break

This will send the message to the first channel in guild where the bot has permission to send messages.

For future references consider upgrading to the latest API version since old ones are NOT supported and you will get a hard time getting help. For the new API the code would look like this:

@client.command()
async def hello(ctx, *, msg):
    for server in bot.guilds:
        for channel in server.channels:
            try:
                await channel.send(msg)
            except Exception:
                continue
            else:
                break

Edit: As per comment from Patrick your specific error indicates that you're using Client instead of Bot , if so just use @bot.command instead.


问:
Call a js function on an html snippet rendered using ngBindHtml
I'm fetching some html content that I want to display in an Angular widget. I'm using ng-bind-html to display this html content in the controller. Once this html content has rendered I want to call a js function that can modify some parts of this html content(Hide/show using classes in the content). There is no trigger for this function I want to call this function as soon as the html is rendered.

I tried calling the js function after the ngBindHtml object is initialized which no surprise doesn't work.

Is there some way to find out(an event or something like that) when the html content has rendered.

I don't have any sharable code right now.

答:
Try calling your function inside $timeout:

```<code>$timeout(function() {
    // your code
});
</code>```

$timeout will add a new event to the browser event queue where the rendering process is in.

Body:
Try calling your function inside $timeout:

$timeout(function() {
    // your code
});

$timeout will add a new event to the browser event queue where the rendering process is in.


问:
Multiply every third element of a list by two
Input data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Output data: [1, 2, 6, 4, 5, 12, 7, 8, 18, 10]

I have read many answers where were suggested to use slice notation with including first element. But in my case I should take each 3rd element of the list.

Is it possible to improve my realization?

for index in range(len(data)):
    if (index + 1) % 3 == 0:
        data[index] = data[index] * 2
```

答:
You could organize it a little bit by passing a third argument to the range() function, like this:

for index in range(2, len(data), 3):
        data[index] = data[index]*2


问:
Accessing Object Property Values Within an Array - JavaScript
Learning how to access property values.

If I have

```<code>let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];
</code>```

How would I console.log just the value of the second object? I.e. "website developer".

I know how to console.log the entire key-value pair (or object) by using .find():

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

console.log(object1.find(function(element) {
    return element.hasOwnProperty("job");
}
));```

But what about just the value of this pair?

答:
First, your object1 is an array of objects, not an object.

Although, there's a way to achieve what you want.

const fun = (arr, prop) => arr.find((obj) => obj.hasOwnProperty(prop))[prop];

const object1 = [{name: 'HappyHands31'}, {job: 'website developer'}, {city: 'Chicago'}];

const property = 'job';

console.log(fun(object1, property));```

Body:
Learning how to access property values.

If I have

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

How would I console.log just the value of the second object? I.e. "website developer".

I know how to console.log the entire key-value pair (or object) by using .find():

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

console.log(object1.find(function(element) {
    return element.hasOwnProperty("job");
}
));

But what about just the value of this pair?


问:
Accepting Splunk license agreement using Ansible-Playbook
I am new to using Ansible-Playbooks, and I am running into issues in accepting license agreements with Splunk.

Any time I have shell run:

```<code>"/opt/splunkforwarder/bin/splunk start --accept-license --answer-yes"
</code>```

I get a continuous lockup that forces me to terminate the program.

```<code>TASK [acceptlicense] ****************************************************************************************************************

^C
</code>```

Going into the box and running the command manually I am told the following:

```<code>[root@##########-lab_env]# /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes

This appears to be your first time running this version of Splunk.

Create credentials for the administrator account.
Characters do not appear on the screen when you type the password.
Password must contain at least:
   * 8 total printable ASCII character(s).
Please enter a new password:
</code>```

I have gone through several forums online that give help in answering what to do when met with specific prompts like this, but anytime I make an adjustment I am told something along the lines of:

ERROR! '_______' is not a valid attribute for a Task

At this point I am pretty stuck and unsure of how to continue.

My code snippet is as follows:

```<code>- hosts: "{{hostName}}"
  become: true
  become_user: root
  become_method: sudo

  tasks:

    - name: copy_splunk
      shell: cp splunkforwarder-7.1.3-51d9cac7b837-linux-2.6-x86_64.rpm /opt/.; date; ls -l /opt
      args:
        chdir: /tmp
      register: run_ll

    - debug: var=run_ll.stdout_lines

    - name: install rpm package
      shell: rpm -ivh splunkforwarder-7.1.3-51d9cac7b837-linux-2.6-x86_64.rpm
      args:
        chdir: /tmp
      ignore_errors: True
      register: install_rpm

    - debug: var=install_rpm.stdout_lines

    - name: acceptlicense
      tags:
        - install
      shell: /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes
      register: accept_l

    - debug: var=accept_l.stdout_lines
</code>```

I have only done a couple of playbooks in the past, so this error is something new to me.

Does anyone have any insight?

答:
This is not well documented by Splunk, but there are two ways to do that.

1) Provide the password on the command line.  splunk start --accept-license --answer-yes --no-prompt --seed-passwd <passwd>.

2) Create a $SPLUNK_HOME/etc/system/local/user-seed.conf file

```<code>[user_info]
USERNAME = admin
PASSWORD = <password>
</code>```

Then start Splunk:
splunk start --accept-license --answer-yes --no-prompt

Body:
I am new to using Ansible-Playbooks, and I am running into issues in accepting license agreements with Splunk.

Any time I have shell run:

"/opt/splunkforwarder/bin/splunk start --accept-license --answer-yes"

I get a continuous lockup that forces me to terminate the program.

TASK [acceptlicense] ****************************************************************************************************************

^C

Going into the box and running the command manually I am told the following:

[root@##########-lab_env]# /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes

This appears to be your first time running this version of Splunk.

Create credentials for the administrator account.
Characters do not appear on the screen when you type the password.
Password must contain at least:
   * 8 total printable ASCII character(s).
Please enter a new password:

I have gone through several forums online that give help in answering what to do when met with specific prompts like this, but anytime I make an adjustment I am told something along the lines of:

ERROR! '_______' is not a valid attribute for a Task

At this point I am pretty stuck and unsure of how to continue.

My code snippet is as follows:

- hosts: "{{hostName}}"
  become: true
  become_user: root
  become_method: sudo

  tasks:

    - name: copy_splunk
      shell: cp splunkforwarder-7.1.3-51d9cac7b837-linux-2.6-x86_64.rpm /opt/.; date; ls -l /opt
      args:
        chdir: /tmp
      register: run_ll

    - debug: var=run_ll.stdout_lines

    - name: install rpm package
      shell: rpm -ivh splunkforwarder-7.1.3-51d9cac7b837-linux-2.6-x86_64.rpm
      args:
        chdir: /tmp
      ignore_errors: True
      register: install_rpm

    - debug: var=install_rpm.stdout_lines

    - name: acceptlicense
      tags:
        - install
      shell: /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes
      register: accept_l

    - debug: var=accept_l.stdout_lines

I have only done a couple of playbooks in the past, so this error is something new to me.

Does anyone have any insight?

Body:
This is not well documented by Splunk, but there are two ways to do that.

1) Provide the password on the command line.  splunk start --accept-license --answer-yes --no-prompt --seed-passwd <passwd>.

2) Create a $SPLUNK_HOME/etc/system/local/user-seed.conf file

[user_info]
USERNAME = admin
PASSWORD = <password>

Then start Splunk:
splunk start --accept-license --answer-yes --no-prompt


问:
Passing zero or variable number of values to Click.Option
Suppose we have the following function, which
has an optional parameter exclude, which is expected
to be a list of strings:

```<code>@group.command()
@click.option(???)
def load(exclude = None):
    # ...
</code>```

I want the user to be able to execute the script like so:

```<code>python script.py load --exclude one two three
</code>```

or

```<code>python script.py load --exclude something
</code>```

In which case, I would expect exclude to be
['one', 'two', 'three'] and ['something'], respectively.
But I want the number of values in --exclude to be variable, including 0. I.e. The user should be able to execute

```<code>python script.py load
</code>```

In which case exclude should be None (or [], does not matter).

How can I do that using click?

My only viable option so far is forcing the user to use

```<code>python script.py load --exclude "one two three"
</code>```

and then calling exclude.split(), but something cleaner would be better.

答:
It doesn't appear to be supported, in the way that you want, by Click:

According to the docs Multi Value Options must have the number of options provided as specified in nargs, so nargs=2 requires 2 values.

additionally, multiple options will not negate the need to pass the option multiple times.

Your most likely solution is to pass a string and split, although I haven't used Click too deeply, so someone may have a better solution.

Body:
Suppose we have the following function, which
has an optional parameter exclude, which is expected
to be a list of strings:

@group.command()
@click.option(???)
def load(exclude = None):
    # ...

I want the user to be able to execute the script like so:

python script.py load --exclude one two three

or

python script.py load --exclude something

In which case, I would expect exclude to be
['one', 'two', 'three'] and ['something'], respectively.
But I want the number of values in --exclude to be variable, including 0. I.e. The user should be able to execute

python script.py load

In which case exclude should be None (or [], does not matter).

How can I do that using click?

My only viable option so far is forcing the user to use

python script.py load --exclude "one two three"

and then calling exclude.split(), but something cleaner would be better.


问:
Javascript filter by nested object attribute
I have the following array:

```<code>arr = [{id: 1, type: {name: "Approval", id: 1}},
       {id: 2, type: {name: "Rejection", id: 2}},
       {id: 3, type: {name: "Approval", id: 1}}
      ];
</code>```

Why does the following produce and [] result? I would expect to get an array of 2 objects (i.e. id 1 and 3).

```<code>$.grep(arr, function(a) { return a.type.name === "Approval"; })
</code>```

Thoughts?

答:
return is a reserved keyword in js. Hence you cannot use it as a variable and access its properties.

Instead, you need to access the properties of the a variable:

$.grep(arr, function(a) { return a.type.name === "Approval"; })
```

Body:
I have the following array:

arr = [{id: 1, type: {name: "Approval", id: 1}},
       {id: 2, type: {name: "Rejection", id: 2}},
       {id: 3, type: {name: "Approval", id: 1}}
      ];

Why does the following produce and [] result? I would expect to get an array of 2 objects (i.e. id 1 and 3).

$.grep(arr, function(a) { return a.type.name === "Approval"; })

Thoughts?


问:
ImageMagick: How do I do a simple crop?
All I'm trying to do is crop images to a width of 1400 pixels from the left, but leave them at the same height.

The format should be width: 1400px, height 100% (unchanged), offset X and Y are both zero, so +0+0 (for X and Y):

```<code>convert -crop 1400x100%+0+0 inputfile outputfile
</code>```

This doesn't actually do anything! Can someone help me with my syntax?

答:
Your syntax for ImageMagick is not correct. It may work in ImageMagick 6, which is forgiving, but not in ImageMagick 7. Read the input before any operations.

What you need to do is just specify Wx+0+0, without including H. That will tell ImageMagick, that you just want the width cropped. For example:

Lena:

convert lena.png -crop 100x+0+0 +repage result.png

Include +repage for those formats that support virtual canvas, such as PNG and TIFF. JPG does not need it, but it won't hurt.

See https://imagemagick.org/Usage/crop/#crop_percent

Title: ImageMagick: How do I do a simple crop?

Body:
All I'm trying to do is crop images to a width of 1400 pixels from the left, but leave them at the same height.

The format should be width: 1400px, height 100% (unchanged), offset X and Y are both zero, so +0+0 (for X and Y):

convert -crop 1400x100%+0+0 inputfile outputfile

This doesn't actually do anything! Can someone help me with my syntax?


答:
Why do you use jQuery here? Javascript gives you perfect methods for that. filter or find.

const arr = [
{id: 1, type: {name: "Approval", id: 1}},
{id: 2, type: {name: "Rejection", id: 2}},
{id: 3, type: {name: "Approval", id: 1}}
];

const matches = arr
    .filter(entry => entry.type.name === 'Approval')
console.log(matches)```

Title: Javascript filter by nested object attribute


问:
How can I display videos from my own computer on my website
so I have this website so far

https://imgur.com/a/o4T81MG

Looks like that. I want the play thumbnails to display video I have on my computer. I want to use my computer as a video host. I am trying to play around making a video sharing site. I plan on going down the google cloud route to host my videos but as of right now I wanted to know if its possible to use my own computer as a server to retrieve videos I have saved.

答:
You need to store your video files in a folder on a server, and then you need to reference them in your code. It's very simple to reference the videos when they are in a folder on a server.

see:

https://www.w3schools.com/html/html5_video.asp