问:
How to read request body multiple times in asp net core 2.2 middleware?
I tried this:
Read request body twice
and this:
https://github.com/aspnet/Mvc/issues/4962
but did not work.
I read request body like this:

```<code>app.Use(async (context, next) =>
{
    var requestBody = await ReadStream(context.Request.Body);
    var requestPath = context.Request.Path.ToString();
    //Do some thing

    await next.Invoke();

    var responseStatusCode = context.Response.StatusCode;
    //Do some other thing
});

private async Task<string> ReadStream(Stream stream)
{
    using (var streamReader = new StreamReader(stream))
    {
        var result = await streamReader.ReadToEndAsync();

        return result;
    }
}
</code>```

In controller I get 'disposed object' or 'empty stream'.

答:
When stream is read second time then the stream pointer is set to the last position. You should try to move it back to position zero to read it again from the beginning.

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;

namespace Test_Middlewares.Middlewares
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class LoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<LoggingMiddleware> _logger;

        public LoggingMiddleware(RequestDelegate next, ILogger<LoggingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            var HttpContextBody = httpContext.Request.Body;
            string requestBody = "";

            httpContext.Request.EnableBuffering();

            // Leave the body open so the next middleware can read it.
            using (var reader = new StreamReader(
                httpContext.Request.Body,
                encoding: Encoding.UTF8,
                detectEncodingFromByteOrderMarks: false,
                bufferSize: -1,
                leaveOpen: true))
            {
                var body = await reader.ReadToEndAsync();
                // Do some processing with body…

                // Reset the request body stream position so the next middleware can read it
                httpContext.Request.Body.Position = 0;
            }

            _logger.LogDebug("Middleware 1 body =" + requestBody);

            await _next.Invoke(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class LoggingMiddlewareExtensions
    {
        public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<LoggingMiddleware>();
        }
    }
}
</code>```

For more info please refer to these links :

https://devblogs.microsoft.com/aspnet/re-reading-asp-net-core-request-bodies-with-enablebuffering/

https://gunnarpeipman.com/aspnet-core-request-body/

Body:
I tried this:
Read request body twice
and this:
https://github.com/aspnet/Mvc/issues/4962
but did not work.
I read request body like this:

app.Use(async (context, next) =>
{
    var requestBody = await ReadStream(context.Request.Body);
    var requestPath = context.Request.Path.ToString();
    //Do some thing

    await next.Invoke();

    var responseStatusCode = context.Response.StatusCode;
    //Do some other thing
});

private async Task<string> ReadStream(Stream stream)
{
    using (var streamReader = new StreamReader(stream))
    {
        var result = await streamReader.ReadToEndAsync();

        return result;
    }
}

In controller I get 'disposed object' or 'empty stream'.

Body:
When stream is read second time then the stream pointer is set to the last position. You should try to move it back to position zero to read it again from the beginning.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;

namespace Test_Middlewares.Middlewares
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class LoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<LoggingMiddleware> _logger;

        public LoggingMiddleware(RequestDelegate next, ILogger<LoggingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            var HttpContextBody = httpContext.Request.Body;
            string requestBody = "";

            httpContext.Request.EnableBuffering();

            // Leave the body open so the next middleware can read it.
            using (var reader = new StreamReader(
                httpContext.Request.Body,
                encoding: Encoding.UTF8,
                detectEncodingFromByteOrderMarks: false,
                bufferSize: -1,
                leaveOpen: true))
            {
                var body = await reader.ReadToEndAsync();
                // Do some processing with body…

                // Reset the request body stream position so the next middleware can read it
                httpContext.Request.Body.Position = 0;
            }

            _logger.LogDebug("Middleware 1 body =" + requestBody);

            await _next.Invoke(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class LoggingMiddlewareExtensions
    {
        public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<LoggingMiddleware>();
        }
    }
}

For more info please refer to these links :

https://devblogs.microsoft.com/aspnet/re-reading-asp-net-core-request-bodies-with-enablebuffering/

https://gunnarpeipman.com/aspnet-core-request-body/


来源: stackexchange

问:
syntax error when using forward slash to define positional only arguments
I'm following the python tutorial here.

I'm trying to define a function with positional only arguments and I get a invalid syntax error

I've tried both the command line interpreter and putting the definition into a file

My definition looks like this

def pos_only(x,/):
    return x**2
```

<p>I get the usual syntax error</p>

```  File "bas.py", line 1
    def pos_ony(x,/):
                  ^
SyntaxError: invalid syntax
```

Using * to define a keyword argument only function works just fine.

答:
This works in 3.8 and 3.9, but not before:</p>

```<code>$ pythons --file po
below cmd output started 2020 Fri Feb 14 01:57:45 PM PST
/usr/local/cpython-1.0/bin/python (1.0.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.1/bin/python (1.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.2/bin/python (1.2) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.3/bin/python (1.3) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.4/bin/python (1.4) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.5/bin/python (1.5.2) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.6/bin/python (1.6.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.0/bin/python (2.0.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.1/bin/python (2.1.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.2/bin/python (2.2.0) bad
      File "<string>", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.3/bin/python (2.3.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.4/bin/python (2.4.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.5/bin/python (2.5.6) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.6/bin/python (2.6.9) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.7.16/bin/python (2.7.16) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.7/bin/python (2.7.16) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.0/bin/python (3.0.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.1/bin/python (3.1.5) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.2/bin/python (3.2.5) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.3/bin/python (3.3.7) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.4/bin/python (3.4.8) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.5/bin/python (3.5.5) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.6/bin/python (3.6.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.7/bin/python (3.7.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.8/bin/python (3.8.0) good
/usr/local/cpython-3.9/bin/python (3.9.0a3) good
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by jnr.posix.JavaLibCHelper (file:/usr/local/jython-2.7/jython.jar) to method sun.nio.ch.SelChImpl.getFD()
WARNING: Please consider reporting this to the maintainers of jnr.posix.JavaLibCHelper
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
/usr/local/jython-2.7/bin/jython (2.7.0) bad
    WARNING: An illegal reflective access operation has occurred
    WARNING: Illegal reflective access by jnr.posix.JavaLibCHelper (file:/usr/local/jython-2.7/jython.jar) to method sun.nio.ch.SelChImpl.getFD()
    WARNING: Please consider reporting this to the maintainers of jnr.posix.JavaLibCHelper
    WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
    WARNING: All illegal access operations will be denied in a future release
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: mismatched input '/' expecting RPAREN
/usr/local/pypy-5.10.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy-5.3.1/bin/pypy (2.7.10) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy-5.9.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy-6.0.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy-7.0.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy-7.1.1/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy-7.2.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy-7.3.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy3-5.10.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-5.5.0/bin/pypy3 (3.3.5) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-5.8.0-with-lzma-fixes/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-5.8.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-5.9.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-6.0.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy3-7.0.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy3-7.2.0/bin/pypy3 (3.6.9) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy3-7.3.0/bin/pypy3 (3.6.9) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/micropython-1.11/bin/micropython (3.4.0) bad
    Traceback (most recent call last):
      File "po", line 3
    SyntaxError: invalid syntax
/usr/local/micropython-git-2017-06-16/bin/micropython (3.4.0) bad
    Traceback (most recent call last):
      File "po", line 3
    SyntaxError: invalid syntax
/usr/local/micropython-git-2018-06-06/bin/micropython (3.4.0) bad
    Traceback (most recent call last):
      File "po", line 3
    SyntaxError: invalid syntax
/usr/local/tauthon-2.8/bin/tauthon (2.8.0+) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm following the python tutorial here.

I'm trying to define a function with positional only arguments and I get a invalid syntax error

I've tried both the command line interpreter and putting the definition into a file

My definition looks like this

def pos_only(x,/):
    return x**2

I get the usual syntax error

  File "bas.py", line 1
    def pos_ony(x,/):
                  ^
SyntaxError: invalid syntax

Using * to define a keyword argument only function works just fine.

Body:
This works in 3.8 and 3.9, but not before:

$ pythons --file po
below cmd output started 2020 Fri Feb 14 01:57:45 PM PST
/usr/local/cpython-1.0/bin/python (1.0.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.1/bin/python (1.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.2/bin/python (1.2) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.3/bin/python (1.3) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.4/bin/python (1.4) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.5/bin/python (1.5.2) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-1.6/bin/python (1.6.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.0/bin/python (2.0.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.1/bin/python (2.1.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.2/bin/python (2.2.0) bad
      File "<string>", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.3/bin/python (2.3.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.4/bin/python (2.4.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.5/bin/python (2.5.6) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.6/bin/python (2.6.9) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.7.16/bin/python (2.7.16) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-2.7/bin/python (2.7.16) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.0/bin/python (3.0.1) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.1/bin/python (3.1.5) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.2/bin/python (3.2.5) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.3/bin/python (3.3.7) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.4/bin/python (3.4.8) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.5/bin/python (3.5.5) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.6/bin/python (3.6.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.7/bin/python (3.7.0) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax
/usr/local/cpython-3.8/bin/python (3.8.0) good
/usr/local/cpython-3.9/bin/python (3.9.0a3) good
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by jnr.posix.JavaLibCHelper (file:/usr/local/jython-2.7/jython.jar) to method sun.nio.ch.SelChImpl.getFD()
WARNING: Please consider reporting this to the maintainers of jnr.posix.JavaLibCHelper
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
/usr/local/jython-2.7/bin/jython (2.7.0) bad
    WARNING: An illegal reflective access operation has occurred
    WARNING: Illegal reflective access by jnr.posix.JavaLibCHelper (file:/usr/local/jython-2.7/jython.jar) to method sun.nio.ch.SelChImpl.getFD()
    WARNING: Please consider reporting this to the maintainers of jnr.posix.JavaLibCHelper
    WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
    WARNING: All illegal access operations will be denied in a future release
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: mismatched input '/' expecting RPAREN
/usr/local/pypy-5.10.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy-5.3.1/bin/pypy (2.7.10) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy-5.9.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy-6.0.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy-7.0.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy-7.1.1/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy-7.2.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy-7.3.0/bin/pypy (2.7.13) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy3-5.10.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-5.5.0/bin/pypy3 (3.3.5) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-5.8.0-with-lzma-fixes/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-5.8.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-5.9.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                      ^
    SyntaxError: invalid syntax
/usr/local/pypy3-6.0.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy3-7.0.0/bin/pypy3 (3.5.3) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy3-7.2.0/bin/pypy3 (3.6.9) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/pypy3-7.3.0/bin/pypy3 (3.6.9) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax (expected ')')
/usr/local/micropython-1.11/bin/micropython (3.4.0) bad
    Traceback (most recent call last):
      File "po", line 3
    SyntaxError: invalid syntax
/usr/local/micropython-git-2017-06-16/bin/micropython (3.4.0) bad
    Traceback (most recent call last):
      File "po", line 3
    SyntaxError: invalid syntax
/usr/local/micropython-git-2018-06-06/bin/micropython (3.4.0) bad
    Traceback (most recent call last):
      File "po", line 3
    SyntaxError: invalid syntax
/usr/local/tauthon-2.8/bin/tauthon (2.8.0+) bad
      File "po", line 3
        def pos_only(x,/):
                       ^
    SyntaxError: invalid syntax


问:
tsconfig.json: Build:No inputs were found in config file
I have an ASP.NET core project and I'm getting this error when I try to build it:

```<code>error TS18003: Build:No inputs were found in config file 'Z:/Projects/client/ZV/src/ZV/Scripts/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '["../wwwroot/app","node_modules/*"]'.
1>         The command exited with code 1.
1>       Done executing task "VsTsc" -- FAILED.
</code>```

This is my tsconfig.json file:

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es5", "dom" ],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "outDir": "../wwwroot/app/",
    "removeComments": false,
    "sourceMap": true,
    "target": "es6"
  },
  "exclude": [
    "../wwwroot/app",
    "node_modules/*"
  ]
}
</code>```

