问:
Is there a way to fix permission denied error with pytesseract and python?
I'm trying to create a client/server program in python that sends recognized text from a picture and useful information about it to a client which will then display it on an oled display. But the problem comes on the server side of the program when it tries to use tesseract I get the following error:
PermissionError: [WinError 5] Access is  denied:'C:\Users\BradS\AppData\Local\Temp\tess_97901m0e'. I am using tesseract 5.0.0 with OpenCV 4.2.0 and python 3.8. I have tried creating a new account uninstalling and reinstalling but nothing seems to work, and yes I am administrator. (Server code below)</p>

```<code>import cv2
import pytesseract
from PIL import Image
import numpy as np
from pytesseract import Output
import wolframalpha
import socket
import datetime
import time
import sys

app_id = "********************"
img_counter = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = socket.gethostname()
print(host)
port = 60539
s.bind((host, port))
s.listen(5)

cam = cv2.VideoCapture(0)

while True:
  c, addr = s.accept()
  print (f'Got connection from: {addr}')
  break

while True:
  ret, frame = cam.read()
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

  def remove_noise(gray):
    return cv2.medianBlur(gray, 5)

  def thresholding(gray):
    return cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

  def dilate(image):
    kernel = np.ones((5, 5), np.uint8)
    return cv2.dilate(image, kernel, iterations=1)

  cv2.imshow("test", gray)
  if not ret:
    break
  k = cv2.waitKey(1)

  if k % 256 == 27:
    print("Escape hit, closing...")
    break
  elif k % 256 == 32:

    img_name = "frames_0.png"
    cv2.imwrite(img_name, gray)
    print("frames_0.png written!")
    img = cv2.imread('frames_0.png')
    cv2.destroyAllWindows()

    d = pytesseract.image_to_data(img, output_type = Output.DICT)

    n_boxes = len(d['text'])
    for i in range(n_boxes):
      if int(d['conf'][i]) > 60:
        (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])
        img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    cv2.imshow('img', img)
    cv2.waitKey(0)
cam.release()
cv2.destroyAllWindows()

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

image = cv2.imread('frames_0.png')

text = pytesseract.image_to_string(image)
print(text)
cv2.destroyAllWindows

c.send(bytes(text, "utf-8"))
print ("Message sent")

if len(text) <= 0:
  sys.exit()

elif len(text) >= 1:
  query = text
  client = wolframalpha.Client(app_id)
  res = client.query(query)
  print(res.results)
  answer = next(res.results).text
  print (answer)
  c.send(bytes(answer, "utf-8"))
  print("Second message sent")
  c.close()
</code>```

答:
By referring to https://stackoverflow.com/a/51869555/7961056, the author stated that even you run from Administrator, it may not solve the issue if the pip is installed inside another userspace. This is because Administrator doesn't own another's userspace directory, thus he can't see (go inside) the inside of the directory that is owned by somebody. Below is an exact solution.

```<code>python -m pip install -U pip --user //It solves in Windows. Note: You should provide --user option
</code>```

Hope this can help you.

Body:
I'm trying to create a client/server program in python that sends recognized text from a picture and useful information about it to a client which will then display it on an oled display. But the problem comes on the server side of the program when it tries to use tesseract I get the following error:
PermissionError: [WinError 5] Access is  denied:'C:\Users\BradS\AppData\Local\Temp\tess_97901m0e'. I am using tesseract 5.0.0 with OpenCV 4.2.0 and python 3.8. I have tried creating a new account uninstalling and reinstalling but nothing seems to work, and yes I am administrator. (Server code below)

import cv2
import pytesseract
from PIL import Image
import numpy as np
from pytesseract import Output
import wolframalpha
import socket
import datetime
import time
import sys

app_id = "********************"
img_counter = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = socket.gethostname()
print(host)
port = 60539
s.bind((host, port))
s.listen(5)

cam = cv2.VideoCapture(0)

while True:
  c, addr = s.accept()
  print (f'Got connection from: {addr}')
  break

while True:
  ret, frame = cam.read()
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

  def remove_noise(gray):
    return cv2.medianBlur(gray, 5)

  def thresholding(gray):
    return cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

  def dilate(image):
    kernel = np.ones((5, 5), np.uint8)
    return cv2.dilate(image, kernel, iterations=1)

  cv2.imshow("test", gray)
  if not ret:
    break
  k = cv2.waitKey(1)

  if k % 256 == 27:
    print("Escape hit, closing...")
    break
  elif k % 256 == 32:

    img_name = "frames_0.png"
    cv2.imwrite(img_name, gray)
    print("frames_0.png written!")
    img = cv2.imread('frames_0.png')
    cv2.destroyAllWindows()

    d = pytesseract.image_to_data(img, output_type = Output.DICT)

    n_boxes = len(d['text'])
    for i in range(n_boxes):
      if int(d['conf'][i]) > 60:
        (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])
        img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    cv2.imshow('img', img)
    cv2.waitKey(0)
cam.release()
cv2.destroyAllWindows()

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

image = cv2.imread('frames_0.png')

text = pytesseract.image_to_string(image)
print(text)
cv2.destroyAllWindows

c.send(bytes(text, "utf-8"))
print ("Message sent")

if len(text) <= 0:
  sys.exit()

elif len(text) >= 1:
  query = text
  client = wolframalpha.Client(app_id)
  res = client.query(query)
  print(res.results)
  answer = next(res.results).text
  print (answer)
  c.send(bytes(answer, "utf-8"))
  print("Second message sent")
  c.close()

Body:
By referring to https://stackoverflow.com/a/51869555/7961056, the author stated that even you run from Administrator, it may not solve the issue if the pip is installed inside another userspace. This is because Administrator doesn't own another's userspace directory, thus he can't see (go inside) the inside of the directory that is owned by somebody. Below is an exact solution.

python -m pip install -U pip --user //It solves in Windows. Note: You should provide --user option

Hope this can help you.


来源: stackexchange

问:
Firebase storage error 1200 over wifi only, LTE works perfectly
This error started to pop this week. It is really weird. Code is just a simple putdata on Firebase Storage to save an image. (Swift 5 // XCode 11.3.1)

```<code>    storageRef.putData(profileImageData, metadata: nil, completion: { (metadata, error) in
        if error != nil {
            print(error!)
            completion?(nil)
            return
        }

        storageRef.downloadURL(completion: { (url, error) in
            if error != nil {
                print(error!)
                completion?(nil)
                return
            }

            completion?(url?.absoluteString)
        })

    })
</code>```

Then what I get back over LTE is: Success.
What I get back over my home Wifi is:

2020-02-16 13:44:49.944697-0800 persona[17889:5050090] Task <0E3D8C0D-6B4C-43CF-B897-E549E8D5301E>.<2> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made.

Updates: Worked when tried on another Wifi. No configuration change was made on the original wifi.

答:
Couple of things that move the needle.

1) For reading from Firebase Storage: I've changed my URLSession.shared.dataTask to use KingFisher instead, this solved for reading.

2) Switching Wifi's seems to solve it too, but I hardly believe this is a sustainable answer.

Issue is caused by xFinity Comcast Advanced Security filter, Firebase team is working on it. Follow the thread on Firebase's Github here: https://github.com/firebase/firebase-ios-sdk/issues/4913

ContentLicense: CC BY-SA 4.0

Body:
This error started to pop this week. It is really weird. Code is just a simple putdata on Firebase Storage to save an image. (Swift 5 // XCode 11.3.1)

    storageRef.putData(profileImageData, metadata: nil, completion: { (metadata, error) in
        if error != nil {
            print(error!)
            completion?(nil)
            return
        }

        storageRef.downloadURL(completion: { (url, error) in
            if error != nil {
                print(error!)
                completion?(nil)
                return
            }

            completion?(url?.absoluteString)
        })

    })

Then what I get back over LTE is: Success.
What I get back over my home Wifi is:

2020-02-16 13:44:49.944697-0800 persona[17889:5050090] Task <0E3D8C0D-6B4C-43CF-B897-E549E8D5301E>.<2> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made.

Updates: Worked when tried on another Wifi. No configuration change was made on the original wifi.


问:
Putting finditer() output into an array
I'm trying to find the index of all "TRN" in a string, which I've done, but then I want to put all the indexes into an array, which I can't seem to do.

```<code>    import re

    string = 'a string with TRN, then another TRN'

    for match in re.finditer('TRN', string):
        spots = match.start()
        print(spots)
</code>```

Output is:

```<code>14
32
</code>```

The output i want is:

[14, 32]

I've tried putting it into array and append the output like this, but the result is NONE NONE.

```<code>    import re

    into_array = []

    string = 'a string with TRN, then another TRN'

    for match in re.finditer('TRN', string):
        spots = match.start()
        x = into_array.append(spots)
        print(x)
</code>```

Output is:

```<code>None
None
</code>```

Any help would be greatly appreciated.

答:
You're printing the output of append (which doesn't output anything, hence None), not spots like you want to.

import re

into_array = []

string = 'a string with TRN, then another TRN'

for match in re.finditer('TRN', string):
    spots = match.start()
    into_array.append(spots)
print(into_array)
```

Title: Putting finditer() output into an array

Body:
I'm trying to find the index of all "TRN" in a string, which I've done, but then I want to put all the indexes into an array, which I can't seem to do.

    import re

    string = 'a string with TRN, then another TRN'

    for match in re.finditer('TRN', string):
        spots = match.start()
        print(spots)

Output is:

14
32

The output i want is:

[14, 32]

I've tried putting it into array and append the output like this, but the result is NONE NONE.

    import re

    into_array = []

    string = 'a string with TRN, then another TRN'

    for match in re.finditer('TRN', string):
        spots = match.start()
        x = into_array.append(spots)
        print(x)

Output is:

None
None

Any help would be greatly appreciated.


问:
How to set featureCompatibilityVersion on secondary replica set member which does not startup due to this error?
I'm situation were I am trying to get a broken member of a replica set back online. I have followed the normal procedure of deleting the data in /data/db and trying to sync. Also tried to move all the data from one secondary to the other and restart mongo. Each time I get the standard error above complaining about compatibility issues. Now the servers are the same version 3.6. So why was this an issue?... Must be that the featureCompatibilityVersion=3.6 while on the other server are set to featureCompatibilityVersion=3.4 which they are. However to see this the server needs to startup but since it kept restarting I could not check that. So I removed it from the replica set started it up and seen it was set to featureCompatibilityVersion=3.6. So I changed this to 3.4 and started it up again while part of replica set but still had the same issue. How do I get round this?

The other servers have featureCompatibilityVersion=3.4 so if I was syncing correctly would the other server not pull in admin collection which would have featureCompatibilityVersion=3.4. So why does this keep complaining?
If not how do you change this on a server which does not startup? Is there something in mongo config I can set?

Thanks for the help in advance.

答:
here's probably not a helpful answer, just a sanity check: remove replSet parameter and spin up the mongod totally solo.... does that work ok?

I only suggest it cause I can't see what your issue is and maybe this would find something...wouldn't take long, may not help...   the versioning I don't quite get...


问:
Intl.NumberFormat String Currency before number
The following string return the value like: 938.173,00 euro. How to obtain the value like: Euro 938.173,00?

```<code>formattedValue = value.toLocaleString('it-IT', {currency: 'EUR', currencyDisplay: 'name', style: 'currency'});
</code>```

Thanks

答:
There doesn't seem to be any specific options in Intl to custom-prepend the currency. It is done automatically according to your locale. But, you could simply String.replace:

const value = 938173.00
const formattedValue = `euro ${value.toLocaleString('it-IT', {currency: 'EUR', currencyDisplay: 'name', style: 'currency'}).replace(" euro","")}`;
console.info(formattedValue);```

