问:
ImportError pyzbar macbook m1
Iam using the m1 Macbook Pro and facing error when running my code using pyzbar. I have also downloaded pyzbar and zbar. I have homebrew installed and used brew install zbar and pip3 install pyzbar

Below is the full error:-

```<code>Traceback (most recent call last):
  File "/Users/irajgupta/Desktop/PythonFiles/BarcodeScanner .py", line 4, in <module>
    from pyzbar.pyzbar import decode
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/pyzbar.py", line 7, in <module>
    from .wrapper import (
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/wrapper.py", line 139, in <module>
    zbar_version = zbar_function(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/wrapper.py", line 136, in zbar_function
    return prototype((fname, load_libzbar()))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/wrapper.py", line 115, in load_libzbar
    libzbar, dependencies = zbar_library.load()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/zbar_library.py", line 65, in load
    raise ImportError('Unable to find zbar shared library')
ImportError: Unable to find zbar shared library
</code>```

Below is my code:-

```<code>from tkinter import*
from PIL import ImageTk,Image
import cv2
from pyzbar.pyzbar import decode

root=Tk()
root.title("Barcode Scanner")
root.configure(bg="tan4")
root.geometry("300x400")

vdo=Label(root)
vdo.grid(padx=10,pady=10)

cap=cv2.VideoCapture(0)

def readBarcode(frame):
    barcodes=decode(frame)
    txt.delete(0,END)
    for a in barcodes:
        x,y,w,h=a.rect
        a_info=barcode.data.decode('utf-8')
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
        font=cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame,a_info,(x-6,y-6),font,1.0,(0,0,0),1)
        txt.insert(0,a_info+" ")
    return frame

def video_stream():
    _,frame=cap.read()
    frame=cv2.resize(frame,(250,250))
    frame=cv2.copyMakeBorder(frame,10,10,10,10,cv2.BORDER_CONSTANT)
    frame=readBarcode(frame)
    cv2Image=cv2.cvtColor(frame,cv2.COLOR_BGR2RGBA)
    img=Image.fromarray(cv2Image)
    imgtk=ImageTk.PhotoImage(image=img)
    vdo.imgtk=imgtk
    vdo.configure(image=imgtk)
    vdo.after(1,video_stream)

txt=Entry(root,width=25)
txt.grid(pady=25)

video_stream()
root.mainloop()
</code>```

Pls help me to fix this error I havent found any solution yet.

答:
Try this:

First uninstall pyzbar and zbar. Then start installing zbar using brew install zbar. Then install pyzbar using the command pip install pyzbar if you want to run command line scripts dependencies you have to run the command pip install pyzbar[scripts]

You can read more from here.

Title: ImportError pyzbar macbook m1

Body:
Iam using the m1 Macbook Pro and facing error when running my code using pyzbar. I have also downloaded pyzbar and zbar. I have homebrew installed and used brew install zbar and pip3 install pyzbar

Below is the full error:-