Is this a bug or am I doing something wrong? I did recently upgrade Visual Studio 2015 to update 3. Has anyone encountered this before?

答:
This can occur because typescript server can't find any files described by the include array:

// tsconfig.json
{
  //...
  "include": [
    "./src/"
  ],
}
```

If you're using VSCode, you can restart your TS server within your editor super easily to prompt it to re-evaluate the file like this:

Navigate to any .ts or .tsx file

Open the command palette (CMD + SHIFT + P on mac)

Run the TypeScript: Restart TS server command:

ContentLicense: CC BY-SA 3.0

Body:
I have an ASP.NET core project and I'm getting this error when I try to build it:

error TS18003: Build:No inputs were found in config file 'Z:/Projects/client/ZV/src/ZV/Scripts/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '["../wwwroot/app","node_modules/*"]'.
1>         The command exited with code 1.
1>       Done executing task "VsTsc" -- FAILED.

This is my tsconfig.json file:

{
  "compileOnSave": true,
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es5", "dom" ],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "outDir": "../wwwroot/app/",
    "removeComments": false,
    "sourceMap": true,
    "target": "es6"
  },
  "exclude": [
    "../wwwroot/app",
    "node_modules/*"
  ]
}

Is this a bug or am I doing something wrong? I did recently upgrade Visual Studio 2015 to update 3. Has anyone encountered this before?

Body:
This can occur because typescript server can't find any files described by the include array:

// tsconfig.json
{
  //...
  "include": [
    "./src/"
  ],
}

If you're using VSCode, you can restart your TS server within your editor super easily to prompt it to re-evaluate the file like this:

Navigate to any .ts or .tsx file

Open the command palette (CMD + SHIFT + P on mac)

Run the TypeScript: Restart TS server command:


问:
Google Sheet script for keeping the first tab in view at all times?
I have a Google Sheets spreadsheet with a lot of tabs that I frequently scroll though, but I wish that the master sheet I have (the first tab) is always displayed at the bottom no matter where I'm at in the scrolling process. That way I can just quickly click on the master sheet's tab to go back to it.

I know there's not a way to do this in any of the settings, but perhaps there's an onOpen trigger I could put in a script?

答:
Nothing can control the tabs down below like that but I think you can script yourself to jump back to tab one from the menu

```<code>function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Custom Menu')
      .addItem('Go To Tab 1', 'tab1')
      .addToUi();
}

function tab1(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getSheetByName("Tab2");
sh.setActiveSheet(ss);
SpreadsheetApp.flush();

}
</code>```

should do the trick

Body:
Nothing can control the tabs down below like that but I think you can script yourself to jump back to tab one from the menu

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Custom Menu')
      .addItem('Go To Tab 1', 'tab1')
      .addToUi();
}

function tab1(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getSheetByName("Tab2");
sh.setActiveSheet(ss);
SpreadsheetApp.flush();

}

should do the trick


问:
Vue-cli 3 component library to support SSR
I am creating a custom component library that i want to share across multiple domains.

Domains:

Each domain has its own instance of nuxt

Each domain has my-component-lib registered in package.json

Each domain registers the lib as a plugin

```<code>//my-component-lib.js
import components from 'my-component-lib'
import Vue from 'vue'

export default ({ store }) => {
 Vue.use(components, { store: store })
}

//nuxt.config.js
plugins: [
  /*Desired option 1*/ '@/plugins/my-component-lib',
  /*Currently using*/ { src: '@/plugins/my-component-lib', ssr: false }
]
</code>```

my-component-lib:

Setup using vue-cli 3

The library is composed of basic html tags and CSS ex <input ></input>. The styling is important and i would like to keep it together with the component (extract:false) so i can pull individual components out and not worry about importing a css file.

```<code>//vue.config.js
module.exports = {
 outputDir: 'dist',
 lintOnSave: false,
 css: {
  extract: false
 }
}
</code>```

setup for production using "production": "vue-cli-service build --target lib --name sc components/index.js"

Problems:

Using the desired option, when i run nuxt npm run dev i get a document is not defined in function addStyle (obj /* StyleObjectPart */) {..} within sc.common.js

Using the current option, i get a hydration error(The client-side rendered virtual DOM tree is not matching server-rendered content.) which is fixed if i wrap the components within <no-ssr> tags which i do not want to do.

I want to compile my component library to work with SSR and not have to import a large css file

答:
Change

```<code> ...
 css: {
  extract: false
 }
 ...
</code>```

to true

Body:
I am creating a custom component library that i want to share across multiple domains.

Domains:

Each domain has its own instance of nuxt

Each domain has my-component-lib registered in package.json

Each domain registers the lib as a plugin

//my-component-lib.js
import components from 'my-component-lib'
import Vue from 'vue'

export default ({ store }) => {
 Vue.use(components, { store: store })
}

//nuxt.config.js
plugins: [
  /*Desired option 1*/ '@/plugins/my-component-lib',
  /*Currently using*/ { src: '@/plugins/my-component-lib', ssr: false }
]

my-component-lib:

Setup using vue-cli 3

The library is composed of basic html tags and CSS ex <input ></input>. The styling is important and i would like to keep it together with the component (extract:false) so i can pull individual components out and not worry about importing a css file.

//vue.config.js
module.exports = {
 outputDir: 'dist',
 lintOnSave: false,
 css: {
  extract: false
 }
}

setup for production using "production": "vue-cli-service build --target lib --name sc components/index.js"

Problems:

Using the desired option, when i run nuxt npm run dev i get a document is not defined in function addStyle (obj /* StyleObjectPart */) {..} within sc.common.js

Using the current option, i get a hydration error(The client-side rendered virtual DOM tree is not matching server-rendered content.) which is fixed if i wrap the components within <no-ssr> tags which i do not want to do.

I want to compile my component library to work with SSR and not have to import a large css file

Body:
Change

 ...
 css: {
  extract: false
 }
 ...

to true


问:
Getting value in div and changing to a link
I have a div that gets values from the database and prints them inside a div:

```<code><div class="number-string">
123456789
</div>
</code>```

I'm hoping to pull that value inside .number-string and change that div to a link where the href would be "https://somelink.com/123456789"
All I have right now is

```<code>var getnumber = $('.number-string').text()
</code>```

I can't figure out how to change that div and add in a variable to a link

答:
You can use the replaceWith() method to replace the div with a link.

```<code>$('.number-string').each(function(){
  $(this).replaceWith(`<a href="https://somelink.com/${this.innerText}">${this.innerText}</a>`);
})
</code>```

Body:
I have a div that gets values from the database and prints them inside a div:

123456789

I'm hoping to pull that value inside .number-string and change that div to a link where the href would be "https://somelink.com/123456789"
All I have right now is

var getnumber = $('.number-string').text()

I can't figure out how to change that div and add in a variable to a link

Body:
You can use the replaceWith() method to replace the div with a link.

$('.number-string').each(function(){
  $(this).replaceWith(`<a href="https://somelink.com/${this.innerText}">${this.innerText}</a>`);
})


问:
vscode.languages.registerCompletionItemProvider not working with 'markdown'
I am trying to write a VS Code extension to provide a completion provider in markdown, but following the example from Microsoft from this repo I can't seem to get things working when I switch the language from 'plaintext' to 'markdown'.

With the following code, with my extension running in debug mode, in a .txt file typing "h" will trigger the completion suggestions, but it won't trigger completions when in an .md file.

Am I making some sort of silly mistake here?

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
  console.log('activate');

  let _provideCompletionItems = {
    provideCompletionItems(
      document: vscode.TextDocument,
      position: vscode.Position,
      token: vscode.CancellationToken,
      context: vscode.CompletionContext
    ) {
      console.log('provide');
      const c = new vscode.CompletionItem('Hello World!');
      return [c];
    },
  };

  context.subscriptions.push(
    vscode.languages.registerCompletionItemProvider('plaintext', _provideCompletionItems)
  );

  context.subscriptions.push(
    vscode.languages.registerCompletionItemProvider('markdown', _provideCompletionItems)
  );

  const md = { scheme: 'file', language: 'markdown' };
  context.subscriptions.push(
    vscode.languages.registerCompletionItemProvider(md, _provideCompletionItems)
  );
}

```