Body:
The following string return the value like: 938.173,00 euro. How to obtain the value like: Euro 938.173,00?

formattedValue = value.toLocaleString('it-IT', {currency: 'EUR', currencyDisplay: 'name', style: 'currency'});

Thanks


问:
Arrow keys type capital letters instead of moving the cursor
I've installed the latest vim using homebrew and also installed mac-vim from the google code homepage.
in mac-vim everything works fine. but when I run vim in terminal.app in mac and go to insert mode I'll get A B C D for arrow keys which is extremely annoying.

I googled it and tried all the solutions but nothing is working for me!

it gets intresting when I run vim with vim -u NONE -U NONE -N then the arrow keys start to function normally in insert mode.

my vimrc files are a clone of janus (from carlhuda)

do you have the same problem in terminal? is there a way to fix it in terminal.app?

答:
This works for me:

```<code>map ^[[A <up>
map ^[[B <down>
map ^[[C <right>
map ^[[D <left>
</code>```

To type the sequence for each arrow key, you need to press ctrl-v, then the arrow key.

For example, to type the first line:

m, a, p, space, ctrl-v, ←, space, <, u, p, >

This also might work:

```<code>set t_ku=^[[A
set t_kd=^[[B
set t_kr=^[[C
set t_kl=^[[D
</code>```

More information is available here.

ContentLicense: CC BY-SA 3.0

Body:
This works for me:

map ^[[A <up>
map ^[[B <down>
map ^[[C <right>
map ^[[D <left>

To type the sequence for each arrow key, you need to press ctrl-v, then the arrow key.

For example, to type the first line:

m, a, p, space, ctrl-v, ←, space, <, u, p, >

This also might work:

set t_ku=^[[A
set t_kd=^[[B
set t_kr=^[[C
set t_kl=^[[D

More information is available here.


问:
What does this mean in an argument type. What is it called?
I came across the following code

```<code> public static IMyQueries<T> Foo<T>(this ASet<T> items)
 {
           ...
 }
</code>```

My question is in the parameter of this function the keyword this is being used. Why is that ? From what I understand is that ASet is the typename which is templated. Why is the keyword this there. Can someone give a simple example of why this is employed as a parameter?

答:
It shows that the function is extension for ASet type.

An example for string extension could be:

```<code>    public static class Extensions
    {
        public static string SayHiExtension(this string to)
        {
            return $"Hello {to}";
        }

        public static string SayHi(string to)
        {
            return $"Hello {to}";
        }
    }
</code>```

And usage difference:

```<code>  string name = "World";

   // Extension
  string output = name.SayHiExtension();

  // Without extension
  output = Extensions.SayHi(name);
</code>```

Body:
I came across the following code

 public static IMyQueries<T> Foo<T>(this ASet<T> items)
 {
           ...
 }

My question is in the parameter of this function the keyword this is being used. Why is that ? From what I understand is that ASet is the typename which is templated. Why is the keyword this there. Can someone give a simple example of why this is employed as a parameter?

Body:
It shows that the function is extension for ASet type.

An example for string extension could be:

    public static class Extensions
    {
        public static string SayHiExtension(this string to)
        {
            return $"Hello {to}";
        }

        public static string SayHi(string to)
        {
            return $"Hello {to}";
        }
    }

And usage difference:

  string name = "World";

   // Extension
  string output = name.SayHiExtension();

  // Without extension
  output = Extensions.SayHi(name);


问:
Many-to-many relationship between Django User, Permissions, and another entity
Consider a Django web app for CompanyXYZ that provides goods and services to many organizations.  Users of the app will be affiliated with one or more of those organizations, and have different roles (and be permitted access to different data) within each.  So, imagine a schema like this:

```<code>Users>---UserOrg----<Org
             V
             |
          UserOrgPermissions
             |
             ^
           Permissions

</code>```

Permissions relate to services provided by the company, and in general look like:  “Can order X”, “Can view X orders”, “Can order Y”, “Can view Y orders”, “Can order Z”...etc.  Users should be able to log on to CompanyXYZ’s site once, and then choose from among his/her affiliated organizations to view summary data and/or place orders, depending on his/her permissions at a given organization.

From an admin perspective, I need to be able to create organizations, create users, assign users to organizations, and assign permissions to users for each of his/her organizations.

I’m fairly new to Django, so I'm not sure if this is even doable. How would I start?

答: Django provides you almost all for you needs. Try to learn about users first. Avoid to create users from scrach, you can simple use or customize the Django User models. then, permissions and organizations can be solved with groups.</p>

Body:
Consider a Django web app for CompanyXYZ that provides goods and services to many organizations.  Users of the app will be affiliated with one or more of those organizations, and have different roles (and be permitted access to different data) within each.  So, imagine a schema like this:

Users>---UserOrg----<Org
             V
             |
          UserOrgPermissions
             |
             ^
           Permissions

Permissions relate to services provided by the company, and in general look like:  “Can order X”, “Can view X orders”, “Can order Y”, “Can view Y orders”, “Can order Z”...etc.  Users should be able to log on to CompanyXYZ’s site once, and then choose from among his/her affiliated organizations to view summary data and/or place orders, depending on his/her permissions at a given organization.

From an admin perspective, I need to be able to create organizations, create users, assign users to organizations, and assign permissions to users for each of his/her organizations.

I’m fairly new to Django, so I'm not sure if this is even doable. How would I start?


问:
In Azure DevOps release pipeline is it possible to request approval conditionally?
We use Azure DevOps Server 2019 (on-prem). I.e. no unified pipelines, no YAML release pipeline.

The scenario is this:

Stage A invokes terraform plan to produce a plan file

Stage B takes the plan file (somehow, see In Azure DevOps Server 2019 (on-prem) release pipeline how can one stage pass a file to another stage?) and runs terraform apply.

There is post-deployment approval on Stage A (and/or pre-deployment on Stage B) to let human inspect the plan before applying it.

Now, it does not make sense to request human approval always. We can inspect the plan automatically and request approval only if the plan contains destruction of stateful resources. The scripting code is not a problem, but how to request approval conditionally?

答:
Currently there isn't such a feature to approve the stages conditionally. I don't think we can achieve that based on current features.

There's already a suggestion ticket submitted here : Conditional deployment approvals, you can go and vote it up to help achieve that in future release.

However we can extend the condition by using approvals and gates to control your deployments, please check it.
Hope that helps.


问:
How to set UVs of a quad containing a non-square and non-power-of-two RenderTexture?
I want to render something manually using APIs like Graphics.DrawMeshNow().

Now I need to draw a RenderTexture using a quad mesh. This RenderTexture is non-square and non-power-of-two, for example 1901 x 995.

I don't know how to set the UVs for the quad in this situation.

Will this kind of texture internally be padded to 2048 x 2048?

Do I need to calculate the relative position of the real content in the padded texture, using (0,0), (1901/2048, 0), (1901/2048, 995/2048), (0, 995/2048) as the quad's UV?

Or should I ignore this kind of thing and just set UVs to (0,0), (1,0), (1,1), (0,1)?

Or is this a more complex thing?

答: You should ignore this kind of thing and just set UVs to (0,0), (1,0), (1,1), (0,1).</p>


问:
How to authorize an API Gateway Endpoint for users logged in with cognito and users not logged in
My question is about how I should secure an API Gateway Endpoint.

I'm currently playing around with a web app, and I'm using API Gateway and AWS cognito.

I'm using aws cognito to manage users that sign up.

However, not all endpoints require a user to be signedup/loggedin to get access to it. There are some endpoints that will return different payloads depending on whether the user is signedup/loggedin.
For example if a user is signed in then they will see there message inbox on the page, however if the user is not signed in they will just see the content of the page.  Similar to how twitter or facebook does it.

What is the best way to secure these types of endpoints.
If I use aws_iam to secure it does that mean that any user that hasn't signed up can not access the endpoint?
Or if I use cognito pool authorizers will I be able to distinguish from a logged in user and a non logged user?

Thanks, any help and additional explanations will be much appreciated.  I'm still trying to get my head around Cognito.

答:
Your question is: if an endpoint returns different payloads depending on whether the user is signedup/loggedin, should this endpoint is secured (using AWS Cognito)?

We have two solution:

Solution 1: Define one endpoint. This endpoint is not secured. In the code of apigateway-integration , checking whether cognito authorizer is provided.

If "cognito authorizer" is provided (signed in user), returns data for signed in user

If "cognito authorizer" is NOT provided (NOT signed in user), returns data for visitor

Solution 2: Define three endpoints. One for receive initial request, one for returning data of visitor, one for returning data of signed in user:

Endpoint#1: Receive initial request, check whether cognito authorizer is provided <= This endpoint is not secured.

If "cognito authorizer" is provided (signed in user), redirect the request to Endpoint#2

If "cognito authorizer" is NOT provided (NOT signed in user), redirect the request to Endpoint#3

Endpoint#2: Returns data for signed in user <= This endpoint is secured.

Endpoint#3: Returns data for visitor <= This endpoint is not secured.

Summary: The endpoint for handling initial request should not be secured. Just consider secure for request/processing of returning signed-in/visitor user data.


问:
Claims Identity .NET CORE 3.0 API JWT
I'm trying to develop a web API on .NET CORE 3.0 but I can't get userId from the controller

this is my StartUp

```<code>RSAParameters keyParams = RsaKeyUtils.GetKeyParameters("jwt_key.conf");
        var key = new RsaSecurityKey(keyParams);

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey = key,
                    ValidAudience = GappedAuthSettings.TokenAudience,
                    ValidIssuer = GappedAuthSettings.TokenIssuer,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    RequireSignedTokens = true,
                    ClockSkew = TimeSpan.FromMinutes(0)
                };
            });
</code>```

This is how issue a JWT token :

```<code> private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
    {
        var handler = new JwtSecurityTokenHandler();

        var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = this.tokenOptions.Issuer,
            Audience = this.tokenOptions.Audience,
            SigningCredentials = this.tokenOptions.SigningCredentials,
            Subject = identity,
            Expires = expires,
            IssuedAt = DateTime.UtcNow
        });

        return handler.WriteToken(securityToken);
    }
</code>```

And when I try to read it claimsIdentity returns an object with null properties

```<code>    protected string GetUserId()
    {
        var claimsIdentity = this.User.Identity as ClaimsIdentity;
        var userId = claimsIdentity.FindFirst("userId")?.Value;

        if (userId != null)
        {
            return userId;
        }

        return null;
    }
</code>```

IMG

答:
Here is a working demo like below:

1.appsettings.json:

```<code>"Jwt": {
   "Key": "ThisismySecretKey",
   "Issuer": "Test.com"
}
</code>```

2.Startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),

            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            RequireSignedTokens = true,
            ClockSkew = TimeSpan.FromMinutes(0)
        };
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseRouting();

    app.UseAuthentication();   //be sure to add this line
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
</code>```

3.Controller:

```<code>[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    private IConfiguration _config;
    public ValuesController(IConfiguration config)
    {
        _config = config;
    }
    [HttpGet]
    public string Get()
    {
        var claim = new[]
        {
            new Claim("userId", "1")
        };
        var data = GetToken("np@hotmail.com", null, claim);
        return data;
    }
    [HttpGet]
    private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
    {
        var handler = new JwtSecurityTokenHandler();
        var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);

        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = _config["Jwt:Issuer"],
            Audience = _config["Jwt:Issuer"],
            SigningCredentials = credentials,
            Subject = identity,
            Expires = DateTime.Now.AddMinutes(120),
            IssuedAt = DateTime.UtcNow
        });
        return handler.WriteToken(securityToken);
    }
}
</code>```

4.The Test method(Be sure to add [Authorize]):

```<code>[Route("api/[controller]")]
public class TestController : Controller
{
    [Authorize]
    [HttpGet]
    public string Get()
    {
        var claimsIdentity = this.User.Identity as ClaimsIdentity;
        var claim = claimsIdentity.Claims;
        // or
        var data = claimsIdentity.FindFirst("userId").Value;
        return data;
    }
}
</code>```

5.Test Procedure:

First,you need to get the token from GetToken method.

Then,call the test method with Authorization type Bearer Token.

Finally,you could get the claim.

Title: Claims Identity .NET CORE 3.0 API JWT

Body:
I'm trying to develop a web API on .NET CORE 3.0 but I can't get userId from the controller

this is my StartUp

RSAParameters keyParams = RsaKeyUtils.GetKeyParameters("jwt_key.conf");
        var key = new RsaSecurityKey(keyParams);

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey = key,
                    ValidAudience = GappedAuthSettings.TokenAudience,
                    ValidIssuer = GappedAuthSettings.TokenIssuer,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    RequireSignedTokens = true,
                    ClockSkew = TimeSpan.FromMinutes(0)
                };
            });

This is how issue a JWT token :

 private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
    {
        var handler = new JwtSecurityTokenHandler();

        var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = this.tokenOptions.Issuer,
            Audience = this.tokenOptions.Audience,
            SigningCredentials = this.tokenOptions.SigningCredentials,
            Subject = identity,
            Expires = expires,
            IssuedAt = DateTime.UtcNow
        });

        return handler.WriteToken(securityToken);
    }

And when I try to read it claimsIdentity returns an object with null properties

    protected string GetUserId()
    {
        var claimsIdentity = this.User.Identity as ClaimsIdentity;
        var userId = claimsIdentity.FindFirst("userId")?.Value;

        if (userId != null)
        {
            return userId;
        }

        return null;
    }

IMG

Body:
Here is a working demo like below:

1.appsettings.json:

"Jwt": {
   "Key": "ThisismySecretKey",
   "Issuer": "Test.com"
}

2.Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),

            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            RequireSignedTokens = true,
            ClockSkew = TimeSpan.FromMinutes(0)
        };
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseRouting();

    app.UseAuthentication();   //be sure to add this line
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

3.Controller:

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    private IConfiguration _config;
    public ValuesController(IConfiguration config)
    {
        _config = config;
    }
    [HttpGet]
    public string Get()
    {
        var claim = new[]
        {
            new Claim("userId", "1")
        };
        var data = GetToken("np@hotmail.com", null, claim);
        return data;
    }
    [HttpGet]
    private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
    {
        var handler = new JwtSecurityTokenHandler();
        var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);

        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = _config["Jwt:Issuer"],
            Audience = _config["Jwt:Issuer"],
            SigningCredentials = credentials,
            Subject = identity,
            Expires = DateTime.Now.AddMinutes(120),
            IssuedAt = DateTime.UtcNow
        });
        return handler.WriteToken(securityToken);
    }
}

4.The Test method(Be sure to add [Authorize]):

[Route("api/[controller]")]
public class TestController : Controller
{
    [Authorize]
    [HttpGet]
    public string Get()
    {
        var claimsIdentity = this.User.Identity as ClaimsIdentity;
        var claim = claimsIdentity.Claims;
        // or
        var data = claimsIdentity.FindFirst("userId").Value;
        return data;
    }
}

5.Test Procedure:

First,you need to get the token from GetToken method.

Then,call the test method with Authorization type Bearer Token.

Finally,you could get the claim.


问:
How can I convert string to datetime?
How can I convert string column  to datetime in pandas?

My columns is as follows

```<code>Date

01Jan2019
01Feb2019
01Mar2019

</code>```

How can I convert this to a pandas date time?

答:
Could you try with below code</p>

```<code>from datetime import datetime
datetime_object =datetime.strptime('01Jan2019', '%d%b%Y')
</code>```

Title: How can I convert string to datetime?

Body:
How can I convert string column  to datetime in pandas?

My columns is as follows

Date

01Jan2019
01Feb2019
01Mar2019

How can I convert this to a pandas date time?

Body:
Could you try with below code

from datetime import datetime
datetime_object =datetime.strptime('01Jan2019', '%d%b%Y')


问:
Express JavaScript Supertest Expect specific json fields
I'm attempting to write some unit tests for API endpoints, and decided on JavaScript Express w/ Supertest. I've got the basic downs, but running into issues checking the response for a specific field. I want to parse the body and check if an expected field returns and has the correct value. Most everything I've seen online uses this method, but when I try it always passes, even when I enter values I know don't exist in the JSON. Any advice? Here is my code snippet:

```<code>describe('GET category', function () {
    it('response w/ only injury returned', function () {
        request('endpoint')
            .get('path')
            .set('header', 'token')
            .expect(200)
            .then(response => {
                console.assert(response.body, "Baseball")
            })
    })
});
</code>```

I have also tried changing the .then to .expect, with same results. If I do response.body.specificFieldinBody I get similar results. Any help?

答:
You can do with your way - use .then syntax, but I think use Supertest assertion syntax will be good.

This mean, use response.body.should.have.property("Baseball"); instead of console.assert(response.body, "Baseball") (Baseball is your special field).

Or, My suggestion is creating a re-use code: Put a assertion callback function to a next expects section.

```<code>const isIncludeField = function (fieldName) {
  return function (res) {
    res.body.should.have.property(fieldName);
  };
}

describe('GET category', function () {
  it('response w/ only injury returned', function () {
    request('endpoint')
      .get('path')
      .set('header', 'token')
      .expect(200)
      .expect(isIncludeField('Baseball')) //
      .end(done); // call done callback
  })
});
</code>```

Body:
I'm attempting to write some unit tests for API endpoints, and decided on JavaScript Express w/ Supertest. I've got the basic downs, but running into issues checking the response for a specific field. I want to parse the body and check if an expected field returns and has the correct value. Most everything I've seen online uses this method, but when I try it always passes, even when I enter values I know don't exist in the JSON. Any advice? Here is my code snippet:

describe('GET category', function () {
    it('response w/ only injury returned', function () {
        request('endpoint')
            .get('path')
            .set('header', 'token')
            .expect(200)
            .then(response => {
                console.assert(response.body, "Baseball")
            })
    })
});

I have also tried changing the .then to .expect, with same results. If I do response.body.specificFieldinBody I get similar results. Any help?

Body:
You can do with your way - use .then syntax, but I think use Supertest assertion syntax will be good.

This mean, use response.body.should.have.property("Baseball"); instead of console.assert(response.body, "Baseball") (Baseball is your special field).

Or, My suggestion is creating a re-use code: Put a assertion callback function to a next expects section.

const isIncludeField = function (fieldName) {
  return function (res) {
    res.body.should.have.property(fieldName);
  };
}

describe('GET category', function () {
  it('response w/ only injury returned', function () {
    request('endpoint')
      .get('path')
      .set('header', 'token')
      .expect(200)
      .expect(isIncludeField('Baseball')) //
      .end(done); // call done callback
  })
});


问:
Azure DevOps Boards - display query result on a board
how to develop the extension to display query result on a board? Such thing is not possible in the Azure Devops unfortunatelly. I've found two extensions on the marketplace which are doing what I need:

AA Query Board

Query based boards

but this extensions are not updated for a long time and I couldn't contact the authors (I need to change few things in order to be able to use it internally in my company).

I've found also this topic Add tabs on query result pages, so it looks like it's quite easy to add new tab to the query result menu, but I have no idea and I can't find any info how to get data (work items) from query result to display them?

Rest of the extension is just to display this data in grid, so that would be also quite easy, but getting this query result data is blocking me.

答:
There is a Query Results Widget that you can use to display the query results on the Dashboards under Overview.

1, First you need to create a shared query if not exist, and save query to the shared queries folder shown as below screenshot. (You can click the Column options from the Editor page to add and remove columns to be shown on the results)

Or drag and drop the query from My Queries folder to Shared Queries folder.

2,  Go to Dashboards under Overview, and Click Edit, then search and add widget Query results

3, Click the gear icon on the Query Results widget to configure it and select the query you want to display. Then the query result will be display on the Dashboards

Update:

There are some other ways to show the query results on the dashboards, For below example:

you can select your shared query and click more actions(3dots) and click Add to dashboards. This will display simple total number of query results.

you can also create different Charts for the query results and add it to Dashboards.

Select your shared query and go to Charts tab, the choose New Chart, select a Chart type,  After you configured the chart, you can click the 3dots on the chart and add it to dashboards, check below screenshot:


问:
addScoped service lifetime in an ASP.NET Core multithreaded application
I know that AddSingleton() creates a single instance of the service when it is first requested and reuses that same instance in all the places where that service is needed.

If my ASP.NET Core application is multi-threaded, does that mean all HTTP requests from all users will share the same object instance created by dependency injection (DI)?

If so, that would be not a good way if the application process data to be stored. Are there any best practices?

答:
As mentioned in Microsoft documentation, Service lifetimes, it depends on your specific case.

Presumably, if you have a service, A, and you want to create a new instance on every single request, you can use AddScoped() rather than AddSingleton(). A scoped lifetime service would be created per client request.


问:
Specifying a proportion in a nested table in prop.table
I make a four way table with xtabs

```<code>library(magrittr)
xtabs( ~ vs + gear + cyl, data = mtcars) %>%
  ftable(row.vars = "gear")
</code>```

returns

```<code>     vs   0        1
     cyl  4  6  8  4  6  8
gear
3         0  0 12  1  2  0
4         0  2  0  8  2  0
5         1  1  2  1  0  0
</code>```

Now I want proportions within levels of mtcars$vs.

If I use prop.table

```<code>xtabs( ~ vs + gear + cyl, data = mtcars) %>%
  ftable(row.vars = "gear") %>%
  prop.table(margin = 1) %>%
  round(2)
</code>```

I get

```<code>     vs     0              1
     cyl    4    6    8    4    6    8
gear
3        0.00 0.00 0.80 0.07 0.13 0.00
4        0.00 0.17 0.00 0.67 0.17 0.00
5        0.20 0.20 0.40 0.20 0.00 0.00
</code>```

Ie--I want the entry for vs == 0, gear == 3, cyl == 8, to be 1.00

Body:
I make a four way table with xtabs

library(magrittr)
xtabs( ~ vs + gear + cyl, data = mtcars) %>%
  ftable(row.vars = "gear")

returns

     vs   0        1
     cyl  4  6  8  4  6  8
gear
3         0  0 12  1  2  0
4         0  2  0  8  2  0
5         1  1  2  1  0  0

Now I want proportions within levels of mtcars$vs.

If I use prop.table

xtabs( ~ vs + gear + cyl, data = mtcars) %>%
  ftable(row.vars = "gear") %>%
  prop.table(margin = 1) %>%
  round(2)

I get

     vs     0              1
     cyl    4    6    8    4    6    8
gear
3        0.00 0.00 0.80 0.07 0.13 0.00
4        0.00 0.17 0.00 0.67 0.17 0.00
5        0.20 0.20 0.40 0.20 0.00 0.00

Ie--I want the entry for vs == 0, gear == 3, cyl == 8, to be 1.00

Body:
Try this

 xtabs( ~ vs + gear + cyl, data = mtcars) %>%
   ftable(row.vars = c("gear","vs")) %>%
   prop.table(margin = 1) %>%
   round(2)

the results are

        cyl    4    6    8
gear vs
3    0      0.00 0.00 1.00
     1      0.33 0.67 0.00
4    0      0.00 1.00 0.00
     1      0.80 0.20 0.00
5    0      0.25 0.25 0.50
     1      1.00 0.00 0.00


问:
I can't fill 'input' and 'textarea'
I have an issue with <input> and <textarea> tag.

I'm trying to receive a information by clients, but those tags does not work.

I cannot click the fields, and fill the fields with texts.

Only cursor changes into I when the mouse is hovering the fields.

I don't know what is the problem..

I didn't change any settings for texts, but it doesn't work.

I'm using those fields with HTML which use Three.js.

Please help me.

Below codes are whole about it.

It's just pop-up.

.userInfo {
  vertical-align: middle;
  width: 90%;
  height: 40px;
  border-radius: 4px;
  background-color: #ffffff;
  color: black;
  margin-bottom: 50px;
  margin-left: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <textarea class='userInfo' id='userName' placeholder='Name'></textarea>
  <!--  <input type='text' style='color:black;' class='userInfo' id='userName' /> I tried textarea becuase
                                                                                input tag does not work.-->
</div></code>```

Thanks for your help :)

答:
I just checked and the code is working fine. Maybe try a different browser or restart your browser or clear cache and try, hopefully, it should work.

See below snippet, it's working fine:

.userInfo{
  vertical-align:middle;
  width: 90%;
  height: 40px;
  border-radius: 4px;
  background-color: #ffffff;
  color: black;
  margin-bottom: 50px;
  margin-left: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
    <textarea class='userInfo' id='userName' placeholder='Name'></textarea>
  <input type='text' style='color:black;' class='userInfo' id='userName' />
</div>

</body>
</html></code>```

Title: I can't fill 'input' and 'textarea'

Body:
I have an issue with <input> and <textarea> tag.

I'm trying to receive a information by clients, but those tags does not work.

I cannot click the fields, and fill the fields with texts.

Only cursor changes into I when the mouse is hovering the fields.

I don't know what is the problem..

I didn't change any settings for texts, but it doesn't work.

I'm using those fields with HTML which use Three.js.

Please help me.

Below codes are whole about it.

It's just pop-up.

.userInfo {
  vertical-align: middle;
  width: 90%;
  height: 40px;
  border-radius: 4px;
  background-color: #ffffff;
  color: black;
  margin-bottom: 50px;
  margin-left: 50px;
}

  <textarea class='userInfo' id='userName' placeholder='Name'></textarea>

Thanks for your help :)

Body:
I just checked and the code is working fine. Maybe try a different browser or restart your browser or clear cache and try, hopefully, it should work.

See below snippet, it's working fine:

.userInfo{
  vertical-align:middle;
  width: 90%;
  height: 40px;
  border-radius: 4px;
  background-color: #ffffff;
  color: black;
  margin-bottom: 50px;
  margin-left: 50px;
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
    <textarea class='userInfo' id='userName' placeholder='Name'></textarea>
  <input type='text' style='color:black;' class='userInfo' id='userName' />
</div>

</body>
</html>


问:
MySql.Data can't connect to AWS Aurora
I have a really weird connection problem between C# .net core and AWS Aurora Serverless (MySql).  I have a really simple web API that I'm using for testing.  One of my endpoints is really simple to get the first row of one table:

```<code>        string cnString = "myConnectionString";
        string returnData = "";

        using (MySqlConnection cnData = new MySqlConnection(cnString))
        {
            using (MySqlCommand cmdData = new MySqlCommand("SELECT userName FROM users LIMIT 1", cnData))
            {
                await cnData.OpenAsync();
                await cmdData.ExecuteScalarAsync();

                returnData = (string)cmdData.ExecuteScalar();
            }
        }

        return Ok(returnData);
</code>```

I have the MySql.Data NuGet package installed.  When I deploy the package, I get an error: Unable to connect to to any of the specified MySQL hosts. (Sequence contains more than one matching element)

If I uninstall the MySql.Data package and install the MySqlConnector package, then there is no error and everything works properly.  There are no changes to the code or connection string.  The only thing I change is the NuGet package.

I don't think it matters, but my app is deployed to an Amazon Linux EC2 instance.

Does anyone know why the MySql.Data package doesn't work?  For my deployment, I need that package and I can't use the MySqlConnector package.

答:
If anyone else is having the same problem, there is an issue in the MySql.Data package.

I suspect that it is related to this known bug:
MySql #97448

The way that I read it is this:  the Aurora Cluster uses multiple IP addresses, so the Sequence contains more than 1 element error is thrown.  (The multiple elements are IP addresses in the TcpStream().

There is no fix that I saw, but I found a workaround that downgrading the package to 8.0.16 fixes the problem.

Title: MySql.Data can't connect to AWS Aurora

Body:
I have a really weird connection problem between C# .net core and AWS Aurora Serverless (MySql).  I have a really simple web API that I'm using for testing.  One of my endpoints is really simple to get the first row of one table:

        string cnString = "myConnectionString";
        string returnData = "";

        using (MySqlConnection cnData = new MySqlConnection(cnString))
        {
            using (MySqlCommand cmdData = new MySqlCommand("SELECT userName FROM users LIMIT 1", cnData))
            {
                await cnData.OpenAsync();
                await cmdData.ExecuteScalarAsync();

                returnData = (string)cmdData.ExecuteScalar();
            }
        }

        return Ok(returnData);

I have the MySql.Data NuGet package installed.  When I deploy the package, I get an error: Unable to connect to to any of the specified MySQL hosts. (Sequence contains more than one matching element)

If I uninstall the MySql.Data package and install the MySqlConnector package, then there is no error and everything works properly.  There are no changes to the code or connection string.  The only thing I change is the NuGet package.

I don't think it matters, but my app is deployed to an Amazon Linux EC2 instance.

Does anyone know why the MySql.Data package doesn't work?  For my deployment, I need that package and I can't use the MySqlConnector package.


问:
How to use jQuery inside ReactJs Project jQueryscrollSpeed.js plugin for full page scrolling Effect
I want to use jQueryscrollSpeed.js plugin but I could not found the solution for this.
I have try using ref method but not get good result.

```<code>
import React from 'react';
import $ from 'jquery';
class App extends React.Component{

  componentDidMount(){
    $(function() {

      // Default
      jQuery.scrollSpeed(100, 800);

      // Custom Easing
      jQuery.scrollSpeed(100, 800, 'easeOutCubic');

  });
  }
  render(){
    return (
      <div className="wrapper">
        <button>Click Me</button>
        <p ref={"toggle"}>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Vero, minima. Accusantium illum quam qui, natus eum laudantium vero ex. Vero.</p>
      </div>

    )
  }

}
export default App;

</code>```

I need solution for this
Github jQueryscrollSpeed.js plugin

I need to use scrollspeed in my reactjs project.

答:
Please have a look below:

const elementName = document.getElementById('elem');

elementName.addEventListener('click', () => window.scrollTo({
  top: 400,
  behavior: 'smooth',
}));```

I hope it would help you out!

Body:
I want to use jQueryscrollSpeed.js plugin but I could not found the solution for this.
I have try using ref method but not get good result.

import React from 'react';
import $ from 'jquery';
class App extends React.Component{

  componentDidMount(){
    $(function() {

      // Default
      jQuery.scrollSpeed(100, 800);

      // Custom Easing
      jQuery.scrollSpeed(100, 800, 'easeOutCubic');

  });
  }
  render(){
    return (

        <button>Click Me</button>

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Vero, minima. Accusantium illum quam qui, natus eum laudantium vero ex. Vero.

    )
  }

}
export default App;

I need solution for this
Github jQueryscrollSpeed.js plugin

I need to use scrollspeed in my reactjs project.

Body:
Please have a look below:

const elementName = document.getElementById('elem');

elementName.addEventListener('click', () => window.scrollTo({
  top: 400,
  behavior: 'smooth',
}));

I hope it would help you out!


问:
Jupyter Notebook / Python
I am having trouble to why I am getting this error. I would like to have any assistance with this issue.

happyList = []
sadList = []

exclude = string.punctuation

happy_file = open("happy.txt", "r")
for word in happy_file:
    word = ''.join(ch for ch in word if ch not in exclude)
    happyList.append(word.strip().lower())
happy_file.close()
```

<p>The error:</p>

```    happyList.append(word.strip().lower())
            ^
SyntaxError: invalid syntax
```

答:
For looping the file happy_file, try using the "with" context manager to ensure you are reading properly.</p>

```<code>happyList = []
with open('happy-file.txt') as f:
    input_lines = f.readlines()
    for i in input_lines:
       # -- do your processing for each input_line
       happyList.append( ... )
</code>```

Title: Jupyter Notebook / Python

Body:
I am having trouble to why I am getting this error. I would like to have any assistance with this issue.

happyList = []
sadList = []

exclude = string.punctuation

happy_file = open("happy.txt", "r")
for word in happy_file:
    word = ''.join(ch for ch in word if ch not in exclude)
    happyList.append(word.strip().lower())
happy_file.close()

The error:

    happyList.append(word.strip().lower())
            ^
SyntaxError: invalid syntax

Body:
For looping the file happy_file, try using the "with" context manager to ensure you are reading properly.

happyList = []
with open('happy-file.txt') as f:
    input_lines = f.readlines()
    for i in input_lines:
       # -- do your processing for each input_line
       happyList.append( ... )


问:
How to change the TextView height dynamically to a threshold and then allow scrolling?
I have a TextView that has a constraint of min height of 33. The scroll is disabled from the storyboard. The TextView should increase in height based on the content until it reaches the max height of 100. Then I changes the scrollEnabled to true and the height of the TextView to max height of 100, but the height changes to the 33. How can I fix this problem?

```<code>import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var messageTextView: UITextView!
    let messageTextViewMaxHeight: CGFloat = 100

    override func viewDidLoad() {
        super.viewDidLoad()
        self.messageTextView.delegate = self
    }

    func textViewDidChange(textView: UITextView) {

        if textView.frame.size.height >= self.messageTextViewMaxHeight {
            textView.scrollEnabled = true
            textView.frame.size.height = self.messageTextViewMaxHeight
        } else {
            textView.scrollEnabled = false
        }
    }
}
</code>```

答:
Create a class that inherits from UITextView and add the following into the class:

```<code>class CustomTextView: UITextView, UITextViewDelegate {

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)

        delegate = self
    }

    var maxHeight: CGFloat = 200

    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        if size.height > maxHeight {
            size.height = maxHeight
            isScrollEnabled = true
        } else {
            isScrollEnabled = false
        }
        return size
    }

    override var text: String! {
        didSet {
            invalidateIntrinsicContentSize()
        }
    }

    func textViewDidChange(_ textView: UITextView) {
        invalidateIntrinsicContentSize()
    }

}
</code>```

Note:
- You can initialize maxHeight to infinity and set maxHeight after creating the CustomTextView. This class can be reused anywhere it is needed in the app, and the max height can be modified for different scenarios.

Body:
I have a TextView that has a constraint of min height of 33. The scroll is disabled from the storyboard. The TextView should increase in height based on the content until it reaches the max height of 100. Then I changes the scrollEnabled to true and the height of the TextView to max height of 100, but the height changes to the 33. How can I fix this problem?

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var messageTextView: UITextView!
    let messageTextViewMaxHeight: CGFloat = 100

    override func viewDidLoad() {
        super.viewDidLoad()
        self.messageTextView.delegate = self
    }

    func textViewDidChange(textView: UITextView) {

        if textView.frame.size.height >= self.messageTextViewMaxHeight {
            textView.scrollEnabled = true
            textView.frame.size.height = self.messageTextViewMaxHeight
        } else {
            textView.scrollEnabled = false
        }
    }
}

Body:
Create a class that inherits from UITextView and add the following into the class:

class CustomTextView: UITextView, UITextViewDelegate {

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)

        delegate = self
    }

    var maxHeight: CGFloat = 200

    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        if size.height > maxHeight {
            size.height = maxHeight
            isScrollEnabled = true
        } else {
            isScrollEnabled = false
        }
        return size
    }

    override var text: String! {
        didSet {
            invalidateIntrinsicContentSize()
        }
    }

    func textViewDidChange(_ textView: UITextView) {
        invalidateIntrinsicContentSize()
    }

}

Note:
- You can initialize maxHeight to infinity and set maxHeight after creating the CustomTextView. This class can be reused anywhere it is needed in the app, and the max height can be modified for different scenarios.


问:
using python in c++ basics
can anyone show me a basic program that includes python in a c++ program? i have gotten #include <Python.h> to work, but thats about it. how do you create a string, int, and include a module that is not part of the python library?

答:
Definitely use Boost Python. It is a lightweight dependency (doesn't require changes to existing C++ code), though it does increase compile times slightly.

You can install boost python on ubuntu (or the pkg manager for your platform):

```<code>$ sudo apt-get install boost-python
</code>```

Then a simple library looks like this:

```<code>#include <boost/python.hpp>

using namespace boost::python;

struct mystruct {
    int value;
}

int myfunction(int i) {
    return i + 1;
}

BOOST_PYTHON_MODULE(mymodule) {
    // Code placed here will be executed when you do "import mymodule" in python
    initialize_my_module();

    // Declare my C++ data structures
    class_<mystruct>("mystruct")
        .def_readwrite("value", &mystruct::value)
        ;

    // Declare my C++ functions
    def("myfunction", myfunction);
}
</code>```

Then compile with

```<code>$ g++ -shared mymodule.cpp -I/usr/include/python -lboost_python -omymodule.so
</code>```

Finally, import and use it in python

```<code>>>> import mymodule
>>> mymodule.myfunction(5)
6
>>> s = mymodule.mystruct()
>>> s.value = 4
>>> s.value
4
</code>```

Title: using python in c++ basics

Body:
Definitely use Boost Python. It is a lightweight dependency (doesn't require changes to existing C++ code), though it does increase compile times slightly.

You can install boost python on ubuntu (or the pkg manager for your platform):

$ sudo apt-get install boost-python

Then a simple library looks like this:

#include <boost/python.hpp>

using namespace boost::python;

struct mystruct {
    int value;
}

int myfunction(int i) {
    return i + 1;
}

BOOST_PYTHON_MODULE(mymodule) {
    // Code placed here will be executed when you do "import mymodule" in python
    initialize_my_module();

    // Declare my C++ data structures
    class_<mystruct>("mystruct")
        .def_readwrite("value", &mystruct::value)
        ;

    // Declare my C++ functions
    def("myfunction", myfunction);
}

Then compile with

$ g++ -shared mymodule.cpp -I/usr/include/python -lboost_python -omymodule.so

Finally, import and use it in python

>>> import mymodule
>>> mymodule.myfunction(5)
6
>>> s = mymodule.mystruct()
>>> s.value = 4
>>> s.value
4


问:
Vulkan validation layers VkCmdWaitEvents srcStageMask error meaning
Event is signaled by another cmd buffer on the same queue with VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT stage mask.

Event is not signaled via vkSetEvent on the host.

Event is waited by vkCmdWaitEvents with src stage mask VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT and dst stage mask VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT.

Is this correct stage masks for depth attachment writting and reading as color attachment after?

Validation layers callback message:

```<code>Submitting cmdbuffer with call to VkCmdWaitEvents using srcStageMask 0x200 which must be the
bitwise OR of the stageMask parameters used in calls to vkCmdSetEvent and
VK_PIPELINE_STAGE_HOST_BIT if used with vkSetEvent but instead is 0x0. The Vulkan spec
states: srcStageMask must be a valid combination of VkPipelineStageFlagBits values
(https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#VUID-
vkCmdWaitEvents-srcStageMask-parameter)
</code>```

It actually says, that "submitted value is 0x200, but is 0x0".
Is this a bug? Where from 0x0 value come from, how it can be 0x200 and 0x0 at the same time?

Some code

Signal after depth buffer renderpass:

```<code>cmd.cmd_event_set_signaled(cmd_data.event<EventId::SHADOW_MAP>(),
                           vkw::StageFlag::LATE_FRAGMENT_TESTS);
</code>```

Wait before primary render pass in another cmd:

```<code>vkw::StageMaskChange stage_masks;
stage_masks.src = vkw::StageFlag::LATE_FRAGMENT_TESTS;
stage_masks.dst = vkw::StageFlag::FRAGMENT_SHADER;
auto &shadow_map_event = cmd_data.event<EventId::SHADOW_MAP>();
cmd.cmd_event_wait(shadow_map_event, stage_masks);
cmd.cmd_event_set_unsignaled(shadow_map_event, stage_masks.dst);
</code>```

Wrapper code. There is some C++ type conversions magic, but values are passing to vkCmd functions correctly.

```<code>void cmd_event_set_signaled(Event e, StageMask stage_mask) {
    vkCmdSetEvent(*this, e, stage_mask);
}
void cmd_event_set_unsignaled(Event e, StageMask stage_mask) {
    vkCmdResetEvent(*this, e, stage_mask);
}
void cmd_event_wait(Events es, StageMaskChange smc) {
    vkCmdWaitEvents(*this, es.count32(), &es.begin()->p_vk, smc.src, smc.dst,
                    0, {}, 0, {}, 0, {});
}
</code>```

答: The problem is not present in the VulkanSDK 1.2.131.2, so vulkan-loader-1.1.125 is a bit outdated.</p>

Body:
Event is signaled by another cmd buffer on the same queue with VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT stage mask.

Event is not signaled via vkSetEvent on the host.

Event is waited by vkCmdWaitEvents with src stage mask VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT and dst stage mask VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT.

Is this correct stage masks for depth attachment writting and reading as color attachment after?

Validation layers callback message:

Submitting cmdbuffer with call to VkCmdWaitEvents using srcStageMask 0x200 which must be the
bitwise OR of the stageMask parameters used in calls to vkCmdSetEvent and
VK_PIPELINE_STAGE_HOST_BIT if used with vkSetEvent but instead is 0x0. The Vulkan spec
states: srcStageMask must be a valid combination of VkPipelineStageFlagBits values
(https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#VUID-
vkCmdWaitEvents-srcStageMask-parameter)

It actually says, that "submitted value is 0x200, but is 0x0".
Is this a bug? Where from 0x0 value come from, how it can be 0x200 and 0x0 at the same time?

Some code

Signal after depth buffer renderpass:

cmd.cmd_event_set_signaled(cmd_data.event<EventId::SHADOW_MAP>(),
                           vkw::StageFlag::LATE_FRAGMENT_TESTS);

Wait before primary render pass in another cmd:

vkw::StageMaskChange stage_masks;
stage_masks.src = vkw::StageFlag::LATE_FRAGMENT_TESTS;
stage_masks.dst = vkw::StageFlag::FRAGMENT_SHADER;
auto &shadow_map_event = cmd_data.event<EventId::SHADOW_MAP>();
cmd.cmd_event_wait(shadow_map_event, stage_masks);
cmd.cmd_event_set_unsignaled(shadow_map_event, stage_masks.dst);

Wrapper code. There is some C++ type conversions magic, but values are passing to vkCmd functions correctly.

void cmd_event_set_signaled(Event e, StageMask stage_mask) {
    vkCmdSetEvent(*this, e, stage_mask);
}
void cmd_event_set_unsignaled(Event e, StageMask stage_mask) {
    vkCmdResetEvent(*this, e, stage_mask);
}
void cmd_event_wait(Events es, StageMaskChange smc) {
    vkCmdWaitEvents(*this, es.count32(), &es.begin()->p_vk, smc.src, smc.dst,
                    0, {}, 0, {}, 0, {});
}


问:
Bounded Type Parameters in Static Method
Are these two methods equivalent?

```<code>public static <T extends com.google.protobuf.Message> Any pack(T message) {}
public static Any pack(com.google.protobuf.Message message) {}
</code>```

My understanding is that in the first function, T only applies to that static method, not other static methods or the class. Thus, it just restraint the input parameter to be a subtype of Message. Is that so? If this is the case, are these two methods equivalent?

答:
Yes, these two signatures are equivalent, assuming that the caller does not provide an explicit type witness. This is because, without a type witness, both signatures accept the same sets of arguments:

Any argument that is accepted by the first signature must be an instance of T, and T is a subtype of Message, so the argument must also be an instance of Message, and is accepted by the second signature

Any argument that is accepted by the second signature must be an instance of Message, and so can be accepted by the first signature if T is chosen to be Message

Body:
Are these two methods equivalent?

public static <T extends com.google.protobuf.Message> Any pack(T message) {}
public static Any pack(com.google.protobuf.Message message) {}

My understanding is that in the first function, T only applies to that static method, not other static methods or the class. Thus, it just restraint the input parameter to be a subtype of Message. Is that so? If this is the case, are these two methods equivalent?


问:
Why don't we just keep all dynamic memory in arrays?
In C/C++, when you allocate dynamic memory, the OS gives you an unpredictable address to some distant region of memory.  If you allocate a lot of dynamic memory, and need to travel between it (for example, linked lists, trees), then you have to waste time waiting for the CPU to consult RAM, because, more than likely, the piece of memory you wanted wasn't close to the piece of memory you had.

Recently, for a project in one of my university courses, I had to implement a tree such that nodes could have any number of children, and I had to be able to merge nodes into single trees in constant time.  So, I had a bunch of internal Node objects with a bunch of pointers to surrounding nodes.

Because this was C++, it was fast, of course, but with the time and memory it was being tested on, it had just okay performance.

So, I decided to try implementing pointer replacements which would really be indices of static vectors, and a function to grow the vector when a new object was needed, and a stack of 'deleted' indices that could be re-used.  This way, everything would be close together in memory, and dereferences were less likely to result in cache misses.  Also, because I knew the tree would not be tested on the scale of gigabytes of data, I could restrict these indices to 32 bits, reducing the memory overhead of the tree structure significantly.

The results were amazing -- in most cases a third the time and memory of the staff implementation for my course.

My question is, if the cache benefits are so extreme, why do we bother directly using new and delete at all?  Why not just stick everything in vectors, one for each type?

答:
Why don't we just keep all dynamic memory in arrays?

To be fair, we do keep most of dynamic memory in arrays.

But sometimes an array cannot achieve the same asymptotic complexity as a node based structure can, and in such case it can be beneficial to not use the array.

why do we bother directly using new and delete at all?

It is extremely rare to need to use new and delete directly.


问:
SPFx JQuery Dialog button click does not find public function
I am new to TypeScript and Sharepoint SPFx development.  I have a jquery UI dialog box and a public function in the same class that makes some MSGRAPH calls after the button has been clicked. The button click returns with error this.addAlert is not a function.  I think the problem is that the dialog code executes outside the web part context and hence does not know about the function available in the webpart context.  How can I use the button click to run within the webpart context?

Here is the Dialog code.

```<code>    export default class YlsSpAlertWebPart extends BaseClientSideWebPart<IYlsSpAlertWebPartProps> {

      public constructor() {
        super();
        SPComponentLoader.loadCss('//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css');
      }

public render(): void {

    this.domElement.innerHTML = AlertTemplate.templateHtml;
    const dialogOptions: JQueryUI.DialogOptions = {
      width: "50%",
      height: "auto",
      buttons: {
        "Subscribe": function (e) {
          this.addAlert("Yes");
          jQuery(this).dialog("close");
        },
        "No Thanks": function (e) {
          console.log("moo");
          this.addAlert("No");
          jQuery(this).dialog("close");
        },
        "Ask me later": function (e) {
          this.addAlert("Ask Me Later");
          jQuery(this).dialog("close");
        }
      }
    };

    jQuery('.dialog', this.domElement).dialog(dialogOptions);
    jQuery(".ui-dialog-titlebar").hide();
  }

     public addAlert(status: string): void {
        var url = "/sites/" + this.context.pageContext.site.id + "/lists";
        var listId = "";
        var email = this.getCurrentUserEmail();
        var recordExists = false;
        let item: SubscriptionListItem;
        this.context.msGraphClientFactory
          .getClient()
          .then((client: MSGraphClient): void => {
            client
              .api(url)
              .top(1)
              .filter("equals=(displayName, 'Subscriptions'")
              .version("v1.0")
              .get((err, res) => {
                if (err) {
                  console.error(err);
                  return;
                }
                console.log(res);
                listId = res.id;
              });
          });

}
</code>```

...skipping the rest of the boilerplate generated by the template

答:
Try this:</p>

```<code>    var event=this.addAlert;
    const dialogOptions: JQueryUI.DialogOptions = {
      width: "50%",
      height: "auto",
      buttons: {
        "Subscribe": function (e) {
          event("Yes");
          //this.addAlert("Yes");
          jQuery(this).dialog("close");
        },
        "No Thanks": function (e) {
          console.log("moo");
          event("no");
          jQuery(this).dialog("close");
        },
        "Ask me later": function (e) {
          //this.addAlert("Ask Me Later");
          jQuery(this).dialog("close");
        }
      }
    };
</code>```

Body:
I am new to TypeScript and Sharepoint SPFx development.  I have a jquery UI dialog box and a public function in the same class that makes some MSGRAPH calls after the button has been clicked. The button click returns with error this.addAlert is not a function.  I think the problem is that the dialog code executes outside the web part context and hence does not know about the function available in the webpart context.  How can I use the button click to run within the webpart context?

Here is the Dialog code.

    export default class YlsSpAlertWebPart extends BaseClientSideWebPart<IYlsSpAlertWebPartProps> {

      public constructor() {
        super();
        SPComponentLoader.loadCss('//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css');
      }

public render(): void {

    this.domElement.innerHTML = AlertTemplate.templateHtml;
    const dialogOptions: JQueryUI.DialogOptions = {
      width: "50%",
      height: "auto",
      buttons: {
        "Subscribe": function (e) {
          this.addAlert("Yes");
          jQuery(this).dialog("close");
        },
        "No Thanks": function (e) {
          console.log("moo");
          this.addAlert("No");
          jQuery(this).dialog("close");
        },
        "Ask me later": function (e) {
          this.addAlert("Ask Me Later");
          jQuery(this).dialog("close");
        }
      }
    };

    jQuery('.dialog', this.domElement).dialog(dialogOptions);
    jQuery(".ui-dialog-titlebar").hide();
  }

     public addAlert(status: string): void {
        var url = "/sites/" + this.context.pageContext.site.id + "/lists";
        var listId = "";
        var email = this.getCurrentUserEmail();
        var recordExists = false;
        let item: SubscriptionListItem;
        this.context.msGraphClientFactory
          .getClient()
          .then((client: MSGraphClient): void => {
            client
              .api(url)
              .top(1)
              .filter("equals=(displayName, 'Subscriptions'")
              .version("v1.0")
              .get((err, res) => {
                if (err) {
                  console.error(err);
                  return;
                }
                console.log(res);
                listId = res.id;
              });
          });

}

...skipping the rest of the boilerplate generated by the template

Body:
Try this:

    var event=this.addAlert;
    const dialogOptions: JQueryUI.DialogOptions = {
      width: "50%",
      height: "auto",
      buttons: {
        "Subscribe": function (e) {
          event("Yes");
          //this.addAlert("Yes");
          jQuery(this).dialog("close");
        },
        "No Thanks": function (e) {
          console.log("moo");
          event("no");
          jQuery(this).dialog("close");
        },
        "Ask me later": function (e) {
          //this.addAlert("Ask Me Later");
          jQuery(this).dialog("close");
        }
      }
    };


问:
Swift Parse Google Search API Text File
I am trying to parse the results from Google's search autocomplete endpoint at http://suggestqueries.google.com/complete/search?client=firefox&q=YOURQUERY, but it's returning a textfile without keys.

This is an example output:

```<code>["YOURQUERY",["yourquery","yourquery dou","yourquery s.r.o","yourquery отзывы","yourquery львів","yourquery s.r.o. львів"]]
</code>```

This is my code:

```<code>let baseURL = "http://suggestqueries.google.com/complete/search?client=firefox&q="

var searchResults: [String] = []

func returnResults(searchTerm: String, completion: @escaping ([String?], Error?) -> Void) {
    let finalUrl = URL(string: baseURL + searchTerm)

    // 3. choose method to transmit and configure to do so
    var request = URLRequest(url: finalUrl!)
    request.httpMethod = "GET"

    // 4. request data
    URLSession.shared.dataTask(with: request) { (data, _, error) in
        // check for errors and data
        if let error = error {
            print("There was an error requesting data")
            return completion([], error)
        }
        guard let data = data else {
            print("There was an error getting data.", error)
            return completion([], NSError())
        }

        // if we got our data back, we need to decode it to match our model object
        let jsonDecoder = JSONDecoder()

        do {
            // 1. decode results into array
            let results = try jsonDecoder.decode([String].self, from: data)

            // 2. set search results var equal to our decoded results array
            self.searchResults = results

            completion(results, nil)
        } catch {
            print("There was an error decoding data.", error)
            completion([], error)
        }}.resume()
}
</code>```

I'm getting an decoding error:

```<code>There was an error decoding data. typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1", intValue: 1)], debugDescription: "Expected to decode String but found an array instead.", underlyingError: nil))
</code>```

How would you decode this correctly?

答:
Your problem there is that the JSON returned is an array of Any. The first element is a String and the second is an array of strings [String]. Since Any does not conform to Decodable it would be easier to use JSONSerialization method

```<code>class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
</code>```

to cast the result from Any to [Any] and cast the last element to an array of strings [String].

```<code>let results = try (JSONSerialization.jsonObject(with: data) as? [Any])?.last as? [String] ?? []
print(results)
</code>```

This will print

"["yourquery", "yourquery dou", "yourquery s.r.o", "yourquery отзывы",
  "yourquery львів", "yourquery s.r.o. львів"]\n"

Title: Swift Parse Google Search API Text File

Body:
I am trying to parse the results from Google's search autocomplete endpoint at http://suggestqueries.google.com/complete/search?client=firefox&q=YOURQUERY, but it's returning a textfile without keys.

This is an example output:

["YOURQUERY",["yourquery","yourquery dou","yourquery s.r.o","yourquery отзывы","yourquery львів","yourquery s.r.o. львів"]]

This is my code:

let baseURL = "http://suggestqueries.google.com/complete/search?client=firefox&q="

var searchResults: [String] = []

func returnResults(searchTerm: String, completion: @escaping ([String?], Error?) -> Void) {
    let finalUrl = URL(string: baseURL + searchTerm)

    // 3. choose method to transmit and configure to do so
    var request = URLRequest(url: finalUrl!)
    request.httpMethod = "GET"

    // 4. request data
    URLSession.shared.dataTask(with: request) { (data, _, error) in
        // check for errors and data
        if let error = error {
            print("There was an error requesting data")
            return completion([], error)
        }
        guard let data = data else {
            print("There was an error getting data.", error)
            return completion([], NSError())
        }

        // if we got our data back, we need to decode it to match our model object
        let jsonDecoder = JSONDecoder()

        do {
            // 1. decode results into array
            let results = try jsonDecoder.decode([String].self, from: data)

            // 2. set search results var equal to our decoded results array
            self.searchResults = results

            completion(results, nil)
        } catch {
            print("There was an error decoding data.", error)
            completion([], error)
        }}.resume()
}

I'm getting an decoding error:

There was an error decoding data. typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1", intValue: 1)], debugDescription: "Expected to decode String but found an array instead.", underlyingError: nil))

How would you decode this correctly?

Body:
Your problem there is that the JSON returned is an array of Any. The first element is a String and the second is an array of strings [String]. Since Any does not conform to Decodable it would be easier to use JSONSerialization method

class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any

to cast the result from Any to [Any] and cast the last element to an array of strings [String].

let results = try (JSONSerialization.jsonObject(with: data) as? [Any])?.last as? [String] ?? []
print(results)

This will print

"["yourquery", "yourquery dou", "yourquery s.r.o", "yourquery отзывы",
  "yourquery львів", "yourquery s.r.o. львів"]\n"


问:
cmake cannot find library when linking library to another application
I am trying to make generate a shared library of an existing application, so that i can link it to gtest application.
My main applications cmake file looks like this:

```<code>project(audiodLib CXX C)
cmake_minimum_required(VERSION 2.8.7)

## Lets store all the source code in ${SOURCES}
file(GLOB SOURCES src/*.cpp src/controls/*.cpp src/controls/pulse/*.cpp src/modules/*.cpp src/product/*.cpp src/umi/*.cpp src/umi/modules/*.cpp src/umi/soundSettings/*.cpp src/utils/*.cpp utils/*.cpp pmtrace/*.c)

##Lets generate the library
##Please note, here instead of ${SOURCES} if i try to directly add source code, I always get
##an error saying that cmake could not find any *.cpp files
add_library(audiodLib SHARED ${SOURCES})

##Lets link it with libraries
target_link_libraries(audiodLib     ${GLIB2_LDFLAGS}
                ${LUNASERVICE_LDFLAGS}
                ${PBNJSON_C_LDFLAGS}
                ${LUNAPREFS_LDFLAGS}
                ${POWERD_LDFLAGS}
                ${PMLOGLIB_LDFLAGS}
                ${NYXLIB_LDFLAGS}
                ${LIBPBNJSON_LDFLAGS}
                ${PULSE_LDFLAGS}
                ${LTTNG_UST_LDFLAGS}
                ${URCU_BP_LDFLAGS}
                ${PULSE_SIMPLE_LDFLAGS}
                ${WEBOSI18N_LDFLAGS}
                pthread
                rt
                dl
                -lsnapshot-boot
                )

##Lets make this library availabel for other modules
install(TARGETS audiodLib LIBRARY DESTINATION ${WEBOS_INSTALL_LIBDIR})
</code>```

After compilation, libaudiodLib.so is generated in /usr/lib directory.
And now if I try to access the audiodLib in my gtest code like this:

```<code>##${WEBOS_INSTALL_LIBDIR} = /usr/lib/
include_directories(${WEBOS_INSTALL_LIBDIR})
target_link_libraries(${GTEST_EXECUTABLE}
    ${WEBOS_GTEST_LIBRARIES}
    ${GLIB2_LDFLAGS}
    ${LUNASERVICE_LDFLAGS}
    ${PBNJSON_C_LDFLAGS}
    ${LUNAPREFS_LDFLAGS}
    ${POWERD_LDFLAGS}
    ${PMLOGLIB_LDFLAGS}
    ${NYXLIB_LDFLAGS}
    ${LIBPBNJSON_LDFLAGS}
    ${PULSE_LDFLAGS}
    ${LTTNG_UST_LDFLAGS}
    ${URCU_BP_LDFLAGS}
    ${PULSE_SIMPLE_LDFLAGS}
    ${WEBOSI18N_LDFLAGS}
    pthread
    rt
    dl
    -lsnapshot-boot
    -laudiodLib
    )

</code>```

I get the following error:

```<code>cannot find -laudiodLib
</code>```

The folder structure is as follows:

```<code>audiod/
CMakeList
    |src
|tests
    CMakelist
</code>```

If someone can point out what I am doing wrong, it would be of great help. I am kind of stuck and clueless after spending 2-3 days on this.

答:
Thank you so very much for offering me suggestions, and pointers, I was finally able to sove the problem.
Regarding library not found issue, I resolved it by rearranging the TARGET_LINK_LIBRARIES as follows:

```<code>target_link_libraries(audiod
                audiodLib
                ${GLIB2_LDFLAGS}
                ${LUNASERVICE_LDFLAGS}
                ${PBNJSON_C_LDFLAGS}
                ${LUNAPREFS_LDFLAGS}
                ${POWERD_LDFLAGS}
                ${PMLOGLIB_LDFLAGS}
                ${NYXLIB_LDFLAGS}
                ${LIBPBNJSON_LDFLAGS}
                ${PULSE_LDFLAGS}
                ${LTTNG_UST_LDFLAGS}
                ${URCU_BP_LDFLAGS}
                ${PULSE_SIMPLE_LDFLAGS}
                ${WEBOSI18N_LDFLAGS}
                pthread
                rt
                dl
                -lsnapshot-boot
                )
</code>```

And how i resolved the BAD RPATH Error during do_package_qa, I have already answerd it here:
bitbake do_package_qa issue contains bad RPATH

Body:
I am trying to make generate a shared library of an existing application, so that i can link it to gtest application.
My main applications cmake file looks like this:

project(audiodLib CXX C)
cmake_minimum_required(VERSION 2.8.7)

## Lets store all the source code in ${SOURCES}
file(GLOB SOURCES src/*.cpp src/controls/*.cpp src/controls/pulse/*.cpp src/modules/*.cpp src/product/*.cpp src/umi/*.cpp src/umi/modules/*.cpp src/umi/soundSettings/*.cpp src/utils/*.cpp utils/*.cpp pmtrace/*.c)

##Lets generate the library
##Please note, here instead of ${SOURCES} if i try to directly add source code, I always get
##an error saying that cmake could not find any *.cpp files
add_library(audiodLib SHARED ${SOURCES})

##Lets link it with libraries
target_link_libraries(audiodLib     ${GLIB2_LDFLAGS}
                ${LUNASERVICE_LDFLAGS}
                ${PBNJSON_C_LDFLAGS}
                ${LUNAPREFS_LDFLAGS}
                ${POWERD_LDFLAGS}
                ${PMLOGLIB_LDFLAGS}
                ${NYXLIB_LDFLAGS}
                ${LIBPBNJSON_LDFLAGS}
                ${PULSE_LDFLAGS}
                ${LTTNG_UST_LDFLAGS}
                ${URCU_BP_LDFLAGS}
                ${PULSE_SIMPLE_LDFLAGS}
                ${WEBOSI18N_LDFLAGS}
                pthread
                rt
                dl
                -lsnapshot-boot
                )

##Lets make this library availabel for other modules
install(TARGETS audiodLib LIBRARY DESTINATION ${WEBOS_INSTALL_LIBDIR})

After compilation, libaudiodLib.so is generated in /usr/lib directory.
And now if I try to access the audiodLib in my gtest code like this:

##${WEBOS_INSTALL_LIBDIR} = /usr/lib/
include_directories(${WEBOS_INSTALL_LIBDIR})
target_link_libraries(${GTEST_EXECUTABLE}
    ${WEBOS_GTEST_LIBRARIES}
    ${GLIB2_LDFLAGS}
    ${LUNASERVICE_LDFLAGS}
    ${PBNJSON_C_LDFLAGS}
    ${LUNAPREFS_LDFLAGS}
    ${POWERD_LDFLAGS}
    ${PMLOGLIB_LDFLAGS}
    ${NYXLIB_LDFLAGS}
    ${LIBPBNJSON_LDFLAGS}
    ${PULSE_LDFLAGS}
    ${LTTNG_UST_LDFLAGS}
    ${URCU_BP_LDFLAGS}
    ${PULSE_SIMPLE_LDFLAGS}
    ${WEBOSI18N_LDFLAGS}
    pthread
    rt
    dl
    -lsnapshot-boot
    -laudiodLib
    )

I get the following error:

cannot find -laudiodLib

The folder structure is as follows:

audiod/
CMakeList
    |src
|tests
    CMakelist

If someone can point out what I am doing wrong, it would be of great help. I am kind of stuck and clueless after spending 2-3 days on this.

Body:
Thank you so very much for offering me suggestions, and pointers, I was finally able to sove the problem.
Regarding library not found issue, I resolved it by rearranging the TARGET_LINK_LIBRARIES as follows:

target_link_libraries(audiod
                audiodLib
                ${GLIB2_LDFLAGS}
                ${LUNASERVICE_LDFLAGS}
                ${PBNJSON_C_LDFLAGS}
                ${LUNAPREFS_LDFLAGS}
                ${POWERD_LDFLAGS}
                ${PMLOGLIB_LDFLAGS}
                ${NYXLIB_LDFLAGS}
                ${LIBPBNJSON_LDFLAGS}
                ${PULSE_LDFLAGS}
                ${LTTNG_UST_LDFLAGS}
                ${URCU_BP_LDFLAGS}
                ${PULSE_SIMPLE_LDFLAGS}
                ${WEBOSI18N_LDFLAGS}
                pthread
                rt
                dl
                -lsnapshot-boot
                )

And how i resolved the BAD RPATH Error during do_package_qa, I have already answerd it here:
bitbake do_package_qa issue contains bad RPATH


问:
Runtime analysis of dependent nested for
0

Here is the algorithm:

```<code>int sum = 0
for (int i = 2N; i > 0; i = i / 4)
  for (int j = 0; j < i; j+=2)
    sum++
  end for
end for
</code>```

I figured this would be linearithmic, but it's just linear. I would appreciate seeing a formalized summation and not a qualitative explanation. I have tried doing this but I fail to get linear runtime.

答:
At the first external iteration you increment sum about N times, at the second - about N / 4 times, then about N / 16 times, etc. So the total number will be around N + N / 4 + N / 16 + N / 64 + ... which is an equivalent of 4N / 3.

You can easily prove it in a more formal way, but it would be off-topic for SO community. Therefore you complexity is just linear.

Body:
0

Here is the algorithm:

int sum = 0
for (int i = 2N; i > 0; i = i / 4)
  for (int j = 0; j < i; j+=2)
    sum++
  end for
end for

I figured this would be linearithmic, but it's just linear. I would appreciate seeing a formalized summation and not a qualitative explanation. I have tried doing this but I fail to get linear runtime.


问:
Check whether certain function is used inside a nested function in R
I want to create a function check_sym that takes another function f as argument and checks whether inside f a specific function is used.

Specifically I want to check if inside f non-standard evaluation in the form of !! sym is used.

I can do this with a simple trick that turns a functions body into a character string and then uses regex to check for "!!sym\\(".

library(dplyr)
library(purrr)
library(rlang)

check_sym <- function(f) {
  f <- as.list(body(f))
  f <- unlist(as.character(f))
  purrr::some(f, function(x) grepl("!!sym\\(", x))
}

foo <- function(df, x) {
  select(df, !! sym(x))
}

check_sym(foo)
#> [1] TRUE
```

<p><sup>Created on 2020-02-16 by the reprex package (v0.3.0)</sup></p>

<p>However, while this is possible, I am looking for a way that does not rely on character strings and regex, but rather ideally some method which looks inside the function and "sees" all function calls at a deeper level, which would be more reliable.</p>

<p>Any ideas appreciated.</p>

<p><strong>Final solution based on accepted answer:</strong></p>

<p>Based on MrFlick's answer below my actual solution is the following:</p>

<p>I define check_syms as:</p>

<pre class="lang-r prettyprint-override"><code>check_sym <- function(f) {
  grepl("!!sym", paste(all.names(body(f)), collapse = ""))
}
</code>```

It correctly identifies functions which make a function call to "!! sym" compared to functions that only call for example paste0("!!sym").

foo <- function(df, x) {
  select(df, !! sym(x))
}

test_f <- function(x) {
  print(paste0("!!sym", x))
}

check_sym(foo)
#> [1] TRUE

check_sym(test_f)
#> [1] FALSE
```

答:
You could use the all.names function. It pulls out the names of all the variables/function defined inside the function

```<code>all.names(body(foo))
# [1] "{"      "select" "df"     "!"      "!"      "sym"
# [7] "x"
</code>```

Part of the problem with your specific example is that !!sym isn't really a simple variable. It's more like a call to !(!(sym)) to the parser. The !! stuff really isn't a special operator to the R parser, it's just two calls to the negation operator which rlang re-interprets via non-standard evaluation.

Body:
I want to create a function check_sym that takes another function f as argument and checks whether inside f a specific function is used.

Specifically I want to check if inside f non-standard evaluation in the form of !! sym is used.

I can do this with a simple trick that turns a functions body into a character string and then uses regex to check for "!!sym\\(".

library(dplyr)
library(purrr)
library(rlang)

check_sym <- function(f) {
  f <- as.list(body(f))
  f <- unlist(as.character(f))
  purrr::some(f, function(x) grepl("!!sym\\(", x))
}

foo <- function(df, x) {
  select(df, !! sym(x))
}

check_sym(foo)
#> [1] TRUE

Created on 2020-02-16 by the reprex package (v0.3.0)

However, while this is possible, I am looking for a way that does not rely on character strings and regex, but rather ideally some method which looks inside the function and "sees" all function calls at a deeper level, which would be more reliable.

Any ideas appreciated.

Final solution based on accepted answer:

Based on MrFlick's answer below my actual solution is the following:

I define check_syms as:

check_sym <- function(f) {
  grepl("!!sym", paste(all.names(body(f)), collapse = ""))
}

It correctly identifies functions which make a function call to "!! sym" compared to functions that only call for example paste0("!!sym").

foo <- function(df, x) {
  select(df, !! sym(x))
}

test_f <- function(x) {
  print(paste0("!!sym", x))
}

check_sym(foo)
#> [1] TRUE

check_sym(test_f)
#> [1] FALSE

Body:
You could use the all.names function. It pulls out the names of all the variables/function defined inside the function

all.names(body(foo))
# [1] "{"      "select" "df"     "!"      "!"      "sym"
# [7] "x"

Part of the problem with your specific example is that !!sym isn't really a simple variable. It's more like a call to !(!(sym)) to the parser. The !! stuff really isn't a special operator to the R parser, it's just two calls to the negation operator which rlang re-interprets via non-standard evaluation.


问:
Outlook VBA: Items.Count is overflowing when trying to loop backwards through a collection of appointments to delete them
I am trying to create a macro that will delete all Appointments from the outlook calendar that have the subject 'Move to Marketing Questionnaire'. I followed this instruction from microsoft docs to find and list all of the appointments that I'm looking for, but when I go to delete them I know that I have to switch from a For each loop to a For loop and loop backwards due to the way collections are indexed, otherwise the code misses some appointments.

When I make this change, the for loop is failing because the index is an Integer and the output of the Debug.print oItemsWithSubjectRange.Count is (overflowing?) to 2147483647. Is there a different command to get the number of appointments found with the two filters I've applied?

I'm expecting this macro to need to delete up to 50 appointments at the absolute max (normally 10-20) so an Integer should be sufficient for my needs.

Here is my code - I have included the original For each loop at the bottom (commented) which is able to print the right appointments that I want to delete, but when I run the code it misses some appointments. The For loop above it is causing Runtime error 6: Overflow errors.

Sub deleteMoveToMarketing()

    Dim myStart As Date
    Dim myEnd As Date
    Dim oCalendar As Outlook.Folder
    Dim oItems As Outlook.Items
    Dim oItemsWithDateRange As Outlook.Items
    Dim oItemsWithSubjectRange As Outlook.Items
    Dim oAppt As Outlook.AppointmentItem
    Dim strRestriction As String
    Dim i As Integer

    myStart = Date - 30
    myEnd = Date

    Debug.Print "Start:", myStart
    Debug.Print "End:", myEnd

    'Construct filter for the next 30-day date range
    strRestriction = "[Start] >= '" & _
    Format$(myStart, "mm/dd/yyyy hh:mm AMPM") _
    & "' AND [End] <= '" & _
    Format$(myEnd, "mm/dd/yyyy hh:mm AMPM") & "'"
    'Check the restriction string
    Debug.Print strRestriction

    Set oCalendar = Application.Session.GetDefaultFolder(olFolderCalendar)
    Set oItems = oCalendar.Items
    oItems.IncludeRecurrences = True
    oItems.Sort "[Start]"
    'Restrict the Items collection for the date range
    Set oItemsWithDateRange = oItems.Restrict(strRestriction)

    'Construct filter for the subject restriction
    strRestriction = "[Subject] = 'Move to Marketing Questionnaire'"
    'Check the restriction string
    Debug.Print strRestriction

    'Restrict the Items collection for the date range
    Set oItemsWithSubjectRange = oItemsWithDateRange.Restrict(strRestriction)

    'Construct filter for Subject containing 'team'
    Debug.Print oItemsWithSubjectRange.Count
    For i = oItemsWithSubjectRange.Count To 1 Step -1
        Debug.Print oItemsWithSubjectRange(i).Start, oItemsWithSubjectRange(i).Subject
        'oItemsWithSubjectRange(i).Delete
    Next

    'For Each oAppt In oItemsWithSubjectRange
        'Debug.Print oAppt.Start, oAppt.Subject
        'oAppt.Delete
    'Next

End Sub
```

答:
In your case, Items.Count returns -1 because the collection does not know how many items are there unless it expands all recurring activities. </p>

<p>Since occurrences are included, you end up deleting instances of recurring activities (which do not physically exists as real items). This may or may not be what you want </p>

Body:
In your case, Items.Count returns -1 because the collection does not know how many items are there unless it expands all recurring activities.

Since occurrences are included, you end up deleting instances of recurring activities (which do not physically exists as real items). This may or may not be what you want


问:
How can I convert string to datetime?
How can I convert string column  to datetime in pandas?

My columns is as follows

```<code>Date

01Jan2019
01Feb2019
01Mar2019

</code>```

How can I convert this to a pandas date time?

答:
The following code will convert your String column to datetime64</p>

```<code>df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True)
</code>```

Title: How can I convert string to datetime?

Body:
How can I convert string column  to datetime in pandas?

My columns is as follows

Date

01Jan2019
01Feb2019
01Mar2019

How can I convert this to a pandas date time?

Body:
The following code will convert your String column to datetime64

df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True)


问:
How likely are two blocks of data likely to produce the same CRC64 value?
I have an caching application that uses a CRC64 value to ensure data integrity.
I'm thinking about putting an extra field, a timestamp to be passed around with the data
between the various cache servers and compared to see if data has changed.

However, this requires protocol changes.  While that's not a huge deal,  I already have
a CRC64 that could be used as an indicator that something has changed.

Does anyone know the stats around two blocks of data producing the same CRC64? If not, how could I compute it or estimate it's likelyhood?

答:
The probability of two CRC64s over different random data being identical would be something close to 1 chance in 2** 64.  But since CRCs are somewhat sensitive to data patterns, there could be degenerate cases where you'd lose several binary orders of protection.  It's probably not possible to come up with a hard number, but you'd likely be safe in assuming the worst case chance of collision would be less than 1 chance in 2** 50 or so.

You'd be assured of getting closer to the theoretical limit if you used a cryptographic hash instead of a CRC64, but the crypto hash is generally much more expensive to compute.


问:
Git "fatal: Unable to read current working directory: No such file or directory" in existing repo
I have a repo on a network drive with a proper .git folder etc.

I am able to do everything I want with git version 2.20.1.windows.1 on my machine (push/pull/branches etc.)

I am now trying to use the exact same folder on another machine with git version 2.25.0.windows.1.

The remote repo sits on AWS CodeCommit and I've verified that I can connect to it using the steps outlined here from the new machine.

No matter which git operation I try on the new machine, I get fatal: Unable to read current working directory: No such file or directory. This includes trying to clone a repo into a new folder as well, not just operations on the existing repo/folder.

I can navigate to the folder and list its contents

Am I missing something obvious ?

答:
This is linked to the actual version of git. Will install an older one.

https://github.com/git-for-windows/git/issues/2480