Traceback (most recent call last):
  File "/Users/irajgupta/Desktop/PythonFiles/BarcodeScanner .py", line 4, in <module>
    from pyzbar.pyzbar import decode
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/pyzbar.py", line 7, in <module>
    from .wrapper import (
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/wrapper.py", line 139, in <module>
    zbar_version = zbar_function(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/wrapper.py", line 136, in zbar_function
    return prototype((fname, load_libzbar()))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/wrapper.py", line 115, in load_libzbar
    libzbar, dependencies = zbar_library.load()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyzbar/zbar_library.py", line 65, in load
    raise ImportError('Unable to find zbar shared library')
ImportError: Unable to find zbar shared library

Below is my code:-

from tkinter import*
from PIL import ImageTk,Image
import cv2
from pyzbar.pyzbar import decode

root=Tk()
root.title("Barcode Scanner")
root.configure(bg="tan4")
root.geometry("300x400")

vdo=Label(root)
vdo.grid(padx=10,pady=10)

cap=cv2.VideoCapture(0)

def readBarcode(frame):
    barcodes=decode(frame)
    txt.delete(0,END)
    for a in barcodes:
        x,y,w,h=a.rect
        a_info=barcode.data.decode('utf-8')
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
        font=cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame,a_info,(x-6,y-6),font,1.0,(0,0,0),1)
        txt.insert(0,a_info+" ")
    return frame

def video_stream():
    _,frame=cap.read()
    frame=cv2.resize(frame,(250,250))
    frame=cv2.copyMakeBorder(frame,10,10,10,10,cv2.BORDER_CONSTANT)
    frame=readBarcode(frame)
    cv2Image=cv2.cvtColor(frame,cv2.COLOR_BGR2RGBA)
    img=Image.fromarray(cv2Image)
    imgtk=ImageTk.PhotoImage(image=img)
    vdo.imgtk=imgtk
    vdo.configure(image=imgtk)
    vdo.after(1,video_stream)

txt=Entry(root,width=25)
txt.grid(pady=25)

video_stream()
root.mainloop()

Pls help me to fix this error I havent found any solution yet.


来源: stackexchange

问:
How to Get Access Token and User Info: IdentityServer4 With AspNet Identity
Good day everyone,

So I successfully integrated IdentityServer 4 using AspNet Identity for authentication  into my project. It redirects to the client after authentication, so thats fine. The problem now is that I would like to get the user details on the client, like their username, email, firstname and lastname. I wanted to call the userinfo endpoint with a token, but I cannot get a token. I get the following errors:

Client not authorized for client credentials flow, check the AllowedGrantTypes setting - When I use GrantType.Authorization Code in client config

client cannot request openid scopes in client credentials flow - When I use GrantType.ClientCredentials

The The client has been setup in startup.cs as;

```<code>services.AddAuthentication(options =>
            {
                options.DefaultScheme = "cookie";
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("cookie")
            .AddOpenIdConnect("oidc", options =>
            {
                options.Authority = ConfigurationManager.AppSettings["AuthorityUrl"];
                options.ClientId = ConfigurationManager.AppSettings["ClientId"];
                options.ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
                options.RequireHttpsMetadata = false;
                options.GetClaimsFromUserInfoEndpoint = true;

                options.ResponseType = "code";
                options.UsePkce = true;
                options.ResponseMode = "query";

                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.SaveTokens = true;

            });
</code>```

And my client configuration currently is as follows;

```<code>new Client
                    {
                         ClientName = "Admin Client",
                         ClientId = "admin.client",
                         AllowedGrantTypes = GrantTypes.Code,
                         ClientSecrets = { new Secret("secretkey".Sha256()) },
                         AllowedScopes =new List<string> {
                               IdentityServerConstants.StandardScopes.OpenId,
                               IdentityServerConstants.StandardScopes.Profile
                            },
                         RedirectUris = {"https://localhost:44324/signin-oidc"},
                         FrontChannelLogoutUri = "https://localhost:44324/signout-oidc",
                         PostLogoutRedirectUris = {"https://localhost:44324/signout-callback-oidc"},

                         AllowOfflineAccess = true,
                         RequirePkce = true,
                         RequireConsent = false,
                         AllowPlainTextPkce = false

                    }
</code>```

To get token, I do this (when I use GrantType.ClientCredentials in Client config;

```<code>using var client = new HttpClient();
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = _discoveryDocument.TokenEndpoint,
                ClientId = ConfigurationManager.AppSettings["ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["ClientSecret"],
                Scope = "openid"

            });
</code>```

And I call user like this:

```<code>var response = await client.GetUserInfoAsync(new UserInfoRequest
            {
                Address = _discoveryDocument.UserInfoEndpoint,
                Token = token
            });
</code>```

but it never gets to the userinfo though.
Please note that I have been changing the GrantTypes in the client config to Hybrid, AuhorizationCode, it still doesn't work. When I use AuthorizationCode grantType and Use RequestAuthorizationCodeTokenAsync, it request for Code in the parameters, but I don't know how to get the authorization code (sorry, I'm new to this please).

So please how should I configure my client in order to be able to request token that I can use in the userinfo endpoint or is there any way I can get the user info?

Please help.
Thanks.

答:
To get the user detail you use Claims

basically you call it like this

@User.Claims.FirstOrDefault(c => c.Type == "name")?.Value (on cshtml page)

or

User.Claims.Where(c => c.Type == "mail").First().Value (on .cs class)

ContentLicense: CC BY-SA 4.0

Body:
Good day everyone,

So I successfully integrated IdentityServer 4 using AspNet Identity for authentication  into my project. It redirects to the client after authentication, so thats fine. The problem now is that I would like to get the user details on the client, like their username, email, firstname and lastname. I wanted to call the userinfo endpoint with a token, but I cannot get a token. I get the following errors:

Client not authorized for client credentials flow, check the AllowedGrantTypes setting - When I use GrantType.Authorization Code in client config

client cannot request openid scopes in client credentials flow - When I use GrantType.ClientCredentials

The The client has been setup in startup.cs as;

services.AddAuthentication(options =>
            {
                options.DefaultScheme = "cookie";
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("cookie")
            .AddOpenIdConnect("oidc", options =>
            {
                options.Authority = ConfigurationManager.AppSettings["AuthorityUrl"];
                options.ClientId = ConfigurationManager.AppSettings["ClientId"];
                options.ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
                options.RequireHttpsMetadata = false;
                options.GetClaimsFromUserInfoEndpoint = true;

                options.ResponseType = "code";
                options.UsePkce = true;
                options.ResponseMode = "query";

                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.SaveTokens = true;

            });

And my client configuration currently is as follows;

new Client
                    {
                         ClientName = "Admin Client",
                         ClientId = "admin.client",
                         AllowedGrantTypes = GrantTypes.Code,
                         ClientSecrets = { new Secret("secretkey".Sha256()) },
                         AllowedScopes =new List<string> {
                               IdentityServerConstants.StandardScopes.OpenId,
                               IdentityServerConstants.StandardScopes.Profile
                            },
                         RedirectUris = {"https://localhost:44324/signin-oidc"},
                         FrontChannelLogoutUri = "https://localhost:44324/signout-oidc",
                         PostLogoutRedirectUris = {"https://localhost:44324/signout-callback-oidc"},

                         AllowOfflineAccess = true,
                         RequirePkce = true,
                         RequireConsent = false,
                         AllowPlainTextPkce = false

                    }

To get token, I do this (when I use GrantType.ClientCredentials in Client config;

using var client = new HttpClient();
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = _discoveryDocument.TokenEndpoint,
                ClientId = ConfigurationManager.AppSettings["ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["ClientSecret"],
                Scope = "openid"

            });

And I call user like this:

var response = await client.GetUserInfoAsync(new UserInfoRequest
            {
                Address = _discoveryDocument.UserInfoEndpoint,
                Token = token
            });

but it never gets to the userinfo though.
Please note that I have been changing the GrantTypes in the client config to Hybrid, AuhorizationCode, it still doesn't work. When I use AuthorizationCode grantType and Use RequestAuthorizationCodeTokenAsync, it request for Code in the parameters, but I don't know how to get the authorization code (sorry, I'm new to this please).

So please how should I configure my client in order to be able to request token that I can use in the userinfo endpoint or is there any way I can get the user info?

Please help.
Thanks.


问:
Hosting ASP.NET on Raspberry Pi 3B+ for local network
I am trying to host an API (ASP.NET) on my Raspberri Pi 3B +. I would like to access this API swagger page from my laptop/phone/pc etc.

What I've tried until now:
Installed, compiled, built and ran the web application with dotnet on my RPi.

running dotnet --info  on the RPi provides us the following information:

```<code>.NET SDK (reflecting any global.json):
 Version:   5.0.405
 Commit:    63325e1c7d

Runtime Environment:
 OS Name:     raspbian
 OS Version:  11
 OS Platform: Linux
 RID:         linux-arm
 Base Path:   /usr/share/dotnet/sdk/5.0.405/

Host (useful for support):
  Version: 5.0.14
  Commit:  d5b56c6327

.NET SDKs installed:
  5.0.405 [/usr/share/dotnet/sdk]

.NET runtimes installed:
  Microsoft.AspNetCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
</code>```

When I run the program (filepath ~/first-rpi-api/bin/Release/net5.0/publish/first-rpi-api)

I get the following:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/pi/first-rpi-api/bin/Release/net5.0/publish
```

The default URL for the swagger UI would be : https://localhost:44335/swagger/index.html
However when I try to access the API from my PC on URL : https://RPi_IP:5000/swagger/index.html

I get ERR_CONNECTION_REFUSED

How do I fix this ? Have I missed something and how would I approach this problem ?

答:
Using the previous answer (refering to omajid's answer) provides us only a temporary solution.

Whenever you reboot the Raspberry Pi you would need to execute the command

export ASPNETCORE_URLS="http://*:5000;https://*:5001"
```
<p>again and again.</p>
<p>To prevent this, I suggest using the <code>IHostBuilder.UseUrls("URLS")</code> method.</p>
<p>In your case you would need to edit your <code>Program.cs</code> and add the following line in the CreateHostBuilder method.</p>
<pre class="lang-cs prettyprint-override"><code>public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();

                    //THIS LINE
                    webBuilder.UseUrls("http://*:5000;https://*:5001");
                });
</code>```

This will automatically ensures that you can access the API from whichever device you'd like.

You can read more about this in this article :

Body:
I am trying to host an API (ASP.NET) on my Raspberri Pi 3B +. I would like to access this API swagger page from my laptop/phone/pc etc.

What I've tried until now:
Installed, compiled, built and ran the web application with dotnet on my RPi.

running dotnet --info  on the RPi provides us the following information:

.NET SDK (reflecting any global.json):
 Version:   5.0.405
 Commit:    63325e1c7d

Runtime Environment:
 OS Name:     raspbian
 OS Version:  11
 OS Platform: Linux
 RID:         linux-arm
 Base Path:   /usr/share/dotnet/sdk/5.0.405/

Host (useful for support):
  Version: 5.0.14
  Commit:  d5b56c6327

.NET SDKs installed:
  5.0.405 [/usr/share/dotnet/sdk]

.NET runtimes installed:
  Microsoft.AspNetCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

When I run the program (filepath ~/first-rpi-api/bin/Release/net5.0/publish/first-rpi-api)

I get the following:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/pi/first-rpi-api/bin/Release/net5.0/publish

The default URL for the swagger UI would be : https://localhost:44335/swagger/index.html
However when I try to access the API from my PC on URL : https://RPi_IP:5000/swagger/index.html

I get ERR_CONNECTION_REFUSED

How do I fix this ? Have I missed something and how would I approach this problem ?

Body:
Using the previous answer (refering to omajid's answer) provides us only a temporary solution.

Whenever you reboot the Raspberry Pi you would need to execute the command

export ASPNETCORE_URLS="http://*:5000;https://*:5001"

again and again.

To prevent this, I suggest using the IHostBuilder.UseUrls("URLS") method.

In your case you would need to edit your Program.cs and add the following line in the CreateHostBuilder method.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();

                    //THIS LINE
                    webBuilder.UseUrls("http://*:5000;https://*:5001");
                });

This will automatically ensures that you can access the API from whichever device you'd like.

You can read more about this in this article :


问:
Python iterating through data and returning deltas
Python newbie here with a challenge I'm working to solve...

My goal is to iterate through a data frame and return what changed line by line. Here's what I have so far:

pseudo code (may not be correct method)
step 1: set row 0 to an initial value
step 2: compare row 1 to row 0, add changes to a list and record row number
step 3: set current row to new initial
step 4: compare row 2 to row 1, add changes to a list and record row number
step 5: iterate through all rows
step 6: return a table with changes and row index where change occurred

```<code>d = {
'col1' : [1, 1, 2, 2, 3],
'col2' : [1, 2, 2, 2, 2],
'col3' : [1, 1, 2, 2, 2]
}

df = pd.DataFrame(data=d)

def delta():
    changes = []
    initial = df.loc[0]
    for row in df:
         if row[i] != initial:
              changes.append[i]
delta()
</code>```

changes I expect to see:
index 1: col2 changed from 1 to 2, 2 should be added to changes list
index 2: col 1 and col3 changed from 1 to 2, both 2s should be added to changes list
index 4: col 1 changed from 2 to 3, 3 should be added to changes list

答:
You can use the pandas function diff() which will already provide the increment compared to the previous row:

import pandas as pd

d = {
'col1' : [1, 1, 2, 2, 3],
'col2' : [1, 2, 2, 2, 2],
'col3' : [1, 1, 2, 2, 2]
}

df = pd.DataFrame(data=d)

def delta(df):
    deltas = df.diff()                # will convert to float because this is needed to set Nans in the first row
    deltas.iloc[0] = df.iloc[0]       # replace Nans in first row with original data from first row
    deltas = deltas.astype(df.dtypes) # reset data types according to input data
    filter = (deltas!=0).any(axis=1)  # filter to use only those rows where all values are non zero
    filter.iloc[0] = True             # make sure the first row is included even if original data for first row held only zeros
    deltas = deltas.loc[filter]       # actually apply the filter
    return deltas

print( delta(df) )
```
<p>This prints:</p>
```   col1  col2  col3
0     1     1     1
1     0     1     0
2     1     0     1
4     1     0     0
```

Body:
Python newbie here with a challenge I'm working to solve...

My goal is to iterate through a data frame and return what changed line by line. Here's what I have so far:

pseudo code (may not be correct method)
step 1: set row 0 to an initial value
step 2: compare row 1 to row 0, add changes to a list and record row number
step 3: set current row to new initial
step 4: compare row 2 to row 1, add changes to a list and record row number
step 5: iterate through all rows
step 6: return a table with changes and row index where change occurred

d = {
'col1' : [1, 1, 2, 2, 3],
'col2' : [1, 2, 2, 2, 2],
'col3' : [1, 1, 2, 2, 2]
}

df = pd.DataFrame(data=d)

def delta():
    changes = []
    initial = df.loc[0]
    for row in df:
         if row[i] != initial:
              changes.append[i]
delta()

changes I expect to see:
index 1: col2 changed from 1 to 2, 2 should be added to changes list
index 2: col 1 and col3 changed from 1 to 2, both 2s should be added to changes list
index 4: col 1 changed from 2 to 3, 3 should be added to changes list

Body:
You can use the pandas function diff() which will already provide the increment compared to the previous row:

import pandas as pd

d = {
'col1' : [1, 1, 2, 2, 3],
'col2' : [1, 2, 2, 2, 2],
'col3' : [1, 1, 2, 2, 2]
}

df = pd.DataFrame(data=d)

def delta(df):
    deltas = df.diff()                # will convert to float because this is needed to set Nans in the first row
    deltas.iloc[0] = df.iloc[0]       # replace Nans in first row with original data from first row
    deltas = deltas.astype(df.dtypes) # reset data types according to input data
    filter = (deltas!=0).any(axis=1)  # filter to use only those rows where all values are non zero
    filter.iloc[0] = True             # make sure the first row is included even if original data for first row held only zeros
    deltas = deltas.loc[filter]       # actually apply the filter
    return deltas

print( delta(df) )

This prints:

   col1  col2  col3
0     1     1     1
1     0     1     0
2     1     0     1
4     1     0     0


问:
How to extract elements of an array in object type in c#?
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

```<code>int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (<b>of a priory unknown type and I cannot use type conversion in the code </b>
//How can extract elements of obj and use them, e.g. write them on the screen?`
</code>```

答:
Once you assign the array as the value of obj, you have made a cast. You will have to retrieve an item by casting again:

```<code>int[] array = new int[] { 0, 1, 2 };
object obj = array;

var i = ((int[])obj)[0];
</code>```

If you don't know the type of the array, you will have to use generics:

```<code>object obj;

void StoreArray<T>(T array)
{
    obj = array;
}

T GetValue<T>(int index)
{
    return (T)(obj as T[])[index];
}
</code>```

Note: unntested sample.

ContentLicense: CC BY-SA 3.0

Body:
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (of a priory unknown type and I cannot use type conversion in the code
//How can extract elements of obj and use them, e.g. write them on the screen?`

Body:
Once you assign the array as the value of obj, you have made a cast. You will have to retrieve an item by casting again:

int[] array = new int[] { 0, 1, 2 };
object obj = array;

var i = ((int[])obj)[0];

If you don't know the type of the array, you will have to use generics:

object obj;

void StoreArray<T>(T array)
{
    obj = array;
}

T GetValue<T>(int index)
{
    return (T)(obj as T[])[index];
}

Note: unntested sample.


问:
Finding the most frequent character in a string using binary search
Suppose you are given a string of length n and there are 26 ASCII characters that can constitute the string. Identical characters are grouped together in the string (e.g aaabbbcccddd). Find the most frequent character.

The brute force is to scan the entire string and iteratively count the number of characters which takes O(n) time with O(1) space. Is there a O(log n) solution for this? I was given a hint to binary search to find the partition that contains the most frequent character, but I am not sure how binary search would help me eliminating the half of the string.

答:
As your characters are grouped the problem is reduced to finding longest sequence of consequent letters...

So yes you can use binary search to find the size of each sequence which is O(m.log(n)) where m<=n is the number of sequences (distinct letters). As you stated m<=26 you can consider it as constant leading to O(log(n))

The algo would be something like this:

consider your string is char s[n]; and result int l=0;

for (i=0;i<n;)

binary search j position

of last character the where s[i]==s[j] where i <= j < n

remember max l=max(l , j+1-i)

i=j+1

continue the loop from #2

However note that any letter can have only single sequence so strings like abaaaaaa will not work.


问:
Why a Query Is Not Added to the Cache in OBIEE12c
Some cases query results do not insert in the cache where the  logical sql query was suppose to insert into the cache. As a result, frequently cache missed occurs. Would anyone please explain the reasons for not insert a query result into the obiee12c cache.</p>

答:
The following describes some situation when this might occur

Noncacheable SQL element.

Noncacheable table.

Cache hit

Result set is too big.

Query is cancelled

More details please go through the following document.

https://docs.oracle.com/middleware/1221/biee/BIESG/configfileref.htm#BIESG357


问:
OSError: /usr/lib/libyara.so: cannot open shared object file: No such file or directory
I have some issue trying to run Volatility 3 Framework.

```<code>git clone https://github.com/volatilityfoundation/volatility3.git
cd volatility3/
python3 vol.py ../ramdumps/1289.raw windows.pslist.PsList
</code>```

I got this error traceback:

```<code>Volatility 3 Framework 2.0.0
Failed to import '/usr/lib/libyara.so'
PATH = /home/user/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/go/bin:/home/user/go/bin;/usr/lib
Traceback (most recent call last):
  File "vol.py", line 10, in <module>
    volatility3.cli.main()
  File "/home/user/Documents/volatility3/volatility3/cli/__init__.py", line 625, in main
    CommandLine().run()
  File "/home/user/Documents/volatility3/volatility3/cli/__init__.py", line 229, in run
    True)  # Will not log as console's default level is WARNING
  File "/home/user/Documents/volatility3/volatility3/framework/__init__.py", line 127, in import_files
    ignore_errors)
  File "/home/user/Documents/volatility3/volatility3/framework/__init__.py", line 152, in import_file
    importlib.import_module(module)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/user/Documents/volatility3/volatility3/framework/plugins/yarascan.py", line 17, in <module>
    import yara
  File "/home/user/.local/lib/python3.6/site-packages/yara/__init__.py", line 7, in <module>
    from yara.rules import compile
  File "/home/user/.local/lib/python3.6/site-packages/yara/rules.py", line 17, in <module>
    from yara.libyara_wrapper import *
  File "/home/user/.local/lib/python3.6/site-packages/yara/libyara_wrapper.py", line 315, in <module>
    libyaradll = cdll.LoadLibrary(library)
  File "/usr/lib/python3.6/ctypes/__init__.py", line 426, in LoadLibrary
    return self._dlltype(name)
  File "/usr/lib/python3.6/ctypes/__init__.py", line 348, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /usr/lib/libyara.so: cannot open shared object file: No such file or directory
</code>```

Someone already had the same error a few years ago but none of the answers worked for me.

I'm using python 3.6.9 and Xubuntu 18.04.6

答:
Did you install the requirements with
pip3 install -r requirements.txt
?

Body:
I have some issue trying to run Volatility 3 Framework.

git clone https://github.com/volatilityfoundation/volatility3.git
cd volatility3/
python3 vol.py ../ramdumps/1289.raw windows.pslist.PsList

I got this error traceback:

Volatility 3 Framework 2.0.0
Failed to import '/usr/lib/libyara.so'
PATH = /home/user/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/go/bin:/home/user/go/bin;/usr/lib
Traceback (most recent call last):
  File "vol.py", line 10, in <module>
    volatility3.cli.main()
  File "/home/user/Documents/volatility3/volatility3/cli/__init__.py", line 625, in main
    CommandLine().run()
  File "/home/user/Documents/volatility3/volatility3/cli/__init__.py", line 229, in run
    True)  # Will not log as console's default level is WARNING
  File "/home/user/Documents/volatility3/volatility3/framework/__init__.py", line 127, in import_files
    ignore_errors)
  File "/home/user/Documents/volatility3/volatility3/framework/__init__.py", line 152, in import_file
    importlib.import_module(module)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/user/Documents/volatility3/volatility3/framework/plugins/yarascan.py", line 17, in <module>
    import yara
  File "/home/user/.local/lib/python3.6/site-packages/yara/__init__.py", line 7, in <module>
    from yara.rules import compile
  File "/home/user/.local/lib/python3.6/site-packages/yara/rules.py", line 17, in <module>
    from yara.libyara_wrapper import *
  File "/home/user/.local/lib/python3.6/site-packages/yara/libyara_wrapper.py", line 315, in <module>
    libyaradll = cdll.LoadLibrary(library)
  File "/usr/lib/python3.6/ctypes/__init__.py", line 426, in LoadLibrary
    return self._dlltype(name)
  File "/usr/lib/python3.6/ctypes/__init__.py", line 348, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /usr/lib/libyara.so: cannot open shared object file: No such file or directory

Someone already had the same error a few years ago but none of the answers worked for me.

I'm using python 3.6.9 and Xubuntu 18.04.6


问:
Nginx for block attacking requests
I am receiving requests of this type on my website (I think it's an attack):

```<code>/name-of-post/==f.charAt(f.length-1))%7Bif(f=f.substr(1,f.length-2),-1!=x.indexOf(f))return%20I=!0

/name-of-post/&&(d=!1,b=b.substring(1));var%20m=b.split
</code>```

How can I block them to return an HTTP 444 status code?

答:
In that case you know the kind of URIs and you want to block them AND under the warning that this is NOT! a 100% protection OR WAF (Web application firewall) implementation this will do the trick for the kind of URIs including a sequence of bad characters like ; %3B charAt var

  location ~ "(\bcharAt|;|\%3B|var\b)" {
  return 444 "Bad Request\n";
}
```

Be careful adding bad characters. ? and + = . are legit for example.

A better approach would be the usage of a Web Application Firewall to detect such request and block them. Look into mod_security if you want to learn more about it.

Title: Nginx for block attacking requests

Body:
I am receiving requests of this type on my website (I think it's an attack):

/name-of-post/==f.charAt(f.length-1))%7Bif(f=f.substr(1,f.length-2),-1!=x.indexOf(f))return%20I=!0

/name-of-post/&&(d=!1,b=b.substring(1));var%20m=b.split

How can I block them to return an HTTP 444 status code?

Body:
In that case you know the kind of URIs and you want to block them AND under the warning that this is NOT! a 100% protection OR WAF (Web application firewall) implementation this will do the trick for the kind of URIs including a sequence of bad characters like ; %3B charAt var

  location ~ "(\bcharAt|;|\%3B|var\b)" {
  return 444 "Bad Request\n";
}

Be careful adding bad characters. ? and + = . are legit for example.

A better approach would be the usage of a Web Application Firewall to detect such request and block them. Look into mod_security if you want to learn more about it.


问:
NEST thermostat hot water status and control missing from API
I would like to control Nest thermostat (3rd gen with heatlink) domestic hot water, however the API doesn't seem to be exposing neither it's controls nor it's status (https://developers.google.com/nest/device-access/api/thermostat). As there's clearly at least an internal API for that, which the thermostat itself is using: would it be possible to expose the same controls/stat for external use?
Use-cases:

home assistant integration

triggering a 'boost' with a push button

Update 2022-11-07:
There's a homeassistant integration called 'badnest', which is using an unofficial local API. I've noticed, that on that API for hot water readings and controls are exposed and as such made a contribution to the integration so that it would also be exposed in HA: https://github.com/badguy99/badnest/pull/11

答: This is one of the worst aspects of Best, being able to bost hot water is essential, since it is in the app when is it not available though API.  I realise this is probably because having separate water tanks that are controlled independently is not as common in the states and Nest us very USA centric, but the feature is key in the app.</p>


问:
Reordering OpenGL Texture vertices to flip image rows
I am a complete OpenGL beginner and I inherited a codebase. I want OpenGL to flip a texture in vertical direction, meaning the top row goes to the bottom and so on. I am only doing 2D processing, if that is relevant.

My texture vertices are currently this:

```<code>const float texture_vertices[] = {
    0.0, 1.0,
    0.0, 0.0,
    1.0, 0.0,
    0.0, 1.0,
    1.0, 0.0,
    1.0, 1.0,
};
</code>```

I tried changing the directions of the triangles and reordering them from going clockwise to counter clockwise. I know this is caused by my lack of awareness of how the very basics of OpenGL work, but I would appreciate all help (especially a short explanation of why something is the right way to reorder them).

Maybe I am going about this all wrong and the texture coordinates are not what I am interested in?

答:
You need to flip the 2nd component of the texture coordinates (swap 0 and 1):</p>
```<code>const float texture_vertices[] = {
    0.0, 0.0,
    0.0, 1.0,
    1.0, 1.0,
    0.0, 0.0,
    1.0, 1.0,
    1.0, 0.0,
};
</code>```

Body:
I am a complete OpenGL beginner and I inherited a codebase. I want OpenGL to flip a texture in vertical direction, meaning the top row goes to the bottom and so on. I am only doing 2D processing, if that is relevant.

My texture vertices are currently this:

const float texture_vertices[] = {
    0.0, 1.0,
    0.0, 0.0,
    1.0, 0.0,
    0.0, 1.0,
    1.0, 0.0,
    1.0, 1.0,
};

I tried changing the directions of the triangles and reordering them from going clockwise to counter clockwise. I know this is caused by my lack of awareness of how the very basics of OpenGL work, but I would appreciate all help (especially a short explanation of why something is the right way to reorder them).

Maybe I am going about this all wrong and the texture coordinates are not what I am interested in?

Body:
You need to flip the 2nd component of the texture coordinates (swap 0 and 1):

const float texture_vertices[] = {
    0.0, 0.0,
    0.0, 1.0,
    1.0, 1.0,
    0.0, 0.0,
    1.0, 1.0,
    1.0, 0.0,
};


问:
Create Excel sheet with worksheet_change code
I have code that creates a worksheet and the worksheet contains a table.
I then programmatically add an advanced filter to the table in the created worksheet.
This works fine, but the advanced filter does not refresh on change of the worksheet: A known issue.

The standard solution is to put code behind the worksheet_change event so the filter is refreshed when the worksheet changes.  This also works fine when I add this code manually.

But when I create a sheet I want to automatically create the code for the new sheets worksheet_change event.  I don't know how to programmatically specify code for my new sheet in the worksheet_change event.

Is this possible? Or is there another way to accomplish this?

答:
You can create a class module with the event and hook that to your worksheets. So you can add a hidden sheet with all workbook names that you want to add that event to.

So if you programmatically add a new sheet you just need to add its name to that list.

So first add a sheet named MyClassSheets (you can make it hidden so no user sees it). And add some sheet names there:

So this means we want to run your worksheet_change event in Sheet2 and Sheet3 only.

Then we add a class module MyWsClass:

```<code>Option Explicit

Public WithEvents Ws As Worksheet

Private Sub Ws_Change(ByVal Target As Range)
    MsgBox Target.Address(False, False) & " changed."
End Sub
</code>```

This is the event we want to run. It just shows a message box which cell was changed. You need to adjust that to your wishes.

Finally we need to hook those events to the worksheets. So we add a normal module (non-class module) HookWsEvents:

```<code>Option Explicit

Dim MyWorksheets() As New MyWsClass

Public Sub HookEvents()
    ' get list of worksheets we want to add the class
    With ThisWorkbook.Worksheets("MyClassSheets")
        Dim MyClassSheets() As Variant
        MyClassSheets = .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)).Value
    End With

    ReDim MyWorksheets(UBound(MyClassSheets) - 1)

    Dim i As Long
    ' add class to those worksheets
    Dim Ws As Variant
    For Each Ws In MyClassSheets
        Set MyWorksheets(i).Ws = ThisWorkbook.Worksheets(CStr(Ws))
        i = i + 1
    Next Ws
End Sub
</code>```

So now we just need to make sure that the procedure HookEvents is called everytime the workbook opens. So we add the following into ThisWorkbook:

```<code>Option Explicit

Private Sub Workbook_Open()
    HookEvents
End Sub
</code>```

After running HookEvents the event runs in every sheet that is listed in MyClassSheets.

If you now add a new worksheet that you want to add the event to, you just need to add it to the list in MyClassSheets and run HookEvents again. Therefore we can add a small helper procedure to our HookWsEvents module:

```<code>Public Sub AddWsToList(Ws As Worksheet)
    With ThisWorkbook.Worksheets("MyClassSheets")
        ' add the worksheet name of Ws to the list in MyClassSheets
        .Cells(.Rows.Count, "A").End(xlUp).Offset(RowOffset:=1).Value = Ws.Name
    End With
End Sub
</code>```

So now we can use the following code

```<code>' add a new worksheet as last worksheet
Dim NewWs As Worksheet
Set NewWs = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))