答:
Ok, Matt Bierner was correct in his comment above.

editor.quickSuggestions was false because I was in a markdown file.

I was able to trigger the suggestions with the editor.action.triggerSuggest keybinding (default ctrl+space).

In case anyone is wondering, here is how to override the default for markdown in your settings.json:

```<code> "[markdown]":  {
    "editor.quickSuggestions": true
  },
</code>```

Body:
Ok, Matt Bierner was correct in his comment above.

editor.quickSuggestions was false because I was in a markdown file.

I was able to trigger the suggestions with the editor.action.triggerSuggest keybinding (default ctrl+space).

In case anyone is wondering, here is how to override the default for markdown in your settings.json:

 "[markdown]":  {
    "editor.quickSuggestions": true
  },


问:
angular 9 library publish error "Trying to publish a package that has been compiled by Ivy"
I migrated my angular 8.x.x project to angular 9.x.x and when I try to publish my library, it fails with below error

npm ERR! @candiman/website@9.0.0 prepublishOnly: node --eval "console.error('ERROR: Trying to publish a package that has been compiled by Ivy. This is not allowed.\nPlease delete and rebuild the package, without compiling with Ivy, before attempting to publish.\n')" && exit 1

is there anything changed in the angular 9

答:
UPDATE ANGULAR 12

using the --configuration production option while building the library fixed my issue

```<code>ng build --configuration production
</code>```

Original answer:

using --prod option while building the library fixed my issue

```<code>ng build yourLibraryName --prod
</code>```

Body:
UPDATE ANGULAR 12

using the --configuration production option while building the library fixed my issue

ng build --configuration production

Original answer:

using --prod option while building the library fixed my issue

ng build yourLibraryName --prod


问:
Trying to install gdal 3.0.4 on Red Hat 8
I'm running Red Hat 8, and I'm trying to install gdal 3.0.4 on it.

The commands I've excuted thus far:

wget http://download.osgeo.org/gdal/3.0.4/gdal-3.0.4.tar.gz
tar zxvf gdal-3.0.4.tar.gz
cd gdal-3.0.4
./configure
sudo make install
```

<p>After I run <code>sudo make install</code>, I get the following error messages:</p>

<pre class="lang-sh prettyprint-override"><code>path/to/gdal-3.0.4/.libs/libgdal.so: undefined reference to `jpeg_CreateDecompress_12`
path/to/gdal-3.0.4/.libs/libgdal.so: undefined reference to `jpeg_write_tables_12`
path/to/gdal-3.0.4/.libs/libgdal.so: undefined reference to `jpeg_start_decompress_12`
</code>```

...

It continues on like this for some amount of lines all starting with jpeg and ending with 12 and different words in between. It finally ends with:

```<code>collect2: error: ld returned 1 exit status
make[1]: *** [GNUmakefile:82: gdalinfo] Error 1
make: *** [GNUmakefile:112: apps-target] Error 2
</code>```

I'm not sure what to do or what this error even means. If anyone has any ideas, or if there is anymore information I can share, let me know.

答:
After running my commands, if you run

sudo make clean
 ./configure --with-libtiff=internal --with-geotiff=internal --with-jpeg=internal --with-jpeg12
sudo make install
```

Then my error cleared up. Of course, I suspect one would need the right libjpeg packages installed as well. I may have had them installed beforehand so it's something to keep in mind.

https://trac.osgeo.org/gdal/wiki/TIFF12BitJPEG

The above link was extremely useful in solving this issue.

Body:
I'm running Red Hat 8, and I'm trying to install gdal 3.0.4 on it.

The commands I've excuted thus far:

wget http://download.osgeo.org/gdal/3.0.4/gdal-3.0.4.tar.gz
tar zxvf gdal-3.0.4.tar.gz
cd gdal-3.0.4
./configure
sudo make install

After I run sudo make install, I get the following error messages:

path/to/gdal-3.0.4/.libs/libgdal.so: undefined reference to `jpeg_CreateDecompress_12`
path/to/gdal-3.0.4/.libs/libgdal.so: undefined reference to `jpeg_write_tables_12`
path/to/gdal-3.0.4/.libs/libgdal.so: undefined reference to `jpeg_start_decompress_12`

...

It continues on like this for some amount of lines all starting with jpeg and ending with 12 and different words in between. It finally ends with:

collect2: error: ld returned 1 exit status
make[1]: *** [GNUmakefile:82: gdalinfo] Error 1
make: *** [GNUmakefile:112: apps-target] Error 2

I'm not sure what to do or what this error even means. If anyone has any ideas, or if there is anymore information I can share, let me know.

Body:
After running my commands, if you run

sudo make clean
 ./configure --with-libtiff=internal --with-geotiff=internal --with-jpeg=internal --with-jpeg12
sudo make install

Then my error cleared up. Of course, I suspect one would need the right libjpeg packages installed as well. I may have had them installed beforehand so it's something to keep in mind.

https://trac.osgeo.org/gdal/wiki/TIFF12BitJPEG

The above link was extremely useful in solving this issue.


问:
How to toggle a div that is hidden on page load
I am using the following js to hide and show my div

```<code>function myFunction(test) {
    var x = document.getElementById(test);

    if (x.style.display == "none") {
        //x.style.display = "block";
        x.style.setProperty("display", "block", "important")
    } else {
        //x.style.display = "none";
        x.style.setProperty("display", "none", "important")
    }
}
</code>```

I have all divs hidden on load using a class, which works, but you have to click a link twice to get it to unhide. How can I fix this to unhide on the first click?

The page Im working on is here, you can click on any of the titles to expand some section. (Ignore the formatting, it's very much a work in progress.)

http://thinkularity.eth.link

答:
Your issue is the check before applying the style. On the first click, the element is set to display: none because on pageload, the element has no display property set, so when your code checks if (x.style.display == "none"), it gets false - so it sets it to display: none. Using the style property of a Node references the actual style property of the HTML element, and does not include CSS properties.

I would personally create two classes, .hidden and .visible, and use Node.classList.toggle to toggle the element class, but your approach works too.

We can change your if / else to a switch/case (or if / else if / else) to set a default action if an element has no style.display property set - instead of hiding it by default, which is what was happening here, we will set display: block by default.

function toggleHide(test) {
  var x = document.getElementById(test);

  var newValue;
  var visible = "block";
  var hidden = "none";

  switch(x.style.display) {
    case hidden:
      // show if hidden
      newValue = visible;
      break;

    case visible:
      // hide if visible
      newValue = hidden;
      break;

    default:
      // visible if style.display not set yet
      newValue = visible;
      break;
  }

  // clear out style.display
  x.style.setProperty("display", "");
  // set new value
  x.style.setProperty("display", newValue);
}

// call toggleHide on header click
document.getElementById("header").addEventListener("click",
  e => toggleHide("abc")
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown {
  display: none;
}</code>```

Click me

This is hidden by default
```

Body:
I am using the following js to hide and show my div

function myFunction(test) {
    var x = document.getElementById(test);

    if (x.style.display == "none") {
        //x.style.display = "block";
        x.style.setProperty("display", "block", "important")
    } else {
        //x.style.display = "none";
        x.style.setProperty("display", "none", "important")
    }
}

I have all divs hidden on load using a class, which works, but you have to click a link twice to get it to unhide. How can I fix this to unhide on the first click?

The page Im working on is here, you can click on any of the titles to expand some section. (Ignore the formatting, it's very much a work in progress.)

http://thinkularity.eth.link

Body:
Your issue is the check before applying the style. On the first click, the element is set to display: none because on pageload, the element has no display property set, so when your code checks if (x.style.display == "none"), it gets false - so it sets it to display: none. Using the style property of a Node references the actual style property of the HTML element, and does not include CSS properties.

I would personally create two classes, .hidden and .visible, and use Node.classList.toggle to toggle the element class, but your approach works too.

We can change your if / else to a switch/case (or if / else if / else) to set a default action if an element has no style.display property set - instead of hiding it by default, which is what was happening here, we will set display: block by default.

function toggleHide(test) {
  var x = document.getElementById(test);

  var newValue;
  var visible = "block";
  var hidden = "none";

  switch(x.style.display) {
    case hidden:
      // show if hidden
      newValue = visible;
      break;

    case visible:
      // hide if visible
      newValue = hidden;
      break;

    default:
      // visible if style.display not set yet
      newValue = visible;
      break;
  }

  // clear out style.display
  x.style.setProperty("display", "");
  // set new value
  x.style.setProperty("display", newValue);
}

// call toggleHide on header click
document.getElementById("header").addEventListener("click",
  e => toggleHide("abc")
);

.dropdown {
  display: none;
}

<h1 id="header">Click me</h1>
<p id="abc" class="dropdown">This is hidden by default</p>


问:
Declaring an int in C++ with <<
Can someone explain to me what this declaration means in C++; I have never seen something declared like this, and was just confused on what it meant and how it works:

```<code>int ix((dx > 0) - (dx < 0));
</code>```

Same with this declaration, too:

```<code>int error(dy - (dx >> 1));
</code>```

答:
By default when you write something like int var; and int var = int(); in C++, the value of var will be uninitialized in the first case and will be set to zero in the second.

The lines of your example are the same as:

```<code>int ix = (dx > 0) - (dx < 0);
int error = dy - (dx >> 1);
</code>```

Also,
dx > 0 and dx < 0 are either 0 or 1, and dx >> 1 divides dx by 2.

In the line: int ix((dx > 0) - (dx < 0));

ix =  1  if dx > 0

ix =  0  if dx = 0

ix = -1  if dx < 0

Title: Declaring an int in C++ with <<

Body:
Can someone explain to me what this declaration means in C++; I have never seen something declared like this, and was just confused on what it meant and how it works:

int ix((dx > 0) - (dx < 0));

Same with this declaration, too:

int error(dy - (dx >> 1));

Body:
By default when you write something like int var; and int var = int(); in C++, the value of var will be uninitialized in the first case and will be set to zero in the second.

The lines of your example are the same as:

int ix = (dx > 0) - (dx < 0);
int error = dy - (dx >> 1);

Also,
dx > 0 and dx < 0 are either 0 or 1, and dx >> 1 divides dx by 2.

In the line: int ix((dx > 0) - (dx < 0));

ix =  1  if dx > 0

ix =  0  if dx = 0

ix = -1  if dx < 0


问:
Can't see value from API in b-form-select - Vue.js
I use API fro getting users. And i want bind ths users to b-form-select (bootstrap-vue). But after request i see "null" in b-form-select. My request

```<code>getAllUsers() {
                axios.get('/GetUsers')
                    .then(res => {
                        this.funds = res.data
                        console.log(this.options1)
                    })
            }
</code>```

And form for show data

```<code><b-form-select
                        id="input-3"
                        v-model="userSelect"
                        :options="funds"
                        required
                ></b-form-select>
</code>```

But if i use

```<code><select v-model="userSelect" class="form-control">
                <option v-for="user in funds" :key="user.id" :value="user">{{user.name }} {{user.id }}</option>
            </select>
</code>```

I see my users. Why bootstrap-vue can't show my data?

答:
b--form-select takes value as a default field for value attribute from your options and text field as a label.

If you want to customize the field property names (for example using name field for display text) you can easily change them by setting the text-field, html-field, value-field, and disabled-field props to a string that contains the property name you would like to use:

```<code><b-form-select
       id="input-3"
        v-model="userSelect"
        :options="funds"
       value-field="name"
      text-field="name"
       required
></b-form-select>
</code>```

Body:
I use API fro getting users. And i want bind ths users to b-form-select (bootstrap-vue). But after request i see "null" in b-form-select. My request

getAllUsers() {
                axios.get('/GetUsers')
                    .then(res => {
                        this.funds = res.data
                        console.log(this.options1)
                    })
            }

And form for show data

But if i use

<select v-model="userSelect" class="form-control">
                <option v-for="user in funds" :key="user.id" :value="user">{{user.name }} {{user.id }}</option>
            </select>

I see my users. Why bootstrap-vue can't show my data?

Body:
b--form-select takes value as a default field for value attribute from your options and text field as a label.

If you want to customize the field property names (for example using name field for display text) you can easily change them by setting the text-field, html-field, value-field, and disabled-field props to a string that contains the property name you would like to use:

<b-form-select
       id="input-3"
        v-model="userSelect"
        :options="funds"
       value-field="name"
      text-field="name"
       required
></b-form-select>


问:
Regex capture all matches between each set of delimiters
I need to find all matches in a string that exist between a set of delimiters.

For example, if I have the string The #quick# brown fox #jumped# over the lazy #dog#., I need to get the matches quick, jumped and dog.

I should only get matches that:
 - do not contain the delimiter/  (e.g. quick vs #quick#).
 - are between sets of delimiters.  That is to say delimiters 1 and 2 are a set, as are delimiters 3 and 4.  I should end up with quick, but not brown fox.

Here's the regex I have thus far:  (?<=\#)(.*?)(?=\#).  It meets my first criteria, but not my second.

Here is is on on regex101.com:
https://regex101.com/r/bD5mo0/1/

So my question is, how do I get regex to ignore matches between sets?  That is to say do match between the first and second delimiter, but not between the second and third.

I know changing the second delimiter to be different than the first will solve this, but the strings I'm regex'ing are coming out of the database, so I'd rather not alter them.

答:
If you want to capture string between a pair of #s only then it is better to use this regex with a capture group:

```<code>/#([^#]*)#/
</code>```

Updated RegEx Demo

You need to avoid using zero width look arounds for this regex as we need to match #s as well while moving ahead in inout.

Body:
If you want to capture string between a pair of #s only then it is better to use this regex with a capture group:

/#([^#]*)#/

Updated RegEx Demo

You need to avoid using zero width look arounds for this regex as we need to match #s as well while moving ahead in inout.


问:
How to read the openssl alert messages?
I am trying to read OpenSSL alert messages programmatically, but can't find out the way how to do it. The OpenSSL API provides functions like:

```<code>const char *SSL_alert_type_string(int value);
const char *SSL_alert_type_string_long(int value);