' give it a name
NewWs.Name = "Sheet5"

' add it to the list of MyClassSheets
AddWsToList NewWs

' hook events to all sheets
HookEvents
</code>```

to add a new worksheet and add the event to it.

You may want to add some error checking if a worksheet in the list of MyClassSheets does not exist anymore (was deleted) so your code does not thorw an unhandled exception in this case. I left this out to have the above explanation more clear.

If all your sheets have someting common in their name you don't need to maintain that MyClassSheets list. So for example if all the sheets you want to add the event to start with XYZ_ you just need to loop over all sheets in the HookEvents procedure and check if they start with XYZ_ to add them to the MyWorksheets array then. Resizing that array may be a bit more complicated then.

Body:
You can create a class module with the event and hook that to your worksheets. So you can add a hidden sheet with all workbook names that you want to add that event to.

So if you programmatically add a new sheet you just need to add its name to that list.

So first add a sheet named MyClassSheets (you can make it hidden so no user sees it). And add some sheet names there:

So this means we want to run your worksheet_change event in Sheet2 and Sheet3 only.

Then we add a class module MyWsClass:

Option Explicit

Public WithEvents Ws As Worksheet

Private Sub Ws_Change(ByVal Target As Range)
    MsgBox Target.Address(False, False) & " changed."
End Sub

This is the event we want to run. It just shows a message box which cell was changed. You need to adjust that to your wishes.

Finally we need to hook those events to the worksheets. So we add a normal module (non-class module) HookWsEvents:

Option Explicit

Dim MyWorksheets() As New MyWsClass

Public Sub HookEvents()
    ' get list of worksheets we want to add the class
    With ThisWorkbook.Worksheets("MyClassSheets")
        Dim MyClassSheets() As Variant
        MyClassSheets = .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)).Value
    End With

    ReDim MyWorksheets(UBound(MyClassSheets) - 1)

    Dim i As Long
    ' add class to those worksheets
    Dim Ws As Variant
    For Each Ws In MyClassSheets
        Set MyWorksheets(i).Ws = ThisWorkbook.Worksheets(CStr(Ws))
        i = i + 1
    Next Ws
End Sub

So now we just need to make sure that the procedure HookEvents is called everytime the workbook opens. So we add the following into ThisWorkbook:

Option Explicit

Private Sub Workbook_Open()
    HookEvents
End Sub

After running HookEvents the event runs in every sheet that is listed in MyClassSheets.

If you now add a new worksheet that you want to add the event to, you just need to add it to the list in MyClassSheets and run HookEvents again. Therefore we can add a small helper procedure to our HookWsEvents module:

Public Sub AddWsToList(Ws As Worksheet)
    With ThisWorkbook.Worksheets("MyClassSheets")
        ' add the worksheet name of Ws to the list in MyClassSheets
        .Cells(.Rows.Count, "A").End(xlUp).Offset(RowOffset:=1).Value = Ws.Name
    End With
End Sub

So now we can use the following code

' add a new worksheet as last worksheet
Dim NewWs As Worksheet
Set NewWs = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))

' give it a name
NewWs.Name = "Sheet5"

' add it to the list of MyClassSheets
AddWsToList NewWs

' hook events to all sheets
HookEvents

to add a new worksheet and add the event to it.

You may want to add some error checking if a worksheet in the list of MyClassSheets does not exist anymore (was deleted) so your code does not thorw an unhandled exception in this case. I left this out to have the above explanation more clear.

If all your sheets have someting common in their name you don't need to maintain that MyClassSheets list. So for example if all the sheets you want to add the event to start with XYZ_ you just need to loop over all sheets in the HookEvents procedure and check if they start with XYZ_ to add them to the MyWorksheets array then. Resizing that array may be a bit more complicated then.


问:
How to use a join table when query also contains geography data, in a multi-id query?
Places Table

PlaceId PK

Name

GeoPoint (GeoPoint type)

etc...

PlaceCats Table (the join table)

PlaceId PK FK

CatId PK FK

PlaceCategories Table

CatId PK

Name

etc...

Here's my query, to return places, with entries in the PlaceCats table (by a series of catIds), and within 25km of a Lat/Lng value.

```<code>SELECT Places.*
FROM Places
     INNER JOIN PlaceCats
             ON Places.PlaceId = PlaceCats.PlaceId