const char *SSL_alert_desc_string(int value);
const char *SSL_alert_desc_string_long(int value);
</code>```

but there is no info where to get the "int value" from.

For example when the TLS conenction resets from the reason of expired certificate, there is an alert (45). How to receive this alert number, so I could use the above API to print a message?

答:
You can obtain the alert information code by setting the callback function with void SSL_CTX_set_info_callback(SSL_CTX *ctx, void (*callback)()); and handling those codes however you would like.

More information on this feature is in the OpenSSL documentation. There is a complete callback function in the example section of this page. It's declaration is void apps_ssl_info_callback(SSL *s, int where, int ret), where ret is the code (given where is also appropriately set, please consult the Notes section for more thorough explanation).

Examples of registering the callback are in the s_client and s_server applications.

Title: How to read the openssl alert messages?

Body:
I am trying to read OpenSSL alert messages programmatically, but can't find out the way how to do it. The OpenSSL API provides functions like:

const char *SSL_alert_type_string(int value);
const char *SSL_alert_type_string_long(int value);

const char *SSL_alert_desc_string(int value);
const char *SSL_alert_desc_string_long(int value);

but there is no info where to get the "int value" from.

For example when the TLS conenction resets from the reason of expired certificate, there is an alert (45). How to receive this alert number, so I could use the above API to print a message?


问:
Best framework for targetting a wide range of mobile devices
I'm trying to build a mobile application on a client-server model where clients are people's mobile devices and the server is a PC - all connecting over bluetooth.

I'm expecting the client to be very thin - just enough to establish communications, display some text, and relay user input.

What's the best framework to develop in? I want the maximum possible device compatibility (so for example not just series 60 capabale devices) as opposed to cool features - but the ability to scale easily to colour devices or ones with higher dispaly resolutions would be nice.

答: Easiest way might be to write MIDP application that uses Bluetooth API. That covers widest range of devices with least effort. </p>

OwnerDisplayName: Mark Pim

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Virne


问:
Adding category method to NSObject, but getting warnings because it's not in the <NSObject> protocol when I call it
(I found some questions discussing the idea, but I didn't see a solution for my problem.)

I added this convenience method as a category to NSObject. (I've added other methods, so I'm still interested in an answer even if you disagree with this particular convenience method.)

```<code>@implementation NSObject (MyCategory)
- (void)performInvocationOnMainThread:(NSInvocation *)invocation waitUntilDone:(BOOL)waitForMainThread;
@end
</code>```

Then I have a protocol I defined:

```<code>@protocol MyDelegateProtocol <NSObject>
- (void)myDelegateProtocolMethod;
@end
</code>```

Then I declare the delegate as a property of my class that implements said protocol.

```<code>@property (nonatomic, assign) id <MyDelegateProtocol> delegate;
</code>```

But when I try to call the NSObject method I added in my category like so

```<code>NSInvocation *invocation = [self.delegate invocationForSelector:@selector(someSelector:withArg:)];
</code>```

I get this warning

```<code>'-performInvocationOnMainThread:waitUntilDone:' not found in protocol(s)
</code>```

If I cast my delegate as (NSObject *) then I don't get the warning. What am I doing wrong? It didn't seem like I could (or should?) add methods to an existing protocol without creating a "sub protocol" and using it from then on. (Which kind of defeats the point of adding methods to NSObject in mind.)

```<code>NSInvocation *invocation = [(NSObject *)self.delegate invocationForSelector:@selector(someSelector:withArg:)];
</code>```

答:
Your category extends the NSObject class, not the NSObject protocol. While the class now has the method, it's not defined as part of the protocol, hence the warning.

That's why typecasting to the NSObject * pointer type works; you're casting to the NSObject class type, rather than something like id<NSObject> which means an arbitrary Objective-C object that conforms to the NSObject protocol.

You'll have to make an intermediate protocol (or "sub protocol") that extends the NSObject protocol:

```<code>@protocol ExtendedNSObject <NSObject>
- (void)performInvocationOnMainThread:(NSInvocation *)invocation waitUntilDone:(BOOL)waitForMainThread;
@end
</code>```

Then have your delegate protocol extend that one instead:

```<code>@protocol MyDelegateProtocol <ExtendedNSObject>
- (void)myDelegateProtocolMethod;
@end
</code>```

If I'm not wrong, you can keep the existing NSObject (MyCategory) implementation, and they'll play nice together.

Body:
(I found some questions discussing the idea, but I didn't see a solution for my problem.)

I added this convenience method as a category to NSObject. (I've added other methods, so I'm still interested in an answer even if you disagree with this particular convenience method.)

@implementation NSObject (MyCategory)
- (void)performInvocationOnMainThread:(NSInvocation *)invocation waitUntilDone:(BOOL)waitForMainThread;
@end

Then I have a protocol I defined:

@protocol MyDelegateProtocol <NSObject>
- (void)myDelegateProtocolMethod;
@end

Then I declare the delegate as a property of my class that implements said protocol.

@property (nonatomic, assign) id <MyDelegateProtocol> delegate;

But when I try to call the NSObject method I added in my category like so

NSInvocation *invocation = [self.delegate invocationForSelector:@selector(someSelector:withArg:)];

I get this warning

'-performInvocationOnMainThread:waitUntilDone:' not found in protocol(s)

If I cast my delegate as (NSObject *) then I don't get the warning. What am I doing wrong? It didn't seem like I could (or should?) add methods to an existing protocol without creating a "sub protocol" and using it from then on. (Which kind of defeats the point of adding methods to NSObject in mind.)

NSInvocation *invocation = [(NSObject *)self.delegate invocationForSelector:@selector(someSelector:withArg:)];

Body:
Your category extends the NSObject class, not the NSObject protocol. While the class now has the method, it's not defined as part of the protocol, hence the warning.

That's why typecasting to the NSObject * pointer type works; you're casting to the NSObject class type, rather than something like id<NSObject> which means an arbitrary Objective-C object that conforms to the NSObject protocol.

You'll have to make an intermediate protocol (or "sub protocol") that extends the NSObject protocol:

@protocol ExtendedNSObject <NSObject>
- (void)performInvocationOnMainThread:(NSInvocation *)invocation waitUntilDone:(BOOL)waitForMainThread;
@end

Then have your delegate protocol extend that one instead:

@protocol MyDelegateProtocol <ExtendedNSObject>
- (void)myDelegateProtocolMethod;
@end

If I'm not wrong, you can keep the existing NSObject (MyCategory) implementation, and they'll play nice together.


问:
query retrieve data
i have data in a table like this

```<code>insert into mytable (col1,col2,col3,col4) values(a,2,100,501);
insert into mytable (col1,col2,col3,col4) values(a,4,200,555);
insert into mytable (col1,col2,col3,col4) values(a,3,80,500);
insert into mytable (col1,col2,col3,col4) values(a,3,44,443);
</code>```

Now i want a one select to retrieve data like this:

amnt1 will assigned to col3 if col1=a and col2=2.

amnt2 will assigned to col3 if col1=a and col2=3 and col4=500.

Results:

```<code>| amnt1 | amnt2 |
|---------------|
|   100 |    80 |
</code>```

thnx

答: select * from mytable m where m.col3='amnt1' and m.clo1='a' and m.col2=2</p>

Title: query retrieve data

Body:
i have data in a table like this

insert into mytable (col1,col2,col3,col4) values(a,2,100,501);
insert into mytable (col1,col2,col3,col4) values(a,4,200,555);
insert into mytable (col1,col2,col3,col4) values(a,3,80,500);
insert into mytable (col1,col2,col3,col4) values(a,3,44,443);

Now i want a one select to retrieve data like this:

amnt1 will assigned to col3 if col1=a and col2=2.

amnt2 will assigned to col3 if col1=a and col2=3 and col4=500.

Results:

| amnt1 | amnt2 |
|---------------|
|   100 |    80 |

thnx


答:
Better if you create another class to show the element and toggle that class on each click using DOMTokenList.toggle():

The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.

Demo:

function myFunction(test) {
  var x = document.getElementById(test);
  x.classList.toggle('showElement');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.showNotes{
  display: none;
}
.showElement{
  display: block !important;
}</code>```

023 Autonomy Day

  This is my DIV element.

022 Skateboarding In An Embassy

  This is my DIV element.

```

Title: How to toggle a div that is hidden on page load

Body:
Better if you create another class to show the element and toggle that class on each click using DOMTokenList.toggle():

The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.

Demo:

function myFunction(test) {
  var x = document.getElementById(test);
  x.classList.toggle('showElement');
}

.showNotes{
  display: none;
}
.showElement{
  display: block !important;
}

<h2><a onclick="myFunction('e23')" href="#23">023 Autonomy Day</a></h2>
<div class="showNotes" id="e23">
  This is my DIV element.
</div>
<h2><a onclick="myFunction('e22')" href="#22">022 Skateboarding In An Embassy</a></h2>
<div class="showNotes" id="e22">
  This is my DIV element.
</div>


问:
Dax formula won't ignore the last dropdown filter in Power BI
I am working on a report in Power BI where I have 4 filters to sort the data, and for the report to function properly, the revenue formula needs to ignore the last filter (indicator) so that I can make a comparison. I have tried

```<code>Profit =
CALCULATE (
    [Caravan] + [PKW] + betrag[sleistung] + betrag[smaterial] + betrag[sumsatz],
    ALL ( table[indicator] )
)
</code>```

But it is not working. Any idea what could be the problem?

答:
For your calculation to ignore the filter completely, the ALL function has to be used in each individual measure as well. That is, all the following measures should be rewritten to ignore the filter:

Caravan

PKW

sleistung

smaterial

sumsatz

Once the filter is excluded in all these measures, the calculation should work as expected. Hope this helps.

Body:
I am working on a report in Power BI where I have 4 filters to sort the data, and for the report to function properly, the revenue formula needs to ignore the last filter (indicator) so that I can make a comparison. I have tried

Profit =
CALCULATE (
    [Caravan] + [PKW] + betrag[sleistung] + betrag[smaterial] + betrag[sumsatz],
    ALL ( table[indicator] )
)

But it is not working. Any idea what could be the problem?


问:
Getting back to a CSS position sticky element with JavaScript?
I have a page where all sections fill the entire screen and are positioned with CSS position: sticky; in order to achieve a layered effect. See here:

https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark

This all works great and as expected.

The problem comes however from navigating between these areas with JavaScript. If you try using the menu, you can see that the links will work on sections that we haven't fully gotten to yet (and therefore not "sticky") but does not allow you to "go back up" the page.

I believe this is an issue with el.getBoundingClientRect() once an element has become "sticky", its top value becomes essentially always zero.

Here I am using a small library called Jump.js to jump around but even in vanilla JS this issue would still be the same, as the problem is a result of the calculation from when the element becomes sticky.

Is there any way to find the original position for each section before it was sticky? At least that way I could navigate the user by setting the scroll position manually.

I am using Vue.js but that does not affect the issue at hand which is CSS and JS related.

App.vue

```<code><template>
  <main id="app">
    <ul class="menu">
      <li @click="goTo('A')">Section A</li>
      <li @click="goTo('B')">Section B</li>
      <li @click="goTo('C')">Section C</li>
      <li @click="goTo('D')">Section D</li>
      <li @click="goTo('E')">Section E</li>
    </ul>
    <SectionItem id="A" color="red"/>
    <SectionItem id="B" color="green"/>
    <SectionItem id="C" color="blue"/>
    <SectionItem id="D" color="orange"/>
    <SectionItem id="E" color="purple"/>
  </main>
</template>

<script>
import jump from "jump.js";
import SectionItem from "./components/SectionItem.vue";

export default {
  name: "App",
  components: {
    SectionItem
  },
  methods: {
    goTo(id) {
      jump(`#${id}`, {
        duration: 300
      });
    }
  }
};
</script>
</code>```

SectionItem.vue

```<code><template>
  <div :id="id" class="SectionItem" :style="styles">
    <p>I am section item: {{ id }}</p>
  </div>
</template>

<script>
export default {
  name: "SectionItem",
  props: {
    id: {
      type: String,
      required: true
    },
    color: {
      type: String,
      required: true
    }
  },
  computed: {
    styles() {
      return {
        backgroundColor: this.color
      };
    }
  }
};
</script>