WHERE PlaceCats.CatId IN (2,3,4,5)
AND Places.GeoPoint.STDistance(geography::Point(35.75094975999387, 139.39780220389366, 4326)) < ((25 * 1000))
ORDER BY Places.Name ASC
</code>```

It's returning places, but I need to add DISTINCT after the SELECT... apparently you can't use DISTINCT when selecting geography data. I need to make sure I'm not getting the same place multiple times (as they can have multiple entries in the join table).

Update

When I insert a place into the Places table, the GeoPoint is set like so:

```<code>SqlGeography.Point(sentPlace.Lat.Value, sentPlace.Lng.Value, 4326);
</code>```

答:
It look to me like you have your long/lats the wrong way round.

As for selecting DISTINCT geographies, you can perform the DISTINCT operation over the WKT (Well Known Text) in a nested query, see below:

```<code>SELECT
GEOGRAPHY::STGeomFromText(WKT, [PROJECTION]) AS GEOG
FROM
(
    SELECT DISTINCT
    GEOG.STAsText() AS WKT
    FROM
    [TABLE_NAME]
) a
</code>```

Your query would look something like this:

```<code>SELECT
    a.*
,   GEOGRAPHY::STGeomFromText(WKT, 4326) AS GEOG
FROM
(
    SELECT DISTINCT
        Places.[COL1]
    ,   Places.[COL2]
    ,   Places.[COL3]
    ,   Places.[COL4]
    ...
    ...
    ,   Places.GeoPoint.STAsText() AS WKT
    FROM
    Places
    INNER JOIN
    PlaceCats
    ON
    Places.PlaceId = PlaceCats.PlaceId
    WHERE PlaceCats.CatId IN (2,3,4,5)
    AND
    Places.GeoPoint.STDistance(GEOGRAPHY::Point(35.75094975999387, 139.39780220389366, 4326)) < ((25 * 1000))
    ORDER BY Places.Name ASC
)a
</code>```

One further tip, assuming you have a spatial index on your table, it speeds spatial queries up no end by using an index hit:

```<code>SELECT *
FROM
[TABLE_NAME] WITH(INDEX([INDEX_NAME]))
WHERE
GEOG.STIntersects.(GEOGRAPHY::Point([Longitude], [Latitude], 4326)) = 1
</code>```

Body:
Places Table

PlaceId PK

Name

GeoPoint (GeoPoint type)

etc...

PlaceCats Table (the join table)

PlaceId PK FK

CatId PK FK

PlaceCategories Table

CatId PK

Name

etc...

Here's my query, to return places, with entries in the PlaceCats table (by a series of catIds), and within 25km of a Lat/Lng value.

SELECT Places.*
FROM Places
     INNER JOIN PlaceCats
             ON Places.PlaceId = PlaceCats.PlaceId
WHERE PlaceCats.CatId IN (2,3,4,5)
AND Places.GeoPoint.STDistance(geography::Point(35.75094975999387, 139.39780220389366, 4326)) < ((25 * 1000))
ORDER BY Places.Name ASC

It's returning places, but I need to add DISTINCT after the SELECT... apparently you can't use DISTINCT when selecting geography data. I need to make sure I'm not getting the same place multiple times (as they can have multiple entries in the join table).

Update

When I insert a place into the Places table, the GeoPoint is set like so:

SqlGeography.Point(sentPlace.Lat.Value, sentPlace.Lng.Value, 4326);

Body:
It look to me like you have your long/lats the wrong way round.

As for selecting DISTINCT geographies, you can perform the DISTINCT operation over the WKT (Well Known Text) in a nested query, see below:

SELECT
GEOGRAPHY::STGeomFromText(WKT, [PROJECTION]) AS GEOG
FROM
(
    SELECT DISTINCT
    GEOG.STAsText() AS WKT
    FROM
    [TABLE_NAME]
) a

Your query would look something like this:

SELECT
    a.*
,   GEOGRAPHY::STGeomFromText(WKT, 4326) AS GEOG
FROM
(
    SELECT DISTINCT
        Places.[COL1]
    ,   Places.[COL2]
    ,   Places.[COL3]
    ,   Places.[COL4]
    ...
    ...
    ,   Places.GeoPoint.STAsText() AS WKT
    FROM
    Places
    INNER JOIN
    PlaceCats
    ON
    Places.PlaceId = PlaceCats.PlaceId
    WHERE PlaceCats.CatId IN (2,3,4,5)
    AND
    Places.GeoPoint.STDistance(GEOGRAPHY::Point(35.75094975999387, 139.39780220389366, 4326)) < ((25 * 1000))
    ORDER BY Places.Name ASC
)a

One further tip, assuming you have a spatial index on your table, it speeds spatial queries up no end by using an index hit:

SELECT *
FROM
[TABLE_NAME] WITH(INDEX([INDEX_NAME]))
WHERE
GEOG.STIntersects.(GEOGRAPHY::Point([Longitude], [Latitude], 4326)) = 1


问:
Measure Page Load Speed with Selenium upon Python script on real device
I am trying to measure web page load speed with using Selenium and Python scripting.If the following driver is firefox or chrome in local (ubuntu 16.04) then seems working like a charm but if I use webdriver.Remote then performance responses are not working .

```<code>from selenium import webdriver
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['deviceName'] = 't03g'
desired_caps['appPackage'] = 'com.android.chrome'
desired_caps['appActivity'] = 'com.google.android.apps.chrome.Main'
driver = webdriver.Remote('http://192.168.1.40:4723/wd/hub', desired_caps)
driver.get('https://www.bbc.com/')