<style>
.SectionItem {
  position: sticky;
  top: 0;
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  color: white;
  border: 10px solid white;
}
</style>
</code>```

I'm looking for any reasonable solutions that get get the auto-scrolling to work in both directions. Many thanks for your time.

答:
Here's how your goTo method should look:

```<code>goTo(id) {
  const el = document.querySelector(`#${id}`);
  el.style.position = "static";
  requestAnimationFrame(() => {
    jump(`#${id}`, {
      duration: 300
    });
    el.style.removeProperty('position');
  });
}
</code>```

See it here.

Code should be self evident: set element's position to static using inline style, so the calculation is done correctly and remove the inline style position attribute in the next animation frame, so the element displays as set by the rest of the app (in this case, by CSS). Since it only happens for a single frame, it's not perceptible to human eye.

Note: I just wrote something quickly, to demonstrate the fix - it can probably be written more "vue like" (consider using refs).

Another note: if you're uncomfortable with toggling the element's position for a frame and you want to do it in a less aggressive way (towards the rendered elements) another approach is to clone the entire dom (without events), and do the same thing I'm suggesting, but on the clone. Once you have the value, you can delete the clone and pass it to the actual page. Obviously, the clone should have position: absolute; width 100%; visibility: hidden; top: 0 and be a direct ancestor of . Overall I believe it would be heavier (in terms of memory usage), but with regards to the actual page it would be less aggressive (it would avoid any side effects) - all layout, painting and rendering would be done correctly (as if you scrolled). By side effects I mean edge cases, such as triggers to any potential listeners to viewport intersection, affix plugins, scroll listeners, etc...

Body:
I have a page where all sections fill the entire screen and are positioned with CSS position: sticky; in order to achieve a layered effect. See here:

https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark

This all works great and as expected.

The problem comes however from navigating between these areas with JavaScript. If you try using the menu, you can see that the links will work on sections that we haven't fully gotten to yet (and therefore not "sticky") but does not allow you to "go back up" the page.

I believe this is an issue with el.getBoundingClientRect() once an element has become "sticky", its top value becomes essentially always zero.

Here I am using a small library called Jump.js to jump around but even in vanilla JS this issue would still be the same, as the problem is a result of the calculation from when the element becomes sticky.

Is there any way to find the original position for each section before it was sticky? At least that way I could navigate the user by setting the scroll position manually.

I am using Vue.js but that does not affect the issue at hand which is CSS and JS related.

App.vue

<template>

Section A

Section B

Section C

Section D

Section E

    <SectionItem id="A" color="red"/>
    <SectionItem id="B" color="green"/>
    <SectionItem id="C" color="blue"/>
    <SectionItem id="D" color="orange"/>
    <SectionItem id="E" color="purple"/>

</template>

SectionItem.vue

<template>

I am section item: {{ id }}

</template>

I'm looking for any reasonable solutions that get get the auto-scrolling to work in both directions. Many thanks for your time.

Body:
Here's how your goTo method should look:

goTo(id) {
  const el = document.querySelector(`#${id}`);
  el.style.position = "static";
  requestAnimationFrame(() => {
    jump(`#${id}`, {
      duration: 300
    });
    el.style.removeProperty('position');
  });
}

See it here.

Code should be self evident: set element's position to static using inline style, so the calculation is done correctly and remove the inline style position attribute in the next animation frame, so the element displays as set by the rest of the app (in this case, by CSS). Since it only happens for a single frame, it's not perceptible to human eye.

Note: I just wrote something quickly, to demonstrate the fix - it can probably be written more "vue like" (consider using refs).

Another note: if you're uncomfortable with toggling the element's position for a frame and you want to do it in a less aggressive way (towards the rendered elements) another approach is to clone the entire dom (without events), and do the same thing I'm suggesting, but on the clone. Once you have the value, you can delete the clone and pass it to the actual page. Obviously, the clone should have position: absolute; width 100%; visibility: hidden; top: 0 and be a direct ancestor of <body>. Overall I believe it would be heavier (in terms of memory usage), but with regards to the actual page it would be less aggressive (it would avoid any side effects) - all layout, painting and rendering would be done correctly (as if you scrolled). By side effects I mean edge cases, such as triggers to any potential listeners to viewport intersection, affix plugins, scroll listeners, etc...


答:
var trackingNum = $(".number-string");
function toLink(elem,link){
  let l1 = elem.text();
  elem.replaceWith(`Click here`);
}
toLink(trackingNum,'http://example');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="number-string">
123456789
</div></code>```

Title: Getting value in div and changing to a link

Body:
I have a div that gets values from the database and prints them inside a div:

123456789

I'm hoping to pull that value inside .number-string and change that div to a link where the href would be "https://somelink.com/123456789"
All I have right now is

var getnumber = $('.number-string').text()

I can't figure out how to change that div and add in a variable to a link

Body:
var trackingNum = $(".number-string");
function toLink(elem,link){
  let l1 = elem.text();
  elem.replaceWith(`<a href="${link}/${l1}">Click here</a>`);
}
toLink(trackingNum,'http://example');

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="number-string">
123456789
</div>


问:
BDE administrator and Paradox 11
I've just upgraded from Windows 7 to windows 10. I used to use Paradox 5 with BDE administrator and things worked fine. However Paradox 5 didn't work with windows 10, so I upgraded it to Paradox 11. That's the context for what I'm going to ask next:

I'm trying to get Paradox to connect correctly to my BDE directory. I set a native configuration driver for paradox to a network folder through the BDE administrator, but when I open paradox and look in Settings>Preferences>BDE, the network control file directory is set to a generic folder C:\PROGRA~3\BORLAND\NETDIR\ instead of the network drive I defined in BDE administrator.

Is there some way to get this to work correctly, or force the network control file directory directly in Paradox? There's no options to edit it from the Preferences menu in the BDE subtab. I'm unable to use my queries unless this gets set correctly.

答:
The best way is to load the odapi/Idapi/bde configuration file from the icon you use to start paradox. This allows you to save a configuration which has the network path stored for the net directory

The command line option to add is E.g.
-o x:\yourpath\bde.cfg

Which points to the file you saved from the bde administrator.

I’m guessing your on 64 bit windows which causes a few issues for paradox. Basically the registry entries for bde are not in the expected place in 64 bit windows. There is also a slight problem in the it gets installed into program files x86. This can be fixed by a few Mklink commands to symbolic link to x86 folders to the program files folders.

Edit: forgot to add that paradox 5 is a 16 bit app which is why it does not work in 64 bit windows.

Title: BDE administrator and Paradox 11


问:
Plot points from one df, plot errorbar from another
Raw data looks like:

```<code>Restaurant     Question               rating

McDonalds      How was the food?      5
McDonalds      How were the drinks?   3
McDonalds      How were the workers?  2
Burger_King    How was the food?      1
Burger_King    How were the drinks?   3
Burger_King    How were the workers?  4
</code>```

Averages looks like:

```<code>Question              average_rating    error
How was the food?     3.13              0.7
How were the drinks?  2.37              0.56
</code>```

How do I make a plot of points (x = question, y = rating, fill = restaurant) with the raw data, then plot the error bars (ymin/ymax = average_rating ± error) on top of it?

tribbles for convenience:

```<code>tribble(
  ~restaurant, ~question,  ~rating,
  "McDonalds", "How was the food?", 5,
  "McDonalds", "How were the drinks?", 3,
  "McDonalds", "How were the drinks?", 2,
  "BurgerKing", "How was the food?", 1,
  "BurgerKing", "How were the drinks?", 3,
  "BurgerKing", "How were the drinks?", 4
)
</code>```

```<code>tribble(
  ~question, ~average_rating, ~error,
  "How was the food?", 3.13, 0.7,
  "How were the drinks?", 2.37, 0.56
)
</code>```

答:
Your desired output is not in good agreement with your current dataframes. Because, your second dataframe contains average rating per restaurant and not per question (as outlined by @StupidWolf). So, either, you want to plot with restaurant in x axis and it will be easy to do, or you need to merge both dataframes and set Average_rating as a discrete value of the variable question.

I do the following for the second option:

library(dplyr)
df2 %>% mutate(question = "Average_rating") %>%
  rename(rating = average_rating) %>% full_join(df1,.) %>%
  mutate(restaurant = sub("BurgerKing","Burger_King",restaurant))
Joining, by = c("restaurant", "question", "rating")
# A tibble: 8 x 4
  restaurant  question             rating error
  <chr>       <chr>                 <dbl> <dbl>
1 McDonalds   How was the food?      5    NA
2 McDonalds   How were the drinks?   3    NA
3 McDonalds   How were the drinks?   2    NA
4 Burger_King How was the food?      1    NA
5 Burger_King How were the drinks?   3    NA
6 Burger_King How were the drinks?   4    NA
7 McDonalds   Average_rating         3.13  0.7
8 Burger_King Average_rating         2.37  0.56
```

<p>Then, if you want to add the plot, you can do the following:</p>

<pre class="lang-r prettyprint-override"><code>library(ggplot2)
library(dplyr)
df2 %>% mutate(question = "Average_rating") %>%
  rename(rating = average_rating) %>% full_join(df1,.) %>%
  mutate(restaurant = sub("BurgerKing","Burger_King",restaurant)) %>%
  ggplot(aes(x = question, y= rating, color = restaurant))+
  geom_point(position = position_dodge(0.9))+
  geom_errorbar(aes(ymin = rating-error, ymax = rating+error), width = 0.1, position = position_dodge(0.9))
</code>```

EDIT: Ploting error means per questions

With your new dataframe with the average rate per question, you can use geom_pointrange as follow:

ggplot(df1, aes(x = question, y = rating, color = restaurant))+
  geom_jitter(width = 0.2)+
  geom_pointrange(inherit.aes = FALSE,
                  data = df3,
                  aes(x = question,
                      y = average_rating,
                      ymin = average_rating-error,
                      ymax = average_rating+error))
```