responseStart = driver.execute_script("return window.performance.timing.responseStart")
domComplete = driver.execute_script("return window.performance.timing.domComplete")
frontendPerformance_calc = float(domComplete - responseStart) / 1000

print(frontendPerformance_calc)

driver.quit()

</code>```

And the output of run is like :

```<code>Traceback (most recent call last):
  File "rasha.py", line 10, in <module>
    responseStart = driver.execute_script("return window.performance.timing.responseStart")
  File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 636, in execute_script
    'args': converted_args})['value']
  File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Method is not implemented
</code>```

Something is different I guess if we use real device but couldn't find it; Could you please help on that,

Thanks,

答:
I know this is an old question but I found an article that has ''Navigation Start'' before ''response start'' and ''dom Complete''
https://www.lambdatest.com/blog/how-to-measure-page-load-times-with-selenium/

On windows chrome it works like this for me:

```<code>options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options)
driver.get('https://www.google.com')
driver.maximize_window()

#! Use Navigation Timing  API to calculate the timings that matter the most
navigationStart = driver.execute_script("return window.performance.timing.navigationStart")
responseStart = driver.execute_script("return window.performance.timing.responseStart")
domComplete = driver.execute_script("return window.performance.timing.domComplete")

#! Calculate the performance
backendPerformance_calc = responseStart - navigationStart
frontendPerformance_calc = domComplete - responseStart

print("Back End: %s" % backendPerformance_calc)
print("Front End: %s" % frontendPerformance_calc)
</code>```

Body:
I am trying to measure web page load speed with using Selenium and Python scripting.If the following driver is firefox or chrome in local (ubuntu 16.04) then seems working like a charm but if I use webdriver.Remote then performance responses are not working .

from selenium import webdriver
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['deviceName'] = 't03g'
desired_caps['appPackage'] = 'com.android.chrome'
desired_caps['appActivity'] = 'com.google.android.apps.chrome.Main'
driver = webdriver.Remote('http://192.168.1.40:4723/wd/hub', desired_caps)
driver.get('https://www.bbc.com/')

responseStart = driver.execute_script("return window.performance.timing.responseStart")
domComplete = driver.execute_script("return window.performance.timing.domComplete")
frontendPerformance_calc = float(domComplete - responseStart) / 1000

print(frontendPerformance_calc)

driver.quit()

And the output of run is like :

Traceback (most recent call last):
  File "rasha.py", line 10, in <module>
    responseStart = driver.execute_script("return window.performance.timing.responseStart")
  File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 636, in execute_script
    'args': converted_args})['value']
  File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Method is not implemented

Something is different I guess if we use real device but couldn't find it; Could you please help on that,

Thanks,

Body:
I know this is an old question but I found an article that has ''Navigation Start'' before ''response start'' and ''dom Complete''
https://www.lambdatest.com/blog/how-to-measure-page-load-times-with-selenium/

On windows chrome it works like this for me:

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options)
driver.get('https://www.google.com')
driver.maximize_window()

#! Use Navigation Timing  API to calculate the timings that matter the most
navigationStart = driver.execute_script("return window.performance.timing.navigationStart")
responseStart = driver.execute_script("return window.performance.timing.responseStart")
domComplete = driver.execute_script("return window.performance.timing.domComplete")

#! Calculate the performance
backendPerformance_calc = responseStart - navigationStart
frontendPerformance_calc = domComplete - responseStart

print("Back End: %s" % backendPerformance_calc)
print("Front End: %s" % frontendPerformance_calc)


问:
Permission key denied in Azure
I created a virtual machine on Azure. It was working fine a couple of days ago (I was able to connect to it using SSL using command prompt), after that I reserved the IP public address and shutdown the machine and . Now I am trying to connect to it via SSL using same way and it is throwing permission denied error. How to rectify this ?

ssh -i user_key.pem username@xx.xxx.xx.xx

Load key "user_key.pem": Permission denied

username@xx.xxx.xx.xx: Permission denied (publickey).

答:
The problem was that I removed all permissions (except read by administrator) from my key.pem file. This I did because previously it was showing that the permissions are too open.

Opening the command prompt as administrator mode worked.

Title: Permission key denied in Azure


问:
Format the text after 4 characters (ABCD-EFGH-IJKL) but allow editing
I am trying to format and allow edit formated string in input with jquery, but I cannot achieve editing formated string correctly. Actually when user make mistake when typing code into input and want to correct it, it jump user to the end of the chain, because it forced formate it when user delete a char. How can i edit it, to let user correct his mistake but still format the chain?

What user type: 8F489T4R8T5O7S8E

What user see:  8F48-9T4R-8T5O-7S8E

But when user want to correct O to 0, it make result like this 8F48-9T4R-8T57-S8E0, because it will forced reformat the string immediately and put the 0 to the end of the chain.

    $("input[name=login-access-token]").keyup(function(event){
        var input = $(this).val();
        input = input.replace(/[\W\s\._\-]+/g, '');
        var split = 4;
        var chunk = [];

        for (var i = 0, len = input.length; i < len; i += split) {
            split = 4;
            chunk.push( input.substr( i, split ) );
        }
        $(this).val(function() {
            var out = chunk.join("-").toUpperCase();

            if(out.length == 4 && event.keyCode != 8){
                    out += "-";
            }

            if(out.length == 9 && event.keyCode != 8 ){
                    out += "-";
            }

            return out;
        });

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input type="text" name="login-access-token" placeholder="Code" /></code>```

答:
I think this is a good use case for the plugin jquery-inputmask.

Take a look at the documentation, there are plenty of options.

If you combine it with the CSS property text-transform: uppercase, you get most of your desired behavior in a one-liner javascript (plus workable copy/paste and disabling non-alpha characters).

$("input[name=login-access-token]").inputmask()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {
  font-family: monospace;
  text-transform: uppercase
}</code>```

<input type="text" name="login-access-token" placeholder="Code" data-inputmask="'mask': '****-****-****-****'"/>```

Body:
I am trying to format and allow edit formated string in input with jquery, but I cannot achieve editing formated string correctly. Actually when user make mistake when typing code into input and want to correct it, it jump user to the end of the chain, because it forced formate it when user delete a char. How can i edit it, to let user correct his mistake but still format the chain?

What user type: 8F489T4R8T5O7S8E

What user see:  8F48-9T4R-8T5O-7S8E

But when user want to correct O to 0, it make result like this 8F48-9T4R-8T57-S8E0, because it will forced reformat the string immediately and put the 0 to the end of the chain.

    $("input[name=login-access-token]").keyup(function(event){
        var input = $(this).val();
        input = input.replace(/[\W\s\._\-]+/g, '');
        var split = 4;
        var chunk = [];

        for (var i = 0, len = input.length; i < len; i += split) {
            split = 4;
            chunk.push( input.substr( i, split ) );
        }
        $(this).val(function() {
            var out = chunk.join("-").toUpperCase();

            if(out.length == 4 && event.keyCode != 8){
                    out += "-";
            }

            if(out.length == 9 && event.keyCode != 8 ){
                    out += "-";
            }

            return out;
        });

    });

<input type="text" name="login-access-token" placeholder="Code" />

Body:
I think this is a good use case for the plugin jquery-inputmask.

Take a look at the documentation, there are plenty of options.

If you combine it with the CSS property text-transform: uppercase, you get most of your desired behavior in a one-liner javascript (plus workable copy/paste and disabling non-alpha characters).

$("input[name=login-access-token]").inputmask()

input {
  font-family: monospace;
  text-transform: uppercase
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/jquery.inputmask.bundle.js"></script>

<input type="text" name="login-access-token" placeholder="Code" data-inputmask="'mask': '****-****-****-****'"/>


问:
C# MongoDB - How to select nested properties only
This is what my classes look like:

public class TestA : MongoDocument
{
    public string ProjectID { get; set; }
    public TestB Content { get; set; }

}

public class TestB
{
    public string Id { get; set; }

    public List<TestC> CustInfo { get; set; }
}

public class TestC
{
    public string Id { get; set; }

    public CustomerComment CustomerComment { get; set; }
}

public class CustomerComment
{
    public string Id { get; set; }
    public string notes { get; set; }
}
```
<p>I would like to return only the CustomerComment based on <code>TestA.ProjectID</code> && <code>TestC.Id</code></p>
<pre class="lang-cs prettyprint-override"><code>var projection = Builders<TestA>.Projection
                   .Include(x => x.Content.CustInfo);

var options = new FindOptions<TestA>
{
    Projection = projection
};

var find = await Collection.FindAsync(p => p.ProjectID == "555" &&
                    p.Content.CustInfo.Any(l => l.Id == "123"), options).ConfigureAwait(false);
var result = await find.ToListAsync().ConfigureAwait(false);
</code>```

This works but it will return everything. In this case, I would only want to return CustomerComments.

So for me to only retrieve the customerComments, I do another query based on the results from mongo. The code below gives me the correct data but I would rather do the filtering through the database.

var test = result.SelectMany(x => x.Content.CustInfo.Where(l => l.Id == "123").Select(y => y.CustomerComment)).ToList();
```

答:
I think Aggregation Query meets your requirements for querying the data in the database and returning desired output.

$match - Filtering data.

$unwind - Deconstruct array fields to multiple documents.

$match - Filtering data for Content.CustInfo.

$replaceWith - Replace the current document with the new document for output.

```<code>db.collection.aggregate([
  {
    $match: {
      "ProjectID": "555",
      "Content.CustInfo.Id": "123"
    }
  },
  {
    $unwind: "$Content.CustInfo"
  },
  {
    $match: {
      "Content.CustInfo.Id": {
        $eq: "123"
      }
    }
  },
  {
    "$replaceWith": "$Content.CustInfo.CustomerComment"
  }
])
</code>```

Sample Mongo Playground

Solution 1: With AggregateFluent

Pre-requisite: Create unwind classes.

public class UnwindTestA
{
    public ObjectId _id { get; set; }

    public string ProjectID { get; set; }

    public UnwindTestB Content { get; set; }
}

public class UnwindTestB
{
    public string Id { get; set; }

    public TestC CustInfo { get; set; }
}
```
<pre class="lang-cs prettyprint-override"><code>var result = await Collection.Aggregate()
    .Match(
        p => p.ProjectID == "555"
        && p.Content.CustInfo.Any(l => l.Id == "123")
    )
    .Unwind<TestA, UnwindTestA>(x => x.Content.CustInfo)
    .Match<UnwindTestA>(x => x.Content.CustInfo.Id == "123")
    .ReplaceWith<CustomerComment>("$Content.CustInfo.CustomerComment")
    .ToListAsync();
</code>```

Solution 2: With BsonDocument

Sometimes, writing a query with AggregateFluent is quite complex. You can use the MongoDB query which is converted to BsonDocument.

BsonDocument[] aggregate = new BsonDocument[]
{
    new BsonDocument("$match",
        new BsonDocument
            {
                { "ProjectID", "555" },
                { "Content.CustInfo.Id", "123" }
            }),
    new BsonDocument("$unwind", "$Content.CustInfo"),
    new BsonDocument("$match",
        new BsonDocument("Content.CustInfo.Id",
            new BsonDocument("$eq", "123"))),
    new BsonDocument("$replaceWith", "$Content.CustInfo.CustomerComment")
};

var result = await Collection.Aggregate<CustomerComment>(aggregate)
    .ToListAsync();
```

Output

Body:
This is what my classes look like:

public class TestA : MongoDocument
{
    public string ProjectID { get; set; }
    public TestB Content { get; set; }

}

public class TestB
{
    public string Id { get; set; }

    public List<TestC> CustInfo { get; set; }
}

public class TestC
{
    public string Id { get; set; }

    public CustomerComment CustomerComment { get; set; }
}

public class CustomerComment
{
    public string Id { get; set; }
    public string notes { get; set; }
}

I would like to return only the CustomerComment based on TestA.ProjectID && TestC.Id

var projection = Builders<TestA>.Projection
                   .Include(x => x.Content.CustInfo);

var options = new FindOptions<TestA>
{
    Projection = projection
};

var find = await Collection.FindAsync(p => p.ProjectID == "555" &&
                    p.Content.CustInfo.Any(l => l.Id == "123"), options).ConfigureAwait(false);
var result = await find.ToListAsync().ConfigureAwait(false);

This works but it will return everything. In this case, I would only want to return CustomerComments.

So for me to only retrieve the customerComments, I do another query based on the results from mongo. The code below gives me the correct data but I would rather do the filtering through the database.

var test = result.SelectMany(x => x.Content.CustInfo.Where(l => l.Id == "123").Select(y => y.CustomerComment)).ToList();

Body:
I think Aggregation Query meets your requirements for querying the data in the database and returning desired output.

$match - Filtering data.

$unwind - Deconstruct array fields to multiple documents.

$match - Filtering data for Content.CustInfo.

$replaceWith - Replace the current document with the new document for output.

db.collection.aggregate([
  {
    $match: {
      "ProjectID": "555",
      "Content.CustInfo.Id": "123"
    }
  },
  {
    $unwind: "$Content.CustInfo"
  },
  {
    $match: {
      "Content.CustInfo.Id": {
        $eq: "123"
      }
    }
  },
  {
    "$replaceWith": "$Content.CustInfo.CustomerComment"
  }
])

Sample Mongo Playground

Solution 1: With AggregateFluent

Pre-requisite: Create unwind classes.

public class UnwindTestA
{
    public ObjectId _id { get; set; }

    public string ProjectID { get; set; }

    public UnwindTestB Content { get; set; }
}

public class UnwindTestB
{
    public string Id { get; set; }

    public TestC CustInfo { get; set; }
}

var result = await Collection.Aggregate()
    .Match(
        p => p.ProjectID == "555"
        && p.Content.CustInfo.Any(l => l.Id == "123")
    )
    .Unwind<TestA, UnwindTestA>(x => x.Content.CustInfo)
    .Match<UnwindTestA>(x => x.Content.CustInfo.Id == "123")
    .ReplaceWith<CustomerComment>("$Content.CustInfo.CustomerComment")
    .ToListAsync();

Solution 2: With BsonDocument

Sometimes, writing a query with AggregateFluent is quite complex. You can use the MongoDB query which is converted to BsonDocument.

BsonDocument[] aggregate = new BsonDocument[]
{
    new BsonDocument("$match",
        new BsonDocument
            {
                { "ProjectID", "555" },
                { "Content.CustInfo.Id", "123" }
            }),
    new BsonDocument("$unwind", "$Content.CustInfo"),
    new BsonDocument("$match",
        new BsonDocument("Content.CustInfo.Id",
            new BsonDocument("$eq", "123"))),
    new BsonDocument("$replaceWith", "$Content.CustInfo.CustomerComment")
};

var result = await Collection.Aggregate<CustomerComment>(aggregate)
    .ToListAsync();

Output


问:
Accessing all user's mailbox via Office 365 REST API
I am trying out Office 365 Rest APIs.

I have registered application with Azure AD.

It has following permission set:  Exchange: Access All User's Mailbox, Full Control on User's Calendar, Full Control on User's Contacts, Full Control on User's Mailbox

I have generated access token with admin grant which has global admin privileges.

Sent following request 'https://outlook.office365.com/api/users/me/messages' which resulted in correct results giving me all messages in current admin's mailbox

Sent following request 'https://outlook.office365.com/api/users/{another user's email}/messages'. This resulted in following error

"u'error': {u'message': u'Access is denied. Check credentials and try again.', u'code': u'ErrorAccessDenied'}}"

Please let me know if above steps are wrong ?

If they are wrong, is there a way to fetch emails from another user's mailbox as I have admin credentials ?

Thanks.

答:
If someone is looking for the solution, it was a problem of service principal.
We were pointing to the wrong Service Principal and that was the cause of the issues with permissions.</p>


问:
How to find model records having some or no associated model records in rails?
I am creating an Employee Management System app using Rails 7. Here I have one Employee model, one Document model having a list of all documents and these two are associated through the EmployeeDocuments model which has Employee ID and Document ID. Now I want to use an action mailer to send a list of employees with documents they have not submitted. The problem is I cannot get the Employee list with some or no documents submitted in a single query.
I can get Employees with no submitted documents like this:

```<code>Employee.includes(:documents).where(documents: {id: nil})
</code>```

and Employees with some or all documents submitted by:

```<code>Employee.includes(:documents).where.not(documents: {id: nil})
</code>```

I want the list so that I can iterate through their missing documents by:

```<code>Document.where.not(id: employee.documents.pluck(:id))
</code>```

and send the list.
Currently, my mailer looks like this:

```<code>class DocsNotifierMailer < ApplicationMailer
  default from: 'user@email.com'

  def notification_email
    @employees = Employee.all
    mail(to: 'recipient@email.com',
      subject: 'Reminder for missing documents')
  end
end
</code>```

So I can get the list of all employees in my HTML template and there I am using an If statement like this:

```<code><% if employee.documents.length < Document.all.count %>
</code>```

to filter out the employees with all documents.
But I want to filter them in the mailer itself.
Since I am a beginner, can not find a way out of this. Please help.

答:
Rails 7 has this built in

```<code>Employee.where.associated(:documents)
</code>```

Read more about it: https://blog.saeloun.com/2021/02/15/rails-7-adds-query-method-associated-to-check-association-presence.html

Body:
I am creating an Employee Management System app using Rails 7. Here I have one Employee model, one Document model having a list of all documents and these two are associated through the EmployeeDocuments model which has Employee ID and Document ID. Now I want to use an action mailer to send a list of employees with documents they have not submitted. The problem is I cannot get the Employee list with some or no documents submitted in a single query.
I can get Employees with no submitted documents like this:

Employee.includes(:documents).where(documents: {id: nil})

and Employees with some or all documents submitted by:

Employee.includes(:documents).where.not(documents: {id: nil})

I want the list so that I can iterate through their missing documents by:

Document.where.not(id: employee.documents.pluck(:id))

and send the list.
Currently, my mailer looks like this:

class DocsNotifierMailer < ApplicationMailer
  default from: 'user@email.com'

  def notification_email
    @employees = Employee.all
    mail(to: 'recipient@email.com',
      subject: 'Reminder for missing documents')
  end
end

So I can get the list of all employees in my HTML template and there I am using an If statement like this:

<% if employee.documents.length < Document.all.count %>

to filter out the employees with all documents.
But I want to filter them in the mailer itself.
Since I am a beginner, can not find a way out of this. Please help.

Body:
Rails 7 has this built in

Employee.where.associated(:documents)

Read more about it: https://blog.saeloun.com/2021/02/15/rails-7-adds-query-method-associated-to-check-association-presence.html


问:
Can I store data on an Android device to persist between installs?
I want to store a small amount of data in a way where it persists between application installs. I obviously can't use SharedPreferences as they are removes upon uninstallation. Is there any way to store data so it survives a reinstall of the app?

The data I want to store is a unique ID, to allow blocking of users of the app if they misbehave. If I cannot store an ID, can I access the Google account(s) email addresses to use them as an indicator?

This blog post makes it clear none of the IDs the OS produces are any good, especially when considering tablets
Android: Identifying app installations

答: If the app is removed, the data is removed.  You could put something on the SD card, but there's no reason to believe it would stay there. You might be able to work something through the application licensing mechanism.  Details here</p>


问:
Detect when database is changed by an external program in C#
Is it possible for my software to be notified when the third-party application makes changes to the SQLITE database that we are both connected to?</p>

答:
You can periodically check the PRAGMA data_version output and compare it against the previous value returned by the pragma to see if another connection to the database has modified it in between the checks.

Quoting the documentation:

The "PRAGMA data_version" command provides an indication that the database file has been modified. Interactive programs that hold database content in memory or that display database content on-screen can use the PRAGMA data_version command to determine if they need to flush and reload their memory or update the screen display.

The integer values returned by two invocations of "PRAGMA data_version" from the same connection will be different if changes were committed to the database by any other connection in the interim. The "PRAGMA data_version" value is unchanged for commits made on the same database connection. The behavior of "PRAGMA data_version" is the same for all database connections, including database connections in separate processes and shared cache database connections.

The "PRAGMA data_version" value is a local property of each database connection and so values returned by two concurrent invocations of "PRAGMA data_version" on separate database connections are often different even though the underlying database is identical. It is only meaningful to compare the "PRAGMA data_version" values returned by the same database connection at two different points in time.


问:
Extend NestJS Logger (old version) - where can i set LogLevels
I create a extended logger based like the answer of Ian:
Issue with using Azure Applications Insights sdk with NestJS logger

NestJS old version:

```<code>export class MyLogger extends Logger {
</code>```

Normally you can set the log-level for the nestjs logger:

```<code>const app = await NestFactory.create(AppModule, {
  logger: ['error', 'warn'],
});
</code>```

But how can i set the LogLevels if i extend the Logger.

```<code>const app = await NestFactory.create(AppModule);
const logger = await app.resolve(MyLogger);
logger.setClient(appInsights.defaultClient);
app.useLogger(logger);
</code>```

答:
If your application uses a custom logger class that extends the built-in  Logger, you should update it to extend the  ConsoleLogger  now.

Before:

export class MyLogger extends Logger {}
```
<p><em><strong>Now:</strong></em></p>
<pre class="lang-js prettyprint-override"><code>export class MyLogger extends ConsoleLogger {}
</code>```

extend the built-in ConsoleLogger class

export class MyLogger extends ConsoleLogger
```
<pre class="lang-js prettyprint-override"><code>const app = await NestFactory.create(ApplicationModule, {
  bufferLogs: true,
});
app.useLogger(app.get(MyLogger));
await app.listen(3000);
</code>```

extend the logger built into NestJS and use the LogsService

Please refer Extend built-in logger , this for more information

Body:
I create a extended logger based like the answer of Ian:
Issue with using Azure Applications Insights sdk with NestJS logger

NestJS old version:

export class MyLogger extends Logger {

Normally you can set the log-level for the nestjs logger:

const app = await NestFactory.create(AppModule, {
  logger: ['error', 'warn'],
});

But how can i set the LogLevels if i extend the Logger.

const app = await NestFactory.create(AppModule);
const logger = await app.resolve(MyLogger);
logger.setClient(appInsights.defaultClient);
app.useLogger(logger);

Body:
If your application uses a custom logger class that extends the built-in  Logger, you should update it to extend the  ConsoleLogger  now.

Before:

export class MyLogger extends Logger {}

Now:

export class MyLogger extends ConsoleLogger {}

extend the built-in ConsoleLogger class

export class MyLogger extends ConsoleLogger

const app = await NestFactory.create(ApplicationModule, {
  bufferLogs: true,
});
app.useLogger(app.get(MyLogger));
await app.listen(3000);

extend the logger built into NestJS and use the LogsService

Please refer Extend built-in logger , this for more information


问:
How can I create a wrapper for the RecyclerView Adapter that will accept any Adapter that implements RecyclerView.Adapter<RecyclerView.ViewHolder>
I know the title is a bit weird, sorry. This is a weird one that I'm not even sure I can explain it correctly, here is my attempt:

Basically I want to implement a wrapper for any adapters that extend RecyclerView.Adapter<RecyclerView.ViewHolder> , the wrapper eventually will be able to insert rows if needed and it will modify things like getItemCount() as necessary, but I'm nowhere near that part yet.

This is my class definition:

```<code>class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

I pass to it the original adapter which I want to wrap.

If I have the class definition like that, and then I try to create an instance of MyRecyclerAdapterWrapper like this:

```<code>val wrapper = MyRecyclerAdapterWrapper(activity, myOriginalAdapter)
</code>```

Where myOriginalAdapter is an instance of:

```<code>class MyOriginalAdapter() : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {
</code>```

I then get an error saying that it is expecting RecyclerView.Adapter<RecyclerView.ViewHolder>  but instead got MyOriginalAdapter.

So then I tried the out keyword on the class definition like this:

```<code>class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

And that allows my constructor call MyRecyclerAdapterWrapper(activity, myOriginalAdapter) to stop complaining, however then my MyRecyclerAdapterWrapper class fails at implementing some of the RecyclerView.Adapter<RecyclerView.ViewHolder> overrides because originalAdapter expects Nothing instead of RecyclerView.ViewHolder.

For example inside MyRecyclerAdapterWrapper I have this piece of code:

```<code>override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder,position)
}
</code>```

The error here is Type mismatch Required: Nothing Found: RecyclerView.ViewHolder.

So what is the correct way to handle this?

Edit: just wanted to be clear that other adapters will also use this wrapper, so the wrapper must be generic.

Edit: I should have mentioned this, there is a similar wrapper that works fine that I was using but it is in Java, the class definition on that one was:

```<code>public final class MyRecyclerAdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
     public MyRecyclerAdapterWrapper(@NonNull Activity activity,
        @NonNull RecyclerView.Adapter originalAdapter){
</code>```

Edit: Based on the answer from @muetzenflo I was able to get most of it to work but still have a problem with some methods.

I now have this:

```<code>class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

And

```<code> class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {

        }
</code>```

This works:

```<code>val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
</code>```

But this doesn't:

```<code>genericMethod(myRecyclerAdapterWrapper)

private fun genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<RecyclerView.ViewHolder>) {

    }
</code>```

The error is:

```<code>Type mismatch: inferred type is MainActivity.MyRecyclerAdapterWrapper<MainActivity.MyCustomAdapter.MyViewHolder> but MainActivity.MyRecyclerAdapterWrapper<RecyclerView.ViewHolder> was expected
</code>```

Edit: Think I figured out how to make the generic methods:

```<code>private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {

    }
</code>```

So in the end this is how my class ended up and it all compiles and runs:

```<code>class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
        genericMethod(myRecyclerAdapterWrapper)
    }
    private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {
    }
    class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return originalAdapter.onCreateViewHolder(parent,viewType)
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            originalAdapter.onBindViewHolder(holder as T,position)
        }
        override fun getItemCount(): Int {
            return originalAdapter.itemCount
        }
    }
    class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {
        }
        override fun getItemCount(): Int {
            TODO("Not yet implemented")
        }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            TODO("Not yet implemented")
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            TODO("Not yet implemented")
        }
    }
}
</code>```

答:
You can use below wrapper class of recycler view adapter,</p>
```<code>public class WrapperRecyclerAdapter extends RecyclerView.Adapter {

    private final RecyclerView.Adapter mAdapter;

    public WrapperRecyclerAdapter(RecyclerView.Adapter adapter) {
        super.setHasStableIds(adapter.hasStableIds());
        mAdapter = adapter;
        mAdapter.registerAdapterDataObserver(new ForwardingDataSetObserver());
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return mAdapter.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        mAdapter.onBindViewHolder(holder, position);
    }

    @Override
    public int getItemViewType(int position) {
        return mAdapter.getItemViewType(position);
    }

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        mAdapter.onViewRecycled(holder);
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        mAdapter.onViewAttachedToWindow(holder);
    }

    @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        mAdapter.onViewDetachedFromWindow(holder);
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        mAdapter.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        mAdapter.onDetachedFromRecyclerView(recyclerView);
    }

    @Override
    public long getItemId(int position) {
        return mAdapter.getItemId(position);
    }

    @Override
    public int getItemCount() {
        return mAdapter.getItemCount();
    }

    private class ForwardingDataSetObserver extends RecyclerView.AdapterDataObserver {

        @Override public void onChanged() {
            notifyDataSetChanged();
        }

        @Override public void onItemRangeChanged(int positionStart, int itemCount) {
            notifyItemRangeChanged(positionStart, itemCount);
        }

        @Override public void onItemRangeInserted(int positionStart, int itemCount) {
            notifyItemRangeInserted(positionStart, itemCount);
        }

        @Override public void onItemRangeRemoved(int positionStart, int itemCount) {
            notifyItemRangeRemoved(positionStart, itemCount);
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
           notifyDataSetChanged(); //TODO
        }
    }

}
</code>```

Body:
I know the title is a bit weird, sorry. This is a weird one that I'm not even sure I can explain it correctly, here is my attempt:

Basically I want to implement a wrapper for any adapters that extend RecyclerView.Adapter<RecyclerView.ViewHolder> , the wrapper eventually will be able to insert rows if needed and it will modify things like getItemCount() as necessary, but I'm nowhere near that part yet.

This is my class definition:

class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

I pass to it the original adapter which I want to wrap.

If I have the class definition like that, and then I try to create an instance of MyRecyclerAdapterWrapper like this:

val wrapper = MyRecyclerAdapterWrapper(activity, myOriginalAdapter)

Where myOriginalAdapter is an instance of:

class MyOriginalAdapter() : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {

I then get an error saying that it is expecting RecyclerView.Adapter<RecyclerView.ViewHolder>  but instead got MyOriginalAdapter.

So then I tried the out keyword on the class definition like this:

class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

And that allows my constructor call MyRecyclerAdapterWrapper(activity, myOriginalAdapter) to stop complaining, however then my MyRecyclerAdapterWrapper class fails at implementing some of the RecyclerView.Adapter<RecyclerView.ViewHolder> overrides because originalAdapter expects Nothing instead of RecyclerView.ViewHolder.

For example inside MyRecyclerAdapterWrapper I have this piece of code:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder,position)
}

The error here is Type mismatch Required: Nothing Found: RecyclerView.ViewHolder.

So what is the correct way to handle this?

Edit: just wanted to be clear that other adapters will also use this wrapper, so the wrapper must be generic.

Edit: I should have mentioned this, there is a similar wrapper that works fine that I was using but it is in Java, the class definition on that one was:

public final class MyRecyclerAdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
     public MyRecyclerAdapterWrapper(@NonNull Activity activity,
        @NonNull RecyclerView.Adapter originalAdapter){

Edit: Based on the answer from @muetzenflo I was able to get most of it to work but still have a problem with some methods.

I now have this:

class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

And

 class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {

        }

This works:

val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())

But this doesn't:

genericMethod(myRecyclerAdapterWrapper)

private fun genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<RecyclerView.ViewHolder>) {

    }

The error is:

Type mismatch: inferred type is MainActivity.MyRecyclerAdapterWrapper<MainActivity.MyCustomAdapter.MyViewHolder> but MainActivity.MyRecyclerAdapterWrapper<RecyclerView.ViewHolder> was expected

Edit: Think I figured out how to make the generic methods:

private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {

    }

So in the end this is how my class ended up and it all compiles and runs:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
        genericMethod(myRecyclerAdapterWrapper)
    }
    private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {
    }
    class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return originalAdapter.onCreateViewHolder(parent,viewType)
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            originalAdapter.onBindViewHolder(holder as T,position)
        }
        override fun getItemCount(): Int {
            return originalAdapter.itemCount
        }
    }
    class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {
        }
        override fun getItemCount(): Int {
            TODO("Not yet implemented")
        }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            TODO("Not yet implemented")
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            TODO("Not yet implemented")
        }
    }
}

Body:
You can use below wrapper class of recycler view adapter,

public class WrapperRecyclerAdapter extends RecyclerView.Adapter {

    private final RecyclerView.Adapter mAdapter;

    public WrapperRecyclerAdapter(RecyclerView.Adapter adapter) {
        super.setHasStableIds(adapter.hasStableIds());
        mAdapter = adapter;
        mAdapter.registerAdapterDataObserver(new ForwardingDataSetObserver());
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return mAdapter.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        mAdapter.onBindViewHolder(holder, position);
    }

    @Override
    public int getItemViewType(int position) {
        return mAdapter.getItemViewType(position);
    }

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        mAdapter.onViewRecycled(holder);
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        mAdapter.onViewAttachedToWindow(holder);
    }

    @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        mAdapter.onViewDetachedFromWindow(holder);
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        mAdapter.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        mAdapter.onDetachedFromRecyclerView(recyclerView);
    }

    @Override
    public long getItemId(int position) {
        return mAdapter.getItemId(position);
    }

    @Override
    public int getItemCount() {
        return mAdapter.getItemCount();
    }

    private class ForwardingDataSetObserver extends RecyclerView.AdapterDataObserver {

        @Override public void onChanged() {
            notifyDataSetChanged();
        }

        @Override public void onItemRangeChanged(int positionStart, int itemCount) {
            notifyItemRangeChanged(positionStart, itemCount);
        }

        @Override public void onItemRangeInserted(int positionStart, int itemCount) {
            notifyItemRangeInserted(positionStart, itemCount);
        }

        @Override public void onItemRangeRemoved(int positionStart, int itemCount) {
            notifyItemRangeRemoved(positionStart, itemCount);
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
           notifyDataSetChanged(); //TODO
        }
    }

}


问:
Server won't run this part of Python code
We have a server for python scripts, where there is quite a lot of them running already, but for some reason one code won't run and it is because of this part:

```<code>def getData(ico):
    url = "https://www.mojedatovaschranka.cz/sds/ws/call"

    headers = {'Content-Type':'application/xml'}

    data = """
            <GetInfoRequest xmlns="http://seznam.gov.cz/ovm/ws/v1">
                <Ico>{}</Ico>
            </GetInfoRequest>
    """.format(ico)

    response = requests.post(url, headers=headers, data=data)

    #print(response.status_code)
    #print(response.text)

    data = xmltodict.parse(response.content)
    #print(data)
    return data
</code>```

for
It is offical api for some data off all legal subjects, not really important.
We cant figure out, what is wrong with this segment.

There are other codes with API calls, so there is not a problem, thant server can't send them.

Also we have newest python 7.3.1 installed.

All libs are installed and used by other scripts.

This is the only message we got: Task Scheduler successfully completed task "\Python\API_Databox" , instance "{0b448401-dedd-4cbc-9200-8addd409dfcf}" , action "C:\Windows\SYSTEM32\cmd.exe" with return code 2147942401.

Also it runs normally on my computers.

So my question is, does somebody know what might fix the issue or why server cant"t run this specific code? Other similar codes are running just fine.

答:
Try testing from the context of the running task, rather than the logged in user. You could write the output of what your getData function returns, or the resulting exception, to a text file like this:</p>
```<code>try:
    x = getData("valid input data for website")
    with open('py_log.txt', 'w') as f:
        f.write("Function ran without exception, it returned:\n")
        f.write(str(x))
except Exception as e:
    with open('py_log.txt', 'w') as f:
        if 'x' in globals():
            f.write("Function threw an exception, it returned\n")
            f.write(str(x))
        f.write("Reported exception\n")
        f.write(str(e))
</code>```

Body:
We have a server for python scripts, where there is quite a lot of them running already, but for some reason one code won't run and it is because of this part:

def getData(ico):
    url = "https://www.mojedatovaschranka.cz/sds/ws/call"

    headers = {'Content-Type':'application/xml'}

    data = """
            <GetInfoRequest xmlns="http://seznam.gov.cz/ovm/ws/v1">
                <Ico>{}</Ico>
            </GetInfoRequest>
    """.format(ico)

    response = requests.post(url, headers=headers, data=data)

    #print(response.status_code)
    #print(response.text)

    data = xmltodict.parse(response.content)
    #print(data)
    return data

for
It is offical api for some data off all legal subjects, not really important.
We cant figure out, what is wrong with this segment.

There are other codes with API calls, so there is not a problem, thant server can't send them.

Also we have newest python 7.3.1 installed.

All libs are installed and used by other scripts.

This is the only message we got: Task Scheduler successfully completed task "\Python\API_Databox" , instance "{0b448401-dedd-4cbc-9200-8addd409dfcf}" , action "C:\Windows\SYSTEM32\cmd.exe" with return code 2147942401.

Also it runs normally on my computers.

So my question is, does somebody know what might fix the issue or why server cant"t run this specific code? Other similar codes are running just fine.

Body:
Try testing from the context of the running task, rather than the logged in user. You could write the output of what your getData function returns, or the resulting exception, to a text file like this:

try:
    x = getData("valid input data for website")
    with open('py_log.txt', 'w') as f:
        f.write("Function ran without exception, it returned:\n")
        f.write(str(x))
except Exception as e:
    with open('py_log.txt', 'w') as f:
        if 'x' in globals():
            f.write("Function threw an exception, it returned\n")
            f.write(str(x))
        f.write("Reported exception\n")
        f.write(str(e))