Does it answer your question ?

Body:
Raw data looks like:

Restaurant     Question               rating

McDonalds      How was the food?      5
McDonalds      How were the drinks?   3
McDonalds      How were the workers?  2
Burger_King    How was the food?      1
Burger_King    How were the drinks?   3
Burger_King    How were the workers?  4

Averages looks like:

Question              average_rating    error
How was the food?     3.13              0.7
How were the drinks?  2.37              0.56

How do I make a plot of points (x = question, y = rating, fill = restaurant) with the raw data, then plot the error bars (ymin/ymax = average_rating ± error) on top of it?

tribbles for convenience:

tribble(
  ~restaurant, ~question,  ~rating,
  "McDonalds", "How was the food?", 5,
  "McDonalds", "How were the drinks?", 3,
  "McDonalds", "How were the drinks?", 2,
  "BurgerKing", "How was the food?", 1,
  "BurgerKing", "How were the drinks?", 3,
  "BurgerKing", "How were the drinks?", 4
)

tribble(
  ~question, ~average_rating, ~error,
  "How was the food?", 3.13, 0.7,
  "How were the drinks?", 2.37, 0.56
)

Body:
Your desired output is not in good agreement with your current dataframes. Because, your second dataframe contains average rating per restaurant and not per question (as outlined by @StupidWolf). So, either, you want to plot with restaurant in x axis and it will be easy to do, or you need to merge both dataframes and set Average_rating as a discrete value of the variable question.

I do the following for the second option:

library(dplyr)
df2 %>% mutate(question = "Average_rating") %>%
  rename(rating = average_rating) %>% full_join(df1,.) %>%
  mutate(restaurant = sub("BurgerKing","Burger_King",restaurant))
Joining, by = c("restaurant", "question", "rating")
# A tibble: 8 x 4
  restaurant  question             rating error
  <chr>       <chr>                 <dbl> <dbl>
1 McDonalds   How was the food?      5    NA
2 McDonalds   How were the drinks?   3    NA
3 McDonalds   How were the drinks?   2    NA
4 Burger_King How was the food?      1    NA
5 Burger_King How were the drinks?   3    NA
6 Burger_King How were the drinks?   4    NA
7 McDonalds   Average_rating         3.13  0.7
8 Burger_King Average_rating         2.37  0.56

Then, if you want to add the plot, you can do the following:

library(ggplot2)
library(dplyr)
df2 %>% mutate(question = "Average_rating") %>%
  rename(rating = average_rating) %>% full_join(df1,.) %>%
  mutate(restaurant = sub("BurgerKing","Burger_King",restaurant)) %>%
  ggplot(aes(x = question, y= rating, color = restaurant))+
  geom_point(position = position_dodge(0.9))+
  geom_errorbar(aes(ymin = rating-error, ymax = rating+error), width = 0.1, position = position_dodge(0.9))

EDIT: Ploting error means per questions

With your new dataframe with the average rate per question, you can use geom_pointrange as follow:

ggplot(df1, aes(x = question, y = rating, color = restaurant))+
  geom_jitter(width = 0.2)+
  geom_pointrange(inherit.aes = FALSE,
                  data = df3,
                  aes(x = question,
                      y = average_rating,
                      ymin = average_rating-error,
                      ymax = average_rating+error))

Does it answer your question ?


问:
pandas calculate time series resampling
If I had some random data created on a one hour sample..

```<code>import pandas as pd
import numpy as np
from numpy.random import randint

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)
</code>```

I can use the groupby to break out each day:

```<code>for idx, day in df.groupby(df.index.date):
    print(day)
</code>```

Now is there a way to calculate the time difference between daily min & max value based on the timestamp in hours? for each day record the daily min & max & time difference?

Title: pandas calculate time series resampling

Body:
If I had some random data created on a one hour sample..

import pandas as pd
import numpy as np
from numpy.random import randint

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)

I can use the groupby to break out each day:

for idx, day in df.groupby(df.index.date):
    print(day)

Now is there a way to calculate the time difference between daily min & max value based on the timestamp in hours? for each day record the daily min & max & time difference?

Body:
Alternatively, should you want to retain all columns with data frame output, consider merging on an aggregated dataset:

# ADJUST FOR DATETIME AND DATE AS COLUMNS
df = (df.reset_index()
        .assign(date = df.index.date)
     )

# AGGREGATION + MERGE ON MIN/MAX + CALCULATION
agg_df =  (df.groupby('date')['Random_Number']
             .agg(["min", "max"])
             .reset_index()
             .merge(df, left_on=['date', 'max'], right_on=['date', 'Random_Number'])
             .merge(df, left_on=['date', 'min'], right_on=['date', 'Random_Number'],
                    suffixes=['', '_min'])
             .assign(diff = lambda x: (x['index'] - x['index_min']) / pd.to_timedelta('1H'))
          )

print(agg_df.head(10))

#          date  min  max               index  Random_Number           index_min  Random_Number_min  diff
# 0  2018-10-09    1   94 2018-10-09 05:00:00             94 2018-10-09 09:00:00                  1  -4.0
# 1  2018-10-10   12   95 2018-10-10 20:00:00             95 2018-10-10 21:00:00                 12  -1.0
# 2  2018-10-11    5   97 2018-10-11 15:00:00             97 2018-10-11 19:00:00                  5  -4.0
# 3  2018-10-12    7   98 2018-10-12 18:00:00             98 2018-10-12 06:00:00                  7  12.0
# 4  2018-10-13    1   91 2018-10-13 22:00:00             91 2018-10-13 01:00:00                  1  21.0
# 5  2018-10-14    1   97 2018-10-14 10:00:00             97 2018-10-14 04:00:00                  1   6.0
# 6  2018-10-15    9   97 2018-10-15 06:00:00             97 2018-10-15 12:00:00                  9  -6.0
# 7  2018-10-16    3   95 2018-10-16 04:00:00             95 2018-10-16 22:00:00                  3 -18.0
# 8  2018-10-17    2   95 2018-10-17 13:00:00             95 2018-10-17 21:00:00                  2  -8.0
# 9  2018-10-18    1   91 2018-10-18 21:00:00             91 2018-10-18 12:00:00                  1   9.0


问:
When grouping a JSON array of objects by the first character in a value, how can I group all characters that start with a number into the same group?
I've been tinkering with an issue where I have some JSON data and I want to group the objects based off the first letter of their "Name" value.

I was able to accomplish this with an array sort function. But one thing I am also trying to accomplish is have it so that any item that starts with a number (or any non alphabetical value) should be grouped into a separate group.

Right now everything is grouped by Letter and number.

Here is some sample JSON:

```<code>[{
    "Id": 83107,
    "Name": "10-11",
},
{
    "Id": 83107,
    "Name": "Bill",
},
{
    "Id": 83107,
    "Name": "Jim",
},
{
    "Id": 83107,
    "Name": "7-11",
},
{
    "Id": 83107,
    "Name": "Walgreens",
},
{
    "Id": 83107,
    "Name": "Apple",
},
}]
</code>```

And here's the output I am getting:

```<code>{
   "1":[
      {
         "Id":83107,
         "Name":"10-11"
      }
   ],
   "7":[
      {
         "Id":83107,
         "Name":"7-11"
      }
   ],
   "A":[
      {
         "Id":83107,
         "Name":"Apple"
      }
   ],
   "B":[
      {
         "Id":83107,
         "Name":"Bill"
      }
   ],
   "J":[
      {
         "Id":83107,
         "Name":"Jim"
      }
   ],
   "W":[
      {
         "Id":83107,
         "Name":"Walgreens"
      }
   ]
}
</code>```

What I'd like to do is put all the non-alphabet values into their own group so they would all fall under a group named '#'

Here is the reduce function that I currently use:

```<code>var dataJSON = [{
        "Id": 83107,
        "Name": "10-11",
    },
    {
        "Id": 83107,
        "Name": "Bill",
    },
    {
        "Id": 83107,
        "Name": "Jim",
    },
    {
        "Id": 83107,
        "Name": "7-11",
    },
    {
        "Id": 83107,
        "Name": "Walgreens",
    },
    {
        "Id": 83107,
        "Name": "Apple",
    },
    }];

dataJSON.sort(function(a, b) {
  return a.Name[0].localeCompare(b.Name[0]);
});

var result = {};

for (var i = 0; i < dataJSON.length; i++) {
  var c = dataJSON[i].Name[0].toUpperCase();
  if (result[c] && result[c].length >= 0)

    result[c].push(dataJSON[i]);

  else {

    result[c] = [];
    result[c].push(dataJSON[i]);

  }
}

console.log(result);
</code>```

答:
You can just modify your code to check if the first letter of the name is a number then add it to the # group in your sorted data.

Your code would look  something like this

for (var i = 0; i < dataJSON.length; i++) {
  var c = dataJSON[i].Name[0];
  if(isNaN(parseInt(c))){
    if (result[c] && result[c].length >= 0){
      result[c].push(dataJSON[i]);
    } else {
      result[c] = [dataJSON[i]];
    }
  } else {
    if(result['#'] && result['#'].length >= 0){
      result['#'].push(dataJSON[i]);
    } else {
      result['#'] = [dataJSON[i]];
    }
  }
}
```

<h2>NOTE</h2>

<p>This will lead to <code>result</code> having the <code>#</code> key, but within that key the items will be sorted by the first digit of the number. So the object with the key <code>Name</code> as <code>"10-11"</code> will go before the object with the key <code>Name</code> as <code>"7-11"</code></p>

<p>Running my code with your <code>dataJSON</code> gives this <code>result</code></p>

<pre class="lang-js prettyprint-override"><code>{
  "#" : [
    {
      "Id": 83107,
      "Name": "10-11"
    },
    {
      "Id": 83107,
      "Name": "7-11"
    }
  ],
  "A" : [
    {
      "Id":83107,
      "Name":"Apple"
    }
   ],
   "B" : [
    {
      "Id":83107,
      "Name":"Bill"
    }
   ],
   "J" : [
    {
       "Id":83107,
       "Name":"Jim"
    }
   ],
   "W" : [
    {
       "Id":83107,
       "Name":"Walgreens"
    }
   ]
}
</code>```

Body:
I've been tinkering with an issue where I have some JSON data and I want to group the objects based off the first letter of their "Name" value.

I was able to accomplish this with an array sort function. But one thing I am also trying to accomplish is have it so that any item that starts with a number (or any non alphabetical value) should be grouped into a separate group.

Right now everything is grouped by Letter and number.

Here is some sample JSON:

[{
    "Id": 83107,
    "Name": "10-11",
},
{
    "Id": 83107,
    "Name": "Bill",
},
{
    "Id": 83107,
    "Name": "Jim",
},
{
    "Id": 83107,
    "Name": "7-11",
},
{
    "Id": 83107,
    "Name": "Walgreens",
},
{
    "Id": 83107,
    "Name": "Apple",
},
}]

And here's the output I am getting:

{
   "1":[
      {
         "Id":83107,
         "Name":"10-11"
      }
   ],
   "7":[
      {
         "Id":83107,
         "Name":"7-11"
      }
   ],
   "A":[
      {
         "Id":83107,
         "Name":"Apple"
      }
   ],
   "B":[
      {
         "Id":83107,
         "Name":"Bill"
      }
   ],
   "J":[
      {
         "Id":83107,
         "Name":"Jim"
      }
   ],
   "W":[
      {
         "Id":83107,
         "Name":"Walgreens"
      }
   ]
}

What I'd like to do is put all the non-alphabet values into their own group so they would all fall under a group named '#'

Here is the reduce function that I currently use:

var dataJSON = [{
        "Id": 83107,
        "Name": "10-11",
    },
    {
        "Id": 83107,
        "Name": "Bill",
    },
    {
        "Id": 83107,
        "Name": "Jim",
    },
    {
        "Id": 83107,
        "Name": "7-11",
    },
    {
        "Id": 83107,
        "Name": "Walgreens",
    },
    {
        "Id": 83107,
        "Name": "Apple",
    },
    }];

dataJSON.sort(function(a, b) {
  return a.Name[0].localeCompare(b.Name[0]);
});

var result = {};

for (var i = 0; i < dataJSON.length; i++) {
  var c = dataJSON[i].Name[0].toUpperCase();
  if (result[c] && result[c].length >= 0)

    result[c].push(dataJSON[i]);

  else {

    result[c] = [];
    result[c].push(dataJSON[i]);

  }
}

console.log(result);

Body:
You can just modify your code to check if the first letter of the name is a number then add it to the # group in your sorted data.

Your code would look  something like this

for (var i = 0; i < dataJSON.length; i++) {
  var c = dataJSON[i].Name[0];
  if(isNaN(parseInt(c))){
    if (result[c] && result[c].length >= 0){
      result[c].push(dataJSON[i]);
    } else {
      result[c] = [dataJSON[i]];
    }
  } else {
    if(result['#'] && result['#'].length >= 0){
      result['#'].push(dataJSON[i]);
    } else {
      result['#'] = [dataJSON[i]];
    }
  }
}

NOTE

This will lead to result having the # key, but within that key the items will be sorted by the first digit of the number. So the object with the key Name as "10-11" will go before the object with the key Name as "7-11"

Running my code with your dataJSON gives this result

{
  "#" : [
    {
      "Id": 83107,
      "Name": "10-11"
    },
    {
      "Id": 83107,
      "Name": "7-11"
    }
  ],
  "A" : [
    {
      "Id":83107,
      "Name":"Apple"
    }
   ],
   "B" : [
    {
      "Id":83107,
      "Name":"Bill"
    }
   ],
   "J" : [
    {
       "Id":83107,
       "Name":"Jim"
    }
   ],
   "W" : [
    {
       "Id":83107,
       "Name":"Walgreens"
    }
   ]
}


问:
How can I replace the char '2' in a string with the string "to" in Java?
I am unsure which version of Java I am using, I am using the CodeHS IDE. I am trying to write a function that "fixes the grammar" in a given string. All the method needs to do is replace all of the 2s with to's. Here is my code:  </p>

```<code>public String useProperGrammar(String text) {
   String fixedString = new String();
for (int i = 0; i < text.length(); i++) {
    fixedString += text.charAt(i);
    if (text.charAt(i) == '2') {

     fixedString = text.substring(0, i) + text.substring(i + 1);

      fixedString += "to";
    }
} return fixedString; }
</code>```

答:
Use the String.replace() method.

```<code>
        String str = "this is 2";
        str = str.replace('2'+"", "to");
        System.out.println(str);

</code>```

If you append an empty string "" to the character it will convert it to a string and allow the replace to work.

Body:
I am unsure which version of Java I am using, I am using the CodeHS IDE. I am trying to write a function that "fixes the grammar" in a given string. All the method needs to do is replace all of the 2s with to's. Here is my code:

public String useProperGrammar(String text) {
   String fixedString = new String();
for (int i = 0; i < text.length(); i++) {
    fixedString += text.charAt(i);
    if (text.charAt(i) == '2') {

     fixedString = text.substring(0, i) + text.substring(i + 1);

      fixedString += "to";
    }
} return fixedString; }

Body:
Use the String.replace() method.

        String str = "this is 2";
        str = str.replace('2'+"", "to");
        System.out.println(str);

If you append an empty string "" to the character it will convert it to a string and allow the replace to work.


问:
ActiveStorage - get image dimensions after upload
I am using Rails + ActiveStorage to upload image files, and would like to save the width and height in the database after upload. However, I'm having trouble finding any examples of this anywhere.

This is what I've cobbled together from various API docs, but just end up with this error: private method 'open' called for #<String:0x00007f9480610118>. Replacing blob with image.file causes rails to log "Skipping image analysis because ImageMagick doesn't support the file" (https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/analyzer/image_analyzer.rb#L39).

Code:

```<code>class Image < ApplicationRecord
  after_commit { |image| set_dimensions image }

  has_one_attached :file

  def set_dimensions(image)
    if (image.file.attached?)
      blob = image.file.download

      # error: private method `open' called for #<String:0x00007f9480610118>
      meta = ActiveStorage::Analyzer::ImageAnalyzer.new(blob).metadata
    end
  end
end
</code>```

This approach is also problematic because after_commit is also called on destroy.

TLDR: Is there a "proper" way of getting image metadata immediately after upload?

答:
Answering own question: my original solution was close, but required ImageMagick to be installed (it wasn't, and the error messages did not point that out). This was my final code:

class Image < ApplicationRecord
  attr_accessor :skip_set_dimensions
  after_commit ({unless: :skip_set_dimensions}) { |image| set_dimensions image }

  has_one_attached :file

  def set_dimensions(image)
    if (Image.exists?(image.id))
      if (image.file.attached?)
        meta = ActiveStorage::Analyzer::ImageAnalyzer.new(image.file).metadata

        image.width = meta[:width]
        image.height = meta[:height]
      else
        image.width = 0
        image.height = 0
      end

      image.skip_set_dimensions = true
      image.save!
    end
  end
end
```

I also used this technique to skip the callback on save!, preventing an infinite loop.

Body:
I am using Rails + ActiveStorage to upload image files, and would like to save the width and height in the database after upload. However, I'm having trouble finding any examples of this anywhere.

This is what I've cobbled together from various API docs, but just end up with this error: private method 'open' called for #<String:0x00007f9480610118>. Replacing blob with image.file causes rails to log "Skipping image analysis because ImageMagick doesn't support the file" (https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/analyzer/image_analyzer.rb#L39).

Code:

class Image < ApplicationRecord
  after_commit { |image| set_dimensions image }

  has_one_attached :file

  def set_dimensions(image)
    if (image.file.attached?)
      blob = image.file.download

      # error: private method `open' called for #<String:0x00007f9480610118>
      meta = ActiveStorage::Analyzer::ImageAnalyzer.new(blob).metadata
    end
  end
end

This approach is also problematic because after_commit is also called on destroy.

TLDR: Is there a "proper" way of getting image metadata immediately after upload?

Body:
Answering own question: my original solution was close, but required ImageMagick to be installed (it wasn't, and the error messages did not point that out). This was my final code:

class Image < ApplicationRecord
  attr_accessor :skip_set_dimensions
  after_commit ({unless: :skip_set_dimensions}) { |image| set_dimensions image }

  has_one_attached :file

  def set_dimensions(image)
    if (Image.exists?(image.id))
      if (image.file.attached?)
        meta = ActiveStorage::Analyzer::ImageAnalyzer.new(image.file).metadata

        image.width = meta[:width]
        image.height = meta[:height]
      else
        image.width = 0
        image.height = 0
      end

      image.skip_set_dimensions = true
      image.save!
    end
  end
end

I also used this technique to skip the callback on save!, preventing an infinite loop.