问:
Python socket error: (OSError: [WinError 10057])
I'm making a python code that every 7 seconds send a screenshot through a socket, I have a server and a client. when I run the server I get an error:

the client takes a screenshot every 7 seconds with pyautogui and saves it with a name containing the date and time using the datetime module

client code:

```<code>import socket
import pyautogui
import os
import datetime
from time import sleep

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("#hidden because of security reasons", 9999))

def send_img(img):
    current_datetime = datetime.datetime.now()
    current_datetime = current_datetime.strftime("%H:%M:%S")
    current_datetime = current_datetime.replace(":", ".")

    name = f"image_{current_datetime}.png"
    img.save(name)
    file = open(name, "rb")
    file_size = os.path.getsize(name)

    client.send(name.encode())
    client.send(f"{str(file_size)}".encode())

    data = file.read()
    client.sendall(data)
    client.send(b"<END>")

    file.close()

def screenshot():
    img = pyautogui.screenshot()
    send_img(img)

while True:
    screenshot()
    sleep(7)
</code>```

server code:

```<code>import tqdm
import socket
import threading
import datetime

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip_addr = str(socket.gethostbyname(socket.gethostname()))
server.bind((ip_addr, 9999))
server.listen()

def send():
    current_datetime = datetime.datetime.now()
    current_datetime = current_datetime.strftime("%H:%M:%S")
    print(f"[{current_datetime}] New screenshot taken: {file_name}")

    file = open(file_name, "wb")
    file_bytes = b""
    done = False

    progress = tqdm.tqdm(unit="B", unit_scale=True, unit_divisor=1000, total=int(file_size))

    while not done:
        data = server.recv(1024)
        if file_bytes[-5:] == b"<END>":
            done = True
        else:
            file_bytes += data
        progress.update(1024)
    file.write(file_bytes)

    file.close()

print("[STARTING] SERVER STARTED...")
while True:
    client, addr = server.accept()

    file_name = client.recv(1024).decode()
    print(file_name)
    file_size = client.recv(1024).decode()
    print(file_size)

    thread = threading.Thread(target=send)
    thread.start()
</code>```

if someone could fix this code it would be amazing, btw im using python 3.10 and pycharm IDE

I have tried to change the filename and other things but I keep getting the error.

Body:
I'm making a python code that every 7 seconds send a screenshot through a socket, I have a server and a client. when I run the server I get an error:

the client takes a screenshot every 7 seconds with pyautogui and saves it with a name containing the date and time using the datetime module

client code:

import socket
import pyautogui
import os
import datetime
from time import sleep

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("#hidden because of security reasons", 9999))

def send_img(img):
    current_datetime = datetime.datetime.now()
    current_datetime = current_datetime.strftime("%H:%M:%S")
    current_datetime = current_datetime.replace(":", ".")

    name = f"image_{current_datetime}.png"
    img.save(name)
    file = open(name, "rb")
    file_size = os.path.getsize(name)

    client.send(name.encode())
    client.send(f"{str(file_size)}".encode())

    data = file.read()
    client.sendall(data)
    client.send(b"<END>")

    file.close()

def screenshot():
    img = pyautogui.screenshot()
    send_img(img)

while True:
    screenshot()
    sleep(7)

server code:

import tqdm
import socket
import threading
import datetime

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip_addr = str(socket.gethostbyname(socket.gethostname()))
server.bind((ip_addr, 9999))
server.listen()

def send():
    current_datetime = datetime.datetime.now()
    current_datetime = current_datetime.strftime("%H:%M:%S")
    print(f"[{current_datetime}] New screenshot taken: {file_name}")

    file = open(file_name, "wb")
    file_bytes = b""
    done = False

    progress = tqdm.tqdm(unit="B", unit_scale=True, unit_divisor=1000, total=int(file_size))

    while not done:
        data = server.recv(1024)
        if file_bytes[-5:] == b"<END>":
            done = True
        else:
            file_bytes += data
        progress.update(1024)
    file.write(file_bytes)

    file.close()

print("[STARTING] SERVER STARTED...")
while True:
    client, addr = server.accept()

    file_name = client.recv(1024).decode()
    print(file_name)
    file_size = client.recv(1024).decode()
    print(file_size)

    thread = threading.Thread(target=send)
    thread.start()

if someone could fix this code it would be amazing, btw im using python 3.10 and pycharm IDE

I have tried to change the filename and other things but I keep getting the error.


来源: stackexchange

问:
Visual Studio 2017 - How to remove trailing white spaces
I am running Visual Basic 2017. I continue to have issues with trailing white spaces on my reports. Can someone walk me through how to remove them in the 2017 version. I can find answers for 2019 and above.

Thank you.

I have researched and can only find information on removing trailing white spaces for 2019 versions and newer. I need a step by step instruction for 2017.

ContentLicense: CC BY-SA 4.0


问:
matplotlib's ion() does not make any difference
To test the matplotlib's interactive mode, I used the following two code snippets:

Snippet 1: Has plt.ion() with no call to fig.canvas.draw():

```<code>import numpy as np
import matplotlib.pyplot as plt

x = np.array([])
y_1 = np.array([])
y_2 = np.array([])

plt.ion()

fig = plt.figure(figsize=(9,4))
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

fig.show()

for i in range(0, 100000):
    x = np.append(x, i)
    y_1 = np.append(y_1, i**2)
    y_2 = np.append(y_2, i**3)

    ax1.clear()
    ax2.clear()
    ax1.scatter(x, y_1)
    ax2.scatter(x, y_2)

    #fig.canvas.draw()
    plt.pause(0.02)
</code>```

Snippet 2: Has plt.ion() with call to fig.canvas.draw():

```<code>import numpy as np
import matplotlib.pyplot as plt

x = np.array([])
y_1 = np.array([])
y_2 = np.array([])

plt.ion()

fig = plt.figure(figsize=(9,4))
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

fig.show()

for i in range(0, 100000):
    x = np.append(x, i)
    y_1 = np.append(y_1, i**2)
    y_2 = np.append(y_2, i**3)

    ax1.clear()
    ax2.clear()
    ax1.scatter(x, y_1)
    ax2.scatter(x, y_2)

    fig.canvas.draw()
    plt.pause(0.02)
</code>```

I could not see any difference between the two plotted figures. Both the figures were updated/redrawn automatically.

Further, I set the interactive mode off using plt.ioff() with no call to fig.canvas.draw():

Snippet 3:

```<code>import numpy as np
import matplotlib.pyplot as plt

x = np.array([])
y_1 = np.array([])
y_2 = np.array([])

plt.ioff()

fig = plt.figure(figsize=(9,4))
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

fig.show()

for i in range(0, 100000):
    x = np.append(x, i)
    y_1 = np.append(y_1, i**2)
    y_2 = np.append(y_2, i**3)

    ax1.clear()
    ax2.clear()
    ax1.scatter(x, y_1)
    ax2.scatter(x, y_2)

    #fig.canvas.draw()
    plt.pause(0.02)
</code>```

Same behaviour was observed across all the 3 snippets.

According to what is mentioned on https://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg21139.html about ion():

PS: the documentation I was referring to reads: "The interactive property of
the pyplot interface controls whether a figure canvas is drawn on every
pyplot command. If interactive is False, then the figure state is updated on
every plot command, but will only be drawn on explicit calls to draw(). When
interactive is True, then every pyplot command triggers a draw."

the expected behaviour of Snippet 3 should be different than that of Snippet 1 & Snippet 2. For Snippet 3, the figure should not get updated/redrawn automatically.

Is my understanding correct or am I missing something?

Body:
To test the matplotlib's interactive mode, I used the following two code snippets:

Snippet 1: Has plt.ion() with no call to fig.canvas.draw():

import numpy as np
import matplotlib.pyplot as plt

x = np.array([])
y_1 = np.array([])
y_2 = np.array([])

plt.ion()

fig = plt.figure(figsize=(9,4))
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

fig.show()

for i in range(0, 100000):
    x = np.append(x, i)
    y_1 = np.append(y_1, i**2)
    y_2 = np.append(y_2, i**3)

    ax1.clear()
    ax2.clear()
    ax1.scatter(x, y_1)
    ax2.scatter(x, y_2)

    #fig.canvas.draw()
    plt.pause(0.02)

Snippet 2: Has plt.ion() with call to fig.canvas.draw():

import numpy as np
import matplotlib.pyplot as plt

x = np.array([])
y_1 = np.array([])
y_2 = np.array([])

plt.ion()

fig = plt.figure(figsize=(9,4))
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

fig.show()

for i in range(0, 100000):
    x = np.append(x, i)
    y_1 = np.append(y_1, i**2)
    y_2 = np.append(y_2, i**3)

    ax1.clear()
    ax2.clear()
    ax1.scatter(x, y_1)
    ax2.scatter(x, y_2)

    fig.canvas.draw()
    plt.pause(0.02)

I could not see any difference between the two plotted figures. Both the figures were updated/redrawn automatically.

Further, I set the interactive mode off using plt.ioff() with no call to fig.canvas.draw():

Snippet 3:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([])
y_1 = np.array([])
y_2 = np.array([])

plt.ioff()

fig = plt.figure(figsize=(9,4))
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

fig.show()

for i in range(0, 100000):
    x = np.append(x, i)
    y_1 = np.append(y_1, i**2)
    y_2 = np.append(y_2, i**3)

    ax1.clear()
    ax2.clear()
    ax1.scatter(x, y_1)
    ax2.scatter(x, y_2)

    #fig.canvas.draw()
    plt.pause(0.02)

Same behaviour was observed across all the 3 snippets.

According to what is mentioned on https://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg21139.html about ion():

PS: the documentation I was referring to reads: "The interactive property of
the pyplot interface controls whether a figure canvas is drawn on every
pyplot command. If interactive is False, then the figure state is updated on
every plot command, but will only be drawn on explicit calls to draw(). When
interactive is True, then every pyplot command triggers a draw."

the expected behaviour of Snippet 3 should be different than that of Snippet 1 & Snippet 2. For Snippet 3, the figure should not get updated/redrawn automatically.

Is my understanding correct or am I missing something?


问:
How are you doing CI with Unity and Git with 3rd party assets?
My goal is to be able to build Unity projects with 3rd party assets using GitHub Actions and GameCI. I am able to build and deploy Unity projects on Git, but I have the following problem.
I don't want to check in 3rd party assets, but I do want to build on Git.

Many of the licenses are not open source, and checking them into a repository seems problematic even when the repo is private.
Is there a way to download assets from a command line using a Unity license during the build process? Or is there a better way to manage Unity 3rd party assets in Git with CI?


问:
Is the VSProject4.Refresh() method only for VB and C# projects?
Is the VSProject4.Refresh() method in Visual Studio SDK only for VB and C# projects ?

...or is it supposed to work for ALL types of projects - including C and C++ projects ?

Below is a sample C# code that invokes this method:

    public static void RefreshAllProjects(EnvDTE.DTE dte)
    {
        EnvDTE.Projects prjs = dte.Solution.Projects; //Get all projects in solution.

        foreach (EnvDTE.Project prj in prjs)
        {
            VSLangProj150.VSProject4 prj4 = prj.Object as VSLangProj150.VSProject4;
            prj4.Refresh();
        }
    }
```


问:
i am trying to upload images with vue js cloudinary and node js but when i send the files to the backend i am getting an empty array of files
this is how i have set up my node js backend
///create new products
productRoute.post("/products", isAuthenticatedUser, upload.array('images'),   authorizeRoles('admin', "seller" , "superadmin"), async(req,res, next) => {
// console.log("this is the req.body===>",req)

```<code>req.body.user = req.user.id;
try {

const uploader = async(path) => await uploads(path, 'images')
const urls = []
const files = req.files
console.log("this is the files===>",req.files)

for (const file of files){
    const {path}= file
    const newPath = await uploader(path)
    urls.push(newPath)
    fs.unlinkSync(path)

}

req.body.image = urls

// const products = await Products.create(req.body)
res.status(201).json({
    success: true,
    urls,
    message:"urls created successfully"
})
</code>```

} catch (error) {
res.status(404).json({
success: false,
error,
message:"Product not created!"
})
}

})

here is the upload action

```<code> async save() {
            const token = localStorage.getItem("token");
            // console.log("this is payload for", payload)
            const config = {
                headers: {
                    "Content-Type": "multipart/form-data"
                },
            };
            const fD = new FormData();
            fD.append('images', this.files);

            await axios.post('/products', fD)
            .then((res) => {
            console.log("response add products====>", res.data.products);

            let message = res.data && res.data.message;
            console.log(message);

            ctx.commit("setLoading", false)
            toastr.success(message);

            })
            .catch((err) => {
                console.log("this is the error====>", err);
            })

        },
</code>```

i am trying to append the files to the backend

Body:
this is how i have set up my node js backend
///create new products
productRoute.post("/products", isAuthenticatedUser, upload.array('images'),   authorizeRoles('admin', "seller" , "superadmin"), async(req,res, next) => {
// console.log("this is the req.body===>",req)

req.body.user = req.user.id;
try {

const uploader = async(path) => await uploads(path, 'images')
const urls = []
const files = req.files
console.log("this is the files===>",req.files)

for (const file of files){
    const {path}= file
    const newPath = await uploader(path)
    urls.push(newPath)
    fs.unlinkSync(path)

}

req.body.image = urls

// const products = await Products.create(req.body)
res.status(201).json({
    success: true,
    urls,
    message:"urls created successfully"
})

} catch (error) {
res.status(404).json({
success: false,
error,
message:"Product not created!"
})
}

})

here is the upload action

 async save() {
            const token = localStorage.getItem("token");
            // console.log("this is payload for", payload)
            const config = {
                headers: {
                    "Content-Type": "multipart/form-data"
                },
            };
            const fD = new FormData();
            fD.append('images', this.files);

            await axios.post('/products', fD)
            .then((res) => {
            console.log("response add products====>", res.data.products);

            let message = res.data && res.data.message;
            console.log(message);

            ctx.commit("setLoading", false)
            toastr.success(message);

            })
            .catch((err) => {
                console.log("this is the error====>", err);
            })

        },

i am trying to append the files to the backend


问:
%npm_package_name% is undefined when starting an ASP.NET Core / Angular app
I created a new app using the Standalone Angular Typescript project template. When I run the app, I get errors about the PEM file. The app is started by this line in package.json:

```<code>ng serve --ssl --ssl-cert %appdata%\asp.net\https\%npm_package_name%.pem
               --ssl-key %APPDATA%\\ASP.NET\\https\\%npm_package_name%.key
</code>```

When I replaced the two paths with the actual full path, it worked.

When I did echo %npm_package_name% I got %npm_package_name% instead of the actual value so this tells me it couldn't find the path.

How can I get %npm_package_name% to be defined and have the correct package name value? package.json has

```<code>"name": "health-check"
</code>```

and I assume that's where %npm_package_name% should be getting its value?

Body:
I created a new app using the Standalone Angular Typescript project template. When I run the app, I get errors about the PEM file. The app is started by this line in package.json:

ng serve --ssl --ssl-cert %appdata%\asp.net\https\%npm_package_name%.pem
               --ssl-key %APPDATA%\\ASP.NET\\https\\%npm_package_name%.key

When I replaced the two paths with the actual full path, it worked.

When I did echo %npm_package_name% I got %npm_package_name% instead of the actual value so this tells me it couldn't find the path.

How can I get %npm_package_name% to be defined and have the correct package name value? package.json has

"name": "health-check"

and I assume that's where %npm_package_name% should be getting its value?


问:
How do I write a program in tkinter? The task condition is slightly lower
I am trying to calculate the values of the following functions F(x) on the segment [a,b] with a step h, presenting the result in the form of a table, the first column of which is the value of the argument, the second is the corresponding values of the function.

I don't understand how I can create a table in which different values of x and F(x) will be output.

I have described the appearance of the program and some of its functions:

from tkinter import *
from tkinter import ttk

rt = Tk()
rt.geometry('700x700')
rt.title('Табулирование')
rt['bg']= '#33ffe6'
rt.resizable(width =False, height = False)

def otrA():
    global  entA
    entA=int(ent1.get())
    return entA
def otrB():
    global  entB
    entB=int(ent2.get())
    return entB

def otrH():
    global  entH
    entH=float(ent3.get())
    return entH

def v0():
    global V1
    V1=0
    if otrA() < otrB():
        V1 = otrA() + otrH()
    lbe0.config(text = V1)
    return V1

lbe0 = Label(rt, text = '', padx= 15, pady = 15, fg = 'black')
lbe0.place( x = 350, y = 200)

#A
lbe1 = Label(rt, text = 'Введите начало отрезка A' , padx= 20, pady = 15)
lbe1.place( x = 40, y = 40)

ent1 = Entry(rt)
ent1.place(x = 70, y = 90)
#B
lbe2 = Label(rt, text = 'Введите конец отрезка B',padx= 20, pady = 15)
lbe2.place( x = 245, y = 40)

ent2 = Entry(rt)
ent2.place(x = 275, y = 90, )

#H
lbe3 = Label(rt, text = 'Укажите точку отрезке [A B]', padx= 20, pady = 15)
lbe3.place( x = 440, y = 40)

ent3 = Entry(rt)
ent3.place(x = 490, y = 90)

###
btn1= Button(rt, text = 'Вычислить',command = v0, bg = 'white')
btn1.place(x = 245, y = 200)

# добавляем данные
def konets():
    people = [v0]
    for person in people:
        tree.insert('people', END)

columns = ("name", "age", )

tree = ttk.Treeview(rt,columns=columns, show="headings")
tree.pack( expand=2)

# определяем заголовки
tree.heading("name", text="Значение Х")
tree.heading("age", text="Значение F(x)")

###
btn1= Button(rt, text = 'Добавить',command= konets, bg = 'white')
btn1.place(x = 500, y = 200)

rt.mainloop()
```


问:
Why Does Integer and int behave differently when parsed from a String
I was writing a purging logic from a HashSet to keep last 2 days' data :-

```<code>    while(mscDatesIterator.hasNext()) {
        String entry = (String) mscDatesIterator.next();
        Date currentDate = SystemTime.getCurrentTime();
        String currentDateString = subscriberProfile.getSubscriberID() + sdf.format(currentDate);
        Integer currentStringMonth = Integer.parseInt(currentDateString.substring(currentDateString.length() - 4, currentDateString.length() - 2));
        Integer entryStringMonth = Integer.parseInt(entry.substring(entry.length() - 4, entry.length() - 2));
        Integer currentStringDay = Integer.parseInt(currentDateString.substring(currentDateString.length() - 2, currentDateString.length()));
        Integer entryStringDay = Integer.parseInt(entry.substring(entry.length() - 2, entry.length()));
        Integer currentStringYear = Integer.parseInt(currentDateString.substring(currentDateString.length() - 8, currentDateString.length() - 4));
        Integer entryStringYear = Integer.parseInt(entry.substring(entry.length() - 8, entry.length() - 4));
        if((!currentStringYear.equals(entryStringYear)) || (!currentStringMonth.equals(entryStringMonth)) || (currentStringDay - entryStringDay > 2))
            mscDatesIterator.remove();
    }
</code>```

This works just fine, but when I use currentStringYear != entryStringYear, it returns true even though both values are 2022.
Also, if I change the dataType from class Integer to primitive int, currentStringYear != entryStringYear returns false correctly.

I don't understand this behavior, any light shed on this will be appreciated.

Body:
I was writing a purging logic from a HashSet to keep last 2 days' data :-

    while(mscDatesIterator.hasNext()) {
        String entry = (String) mscDatesIterator.next();
        Date currentDate = SystemTime.getCurrentTime();
        String currentDateString = subscriberProfile.getSubscriberID() + sdf.format(currentDate);
        Integer currentStringMonth = Integer.parseInt(currentDateString.substring(currentDateString.length() - 4, currentDateString.length() - 2));
        Integer entryStringMonth = Integer.parseInt(entry.substring(entry.length() - 4, entry.length() - 2));
        Integer currentStringDay = Integer.parseInt(currentDateString.substring(currentDateString.length() - 2, currentDateString.length()));
        Integer entryStringDay = Integer.parseInt(entry.substring(entry.length() - 2, entry.length()));
        Integer currentStringYear = Integer.parseInt(currentDateString.substring(currentDateString.length() - 8, currentDateString.length() - 4));
        Integer entryStringYear = Integer.parseInt(entry.substring(entry.length() - 8, entry.length() - 4));
        if((!currentStringYear.equals(entryStringYear)) || (!currentStringMonth.equals(entryStringMonth)) || (currentStringDay - entryStringDay > 2))
            mscDatesIterator.remove();
    }

This works just fine, but when I use currentStringYear != entryStringYear, it returns true even though both values are 2022.
Also, if I change the dataType from class Integer to primitive int, currentStringYear != entryStringYear returns false correctly.

I don't understand this behavior, any light shed on this will be appreciated.


问:
Can you recover an R object?
Last night I spent 4 straight hours compiling observations into a data frame in R. I saved the data frame as an object and then closed my laptop and decided to finish the observations in the morning. When I opened my laptop today, R studio had been closed out from closing my laptop even though I didn't shut it off. When I opened it, it took me to my previous session with the same script, but my data frame is no longer saved as an object. It took me so long to collect all the data last night. Does R save any kind of history of objects where I can recover it? For some reason R studio has saved other previous objects I defined but not this one. Why did R keep other objects in the environment but not this one?</p>

Title: Can you recover an R object?


问:
Does expo React-native securestore returns an objects for a string value?
how do I get the string value of a TOKEN I saved to the expo-SecureStore using the following code as documented on their page

Functions

```<code>import * as SecureStore from "expo-secure-store";

export async function save(key, value) {
  try {
    const data = await SecureStore.setItemAsync(key, value);
    return data;
  } catch (err) {
    return false;
  }
}

export async function getValueFor(key) {
  let result = await SecureStore.getItemAsync(key);
  if (result) {
    return result;
  } else {
    return false;
  }
}
</code>```

! ####################
Calling function

```<code> try {
      const res = await axios.post("/token/", data);
      await save("jwt_access", "");
      await save("jwt_refresh", res.data.refresh);
      return resolve(res.data);
    } catch (error) {
      reject(error.message);
    }
</code>```
```<code>getValueFor("jwt_access")

getValueFor("jwt_refresh")
</code>```

Output

```<code> {"_A": null, "_x": 0, "_y": 0, "_z": null} //for access token
 {"_A": null, "_x": 0, "_y": 1,
   "_z": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjcxNDEylcm1lbmVudF9yZXNpZGVudCI6dHJ1ZX0.sy9KrdOnplUbnwe1Col3Vchlja7XwSM36hesmWkEclg"
} //for refresh token
</code>```

how do i get just the token alone an not the object

Body:
how do I get the string value of a TOKEN I saved to the expo-SecureStore using the following code as documented on their page

Functions

import * as SecureStore from "expo-secure-store";

export async function save(key, value) {
  try {
    const data = await SecureStore.setItemAsync(key, value);
    return data;
  } catch (err) {
    return false;
  }
}

export async function getValueFor(key) {
  let result = await SecureStore.getItemAsync(key);
  if (result) {
    return result;
  } else {
    return false;
  }
}

! ####################
Calling function

 try {
      const res = await axios.post("/token/", data);
      await save("jwt_access", "");
      await save("jwt_refresh", res.data.refresh);
      return resolve(res.data);
    } catch (error) {
      reject(error.message);
    }

getValueFor("jwt_access")

getValueFor("jwt_refresh")

Output

 {"_A": null, "_x": 0, "_y": 0, "_z": null} //for access token
 {"_A": null, "_x": 0, "_y": 1,
   "_z": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjcxNDEylcm1lbmVudF9yZXNpZGVudCI6dHJ1ZX0.sy9KrdOnplUbnwe1Col3Vchlja7XwSM36hesmWkEclg"
} //for refresh token

how do i get just the token alone an not the object


问:
How to customize plots that were made using "scikitplot.metrics" other than the arguments show in the function?
I made some graphs with scikit-plot package, but need to customize the axes colors and sizes as well the lines width.

Here is what I already have plotted and the editable arguments of the function generating the plot:

skplt.metrics.plot_ks_statistic(y_train,
random_forest.predict_proba(x_train[["out_prncp",
"int_rate","total_rec_prnc","total_pymnt"]]),ax=None, figsize=(15,7), title_fontsize="large",
text_fontsize="medium")
plt.xlim([0,0.7])
plt.title("KS Modelo Random Forest - Treino", size=20)
plt.rc("lines", linewidth=1.5, color='r')
plt.autoscale()
```

As show, the param arguments of matplotlib.pyplot to format are disregarded for some reason.

Just need to set the graph lines to 1.5 points of widths and black colors in the axis ticks

Quick excel hack to show the formating:

Body:
I made some graphs with scikit-plot package, but need to customize the axes colors and sizes as well the lines width.

Here is what I already have plotted and the editable arguments of the function generating the plot:

skplt.metrics.plot_ks_statistic(y_train,
random_forest.predict_proba(x_train[["out_prncp",
"int_rate","total_rec_prnc","total_pymnt"]]),ax=None, figsize=(15,7), title_fontsize="large",
text_fontsize="medium")
plt.xlim([0,0.7])
plt.title("KS Modelo Random Forest - Treino", size=20)
plt.rc("lines", linewidth=1.5, color='r')
plt.autoscale()

As show, the param arguments of matplotlib.pyplot to format are disregarded for some reason.

Just need to set the graph lines to 1.5 points of widths and black colors in the axis ticks

Quick excel hack to show the formating:


问:
Loading data from a file using pattern
I have a problem with reading data from a .txt text file. The point is that I have to load data on the date of the action, which is sometimes written in the format 2020-12-12 and 2022-7-9.
To take further action on this data, I would like the program to read it as a LocalDate type, to do this I created a formatter and a place where ko is applied:

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(dateOfVisit,formatter);
</code>```

I get the error "DateTimeParseExceptionText '2022-1-25' could not be parsed at index 5'.

How could I make this pattern more flexible?

The code is structured correctly and I know that the error lies in what I added above, how would you change it?

Title: Loading data from a file using pattern

Body:
I have a problem with reading data from a .txt text file. The point is that I have to load data on the date of the action, which is sometimes written in the format 2020-12-12 and 2022-7-9.
To take further action on this data, I would like the program to read it as a LocalDate type, to do this I created a formatter and a place where ko is applied:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(dateOfVisit,formatter);

I get the error "DateTimeParseExceptionText '2022-1-25' could not be parsed at index 5'.

How could I make this pattern more flexible?

The code is structured correctly and I know that the error lies in what I added above, how would you change it?


问:
Google Recaptcha V3 crashes on second Ajax submission attempt
I have a simple login system made in Laravel, and I'm using Google Captcha V3 (invisible) to authenticate:

```<code><form class="loginForm">
<input type="text" name="login">
<input type="password" name="password">
<button type="submit">LOGIN</button>
</form>

<script src="https://www.google.com/recaptcha/api.js?render=XXXXXX"></script>

<script>
grecaptcha.ready(function() {
grecaptcha.execute('xxxxxxx', {action: 'newlogin'}).then(function(token) {
$('.loginForm').prepend('<input type="hidden" name="token_gcaptcha" value="' + token + '">');
/*
HERE I HAVE A AJAX FUNCTION THAT SENDS THE CONTENT OF MY FORM TO A ROUTE
*/
});
});
</script>
</code>```

In my Controller Route I use this code to recognize the captcha:

```<code>$recaptcha = new \ReCaptcha\ReCaptcha('XXXXX');
$resp = $recaptcha->setExpectedAction("newlogin")->setScoreThreshold(0.5)->verify($data['token_gcaptcha'], $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess() != true) {
 return array('Error' => 'An Error Ocurred With Captcha', 'Title' => 'Captcha');
}
</code>```

This code works perfectly when the user manages to login on the first attempt, the problem is that if the user misses the login/password on the first attempt, the route will return an error, and the second time he enters his login/password correctly the error that will be returned will be from the CAPTCHA.

This probably happened because maybe the validity of the captcha token has come to an end, no?

In this case, if the user gets his credentials wrong on the first try, he is obliged to refresh the page and try to log in again (this should update the captcha token).

How do I solve this problem?

Body:
I have a simple login system made in Laravel, and I'm using Google Captcha V3 (invisible) to authenticate:

<form class="loginForm">
<input type="text" name="login">
<input type="password" name="password">
<button type="submit">LOGIN</button>
</form>

In my Controller Route I use this code to recognize the captcha:

$recaptcha = new \ReCaptcha\ReCaptcha('XXXXX');
$resp = $recaptcha->setExpectedAction("newlogin")->setScoreThreshold(0.5)->verify($data['token_gcaptcha'], $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess() != true) {
 return array('Error' => 'An Error Ocurred With Captcha', 'Title' => 'Captcha');
}

This code works perfectly when the user manages to login on the first attempt, the problem is that if the user misses the login/password on the first attempt, the route will return an error, and the second time he enters his login/password correctly the error that will be returned will be from the CAPTCHA.

This probably happened because maybe the validity of the captcha token has come to an end, no?

In this case, if the user gets his credentials wrong on the first try, he is obliged to refresh the page and try to log in again (this should update the captcha token).

How do I solve this problem?


问:
How do I control how a Python class is printed (NOT a class instance)
I have a Python class with class attributes, and I would like it to show the values of the attributes when printed.

But instead, it just shows the name of the class.

class CONFIG:
    ONE = 1
    TWO = 2

print(CONFIG)  # <class '__main__.CONFIG'>
```

Of course, if I wanted to instantiate the class, then I could def __repr__() and control how it prints.

The question is, how do I control how a class (NOT a class instance) prints? Is there an equivalent to __repr__ for the class itself?

Workarounds:

Write a function that uses vars() or dir() to iterate over the attributes

Instantiate the class, stop doing things a weird way :)

Change my code in some other way so I no longer have the requirement to print the class (use Enum, SimpleNamespace, etc.)

Body:
I have a Python class with class attributes, and I would like it to show the values of the attributes when printed.

But instead, it just shows the name of the class.

class CONFIG:
    ONE = 1
    TWO = 2

print(CONFIG)  # <class '__main__.CONFIG'>

Of course, if I wanted to instantiate the class, then I could def __repr__() and control how it prints.

The question is, how do I control how a class (NOT a class instance) prints? Is there an equivalent to __repr__ for the class itself?

Workarounds:

Write a function that uses vars() or dir() to iterate over the attributes

Instantiate the class, stop doing things a weird way :)

Change my code in some other way so I no longer have the requirement to print the class (use Enum, SimpleNamespace, etc.)


问:
Python gcc plugin - if value was written to a variable / struct member
I have a question in regard to module of Python gcc plugin - if value was written to a variable / struct member. Is there a way which I can identify using Python GCC plugin if a write/read operation has been done?</p>


问:
JSONDecodeError when parsing through data, works half the time?
Heyo, I've been working on this code:

```<code>import requests as r
import datetime
import openpyxl
import json
import matplotlib #i was gonna use this for graphing later lol

from openpyxl.chart.axis import DateAxis
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference, Series, LineChart

#i dont thinks we have to do it this way, i just saw that this is how the guy on stackoverflow was doing it and didnt argue lol
try:
        from openpyxl.cell import get_column_letter
except ImportError:
        from openpyxl.utils import get_column_letter
        from openpyxl.utils import column_index_from_string

myname = input('Enter your name: ')

def do_the_work(myname):

    userLink = 'https://api.faceit.com/users/v1/nicknames/'+myname #Inputting the name given here to get the UUID of the user

    print("Getting user . . . this may take a while")

    reqUserLink = r.get(userLink).json() #requesting the link's JSON data
    print("UUID Found; ",str(reqUserLink['payload']['id']))
    reqUserList = []
    reqUserList.append(str(reqUserLink['payload']['id'])) #adding it to our own list because python HATES nested stuff
    print(reqUserList)
    userStatsLink = ""
    userStatsLink = f"https://api.faceit.com/stats/v1/stats/time/users/{reqUserList[0]}/games/csgo"
    print(userStatsLink)
    params = {"page": 0, "size": 30} #we have to do this because the data prevents us from having more than 30 matches a page

    matches = [] #creating our own dictionary to grab only relevant data from the matches
    totalRankedM = 1 #showing ranked matches (aka matches that have an ELO value)

    while True:
        reqStatsPage = r.get(userStatsLink, params=params) #Requesting
        statsPageJSON = reqStatsPage.json()
        print(statsPageJSON)
        for match in statsPageJSON:
            elo = match.get("elo")  #elo variable of the stats
            if elo is not None:  #checking if elo does exist (Faceit removes this parameter from matches that have no elo)
                matches.append({ #adding them to our own list with the relevant data wanted
                    'match_id': match["matchId"],
                    'played_on': match["date"],
                    'map': match["i1"],
                    'elo': match["elo"]
                })
                totalRankedM = totalRankedM + 1 #each time we have a match that counts elo, it is a ranked match

            else:
                matches.append({
                    'match_id': match["matchId"],
                    'played_on': match["date"],
                    'map': match["i1"],
                    'elo': ''  #just putting nothing tbh, we replace this later to "No elo recorded" but i like the freedom
                })
        if len(statsPageJSON) < params['size']: #check if we went thru all the pages
            break

        params['page'] += 1 #changing page

    print(f'Total number of matches: {len(matches)}')  #print the total number of matches
    print(f'Total number of ranked matches: {totalRankedM}') #print total ranked matches

    matches.reverse() #since we start at the top of the pages aka most recent matches and go down from there, we reverse this to make it easier for the excel sheet graph so it's in order

    workbook = openpyxl.Workbook()
    worksheet = workbook.active

    worksheet.append(['Match ID', 'Played On', 'Map', 'ELO', 'Total Ranked Matches']) #those are the columns
    for match in matches: #adding the data from the matches=[] list to the sheet
        worksheet.append([match['match_id'], match['played_on'], match['map'], match['elo']])

    worksheet["E2"].value = totalRankedM
    worksheet["F1"].value = 'To view the game room of a specific match, simply use this link: https://www.faceit.com/en/csgo/room/REPLACE THIS WITH MATCHID/scoreboard'

    for cell in worksheet['D']: #to make it pretty in the excel sheet and get rid of errors, we convert the strings that are numbers to actual numbers in the sheet (excel considers them strings, so it throws an error when its a string number)
        if isinstance(cell.value, str):
            try:
                number = int(cell.value)
                cell.data_type = 'n'
                cell.value = number
            except ValueError:
                pass #just ignoring if we can't make it a number

    for cell in worksheet['B']: #the data we are given for the dates are in unix so we just convert
        if isinstance(cell.value, int):
            date = datetime.datetime.fromtimestamp(cell.value / 1000)
            date_str = date.strftime('%d/%m/%Y')
            cell.value = date_str

    for column_cells in worksheet.columns: #this is just to make each cell size fit the length of the text in it
        new_column_length = max(len(str(cell.value)) for cell in column_cells)
        new_column_letter = (get_column_letter(column_cells[0].column))
        if new_column_length > 0:
            worksheet.column_dimensions[new_column_letter].width = new_column_length*1.23

    #and we save the final product xd
    workbook.save('matches.xlsx')

do_the_work(myname)
#fancy stuff
print("\n")
print("\n")
print("\n")
print("You may now look at the excel sheet.")
</code>```

that basically

lets you input a name

uses faceit's API calls to get the data from said account, gets the UUID (because this is the only way you can see the stats page of a user in the link),

adds that UUID to our list (i think I made it that way when trying to figure out why I was getting the error but that part still works fine) (i think lol, still had the same error before it)

then it adds that UUID to the stats link so we can parse through it

grabs the relevant data and adds it to our own list

prints that list

adds it to an excel sheet

Now the weird part of this is that when I try to run the program, it works for the first time and loads everything correctly and adds it to the excel sheet.

But then I want to do it again with the same username (it should just overwrite) and then it stops halfway through it to show me this error:

```<code>Traceback (most recent call last):
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 7 column 10 (char 107)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\SAM\Desktop\elo-scrape\test3.py", line 111, in <module>
    do_the_work(myname)
  File "C:\Users\SAM\Desktop\elo-scrape\test3.py", line 43, in do_the_work
    statsPageJSON = reqStatsPage.json()
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting property name enclosed in double quotes: line 7 column 10 (char 107)
</code>```

This specific account I am loading the data from has a total of 1605 ranked matches for context
But then I try to do it with my own account (328 ranked matches) over and over and it works over and over.

Does it just stop working when we have a huge amount of data? If so what way i could improve this code? I've been spending a while trying to fix it and I'm out of ideas which is why I'm here

Body:
Heyo, I've been working on this code:

import requests as r
import datetime
import openpyxl
import json
import matplotlib #i was gonna use this for graphing later lol

from openpyxl.chart.axis import DateAxis
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference, Series, LineChart

#i dont thinks we have to do it this way, i just saw that this is how the guy on stackoverflow was doing it and didnt argue lol
try:
        from openpyxl.cell import get_column_letter
except ImportError:
        from openpyxl.utils import get_column_letter
        from openpyxl.utils import column_index_from_string

myname = input('Enter your name: ')

def do_the_work(myname):

    userLink = 'https://api.faceit.com/users/v1/nicknames/'+myname #Inputting the name given here to get the UUID of the user

    print("Getting user . . . this may take a while")

    reqUserLink = r.get(userLink).json() #requesting the link's JSON data
    print("UUID Found; ",str(reqUserLink['payload']['id']))
    reqUserList = []
    reqUserList.append(str(reqUserLink['payload']['id'])) #adding it to our own list because python HATES nested stuff
    print(reqUserList)
    userStatsLink = ""
    userStatsLink = f"https://api.faceit.com/stats/v1/stats/time/users/{reqUserList[0]}/games/csgo"
    print(userStatsLink)
    params = {"page": 0, "size": 30} #we have to do this because the data prevents us from having more than 30 matches a page

    matches = [] #creating our own dictionary to grab only relevant data from the matches
    totalRankedM = 1 #showing ranked matches (aka matches that have an ELO value)

    while True:
        reqStatsPage = r.get(userStatsLink, params=params) #Requesting
        statsPageJSON = reqStatsPage.json()
        print(statsPageJSON)
        for match in statsPageJSON:
            elo = match.get("elo")  #elo variable of the stats
            if elo is not None:  #checking if elo does exist (Faceit removes this parameter from matches that have no elo)
                matches.append({ #adding them to our own list with the relevant data wanted
                    'match_id': match["matchId"],
                    'played_on': match["date"],
                    'map': match["i1"],
                    'elo': match["elo"]
                })
                totalRankedM = totalRankedM + 1 #each time we have a match that counts elo, it is a ranked match

            else:
                matches.append({
                    'match_id': match["matchId"],
                    'played_on': match["date"],
                    'map': match["i1"],
                    'elo': ''  #just putting nothing tbh, we replace this later to "No elo recorded" but i like the freedom
                })
        if len(statsPageJSON) < params['size']: #check if we went thru all the pages
            break

        params['page'] += 1 #changing page

    print(f'Total number of matches: {len(matches)}')  #print the total number of matches
    print(f'Total number of ranked matches: {totalRankedM}') #print total ranked matches

    matches.reverse() #since we start at the top of the pages aka most recent matches and go down from there, we reverse this to make it easier for the excel sheet graph so it's in order

    workbook = openpyxl.Workbook()
    worksheet = workbook.active

    worksheet.append(['Match ID', 'Played On', 'Map', 'ELO', 'Total Ranked Matches']) #those are the columns
    for match in matches: #adding the data from the matches=[] list to the sheet
        worksheet.append([match['match_id'], match['played_on'], match['map'], match['elo']])

    worksheet["E2"].value = totalRankedM
    worksheet["F1"].value = 'To view the game room of a specific match, simply use this link: https://www.faceit.com/en/csgo/room/REPLACE THIS WITH MATCHID/scoreboard'

    for cell in worksheet['D']: #to make it pretty in the excel sheet and get rid of errors, we convert the strings that are numbers to actual numbers in the sheet (excel considers them strings, so it throws an error when its a string number)
        if isinstance(cell.value, str):
            try:
                number = int(cell.value)
                cell.data_type = 'n'
                cell.value = number
            except ValueError:
                pass #just ignoring if we can't make it a number

    for cell in worksheet['B']: #the data we are given for the dates are in unix so we just convert
        if isinstance(cell.value, int):
            date = datetime.datetime.fromtimestamp(cell.value / 1000)
            date_str = date.strftime('%d/%m/%Y')
            cell.value = date_str

    for column_cells in worksheet.columns: #this is just to make each cell size fit the length of the text in it
        new_column_length = max(len(str(cell.value)) for cell in column_cells)
        new_column_letter = (get_column_letter(column_cells[0].column))
        if new_column_length > 0:
            worksheet.column_dimensions[new_column_letter].width = new_column_length*1.23

    #and we save the final product xd
    workbook.save('matches.xlsx')

do_the_work(myname)
#fancy stuff
print("\n")
print("\n")
print("\n")
print("You may now look at the excel sheet.")

that basically

lets you input a name

uses faceit's API calls to get the data from said account, gets the UUID (because this is the only way you can see the stats page of a user in the link),

adds that UUID to our list (i think I made it that way when trying to figure out why I was getting the error but that part still works fine) (i think lol, still had the same error before it)

then it adds that UUID to the stats link so we can parse through it

grabs the relevant data and adds it to our own list

prints that list

adds it to an excel sheet

Now the weird part of this is that when I try to run the program, it works for the first time and loads everything correctly and adds it to the excel sheet.

But then I want to do it again with the same username (it should just overwrite) and then it stops halfway through it to show me this error:

Traceback (most recent call last):
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 7 column 10 (char 107)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\SAM\Desktop\elo-scrape\test3.py", line 111, in <module>
    do_the_work(myname)
  File "C:\Users\SAM\Desktop\elo-scrape\test3.py", line 43, in do_the_work
    statsPageJSON = reqStatsPage.json()
  File "C:\Users\SAM\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting property name enclosed in double quotes: line 7 column 10 (char 107)

This specific account I am loading the data from has a total of 1605 ranked matches for context
But then I try to do it with my own account (328 ranked matches) over and over and it works over and over.

Does it just stop working when we have a huge amount of data? If so what way i could improve this code? I've been spending a while trying to fix it and I'm out of ideas which is why I'm here


问:
Change the iOS / android lock screen video thumbnail when playing from web
I am playing video files on a web application, and I would like to be able to put a "video poster" on the iOS / Android lock screens.

I have already tried to put the image url in the poster property on my <video> element, and changing the favicon of the page, but these doesn't work.

Is there a way to achieve this?


问:
Display DB content to a DIV based on a link click
this topic is often to find but I needed a small twitch and couldn't get it to work, maybe someone has an idea?

A query from a DB generates a clickable list where each entry has class "listDetail" and with content named in columns like "A", "B" and "C". The next entry will have same structure but of course different content. The query also delivers a value for a column "D" which shall not be seen in the list (big text part). Content "A" will be clickable (link) with a href="#". I want to catch the action "click" on any of the links of the list and show content "D" for the clicked row then in a separate Div-Container.

Idea:

Make a JS like:

```<code>$(document).on('click', '.listDetailA', function(){
$('.separateDiv').text($(this).getAttribute(beamAttrib));
});
</code>```

I was hoping that I just can "beam" the content of column D then to the separate container e.g. like adding an attribute to the anchor-tag with the content for "D".

```<code><a class="listDetail" href="#" beamAttrib="D[Content]"><img src="..."></a>
</code>```

So when I click on the link the content "D" of that row shall then be seen here:

```<code><div class="separateDiv"></div>
</code>```

But for now I end that the content of "D" is sudden visible beside the image although its an attribute and that the beam-transfer doesnt work.

Any links to a helpful resource or a hint maybe?

Thank you,
Balael

EDIT: Thanks for reviewing and closing but this is not a duplicate to the topic "How to update the html content of a single div?" as I do not want to load ready-made HTML-pages based on a user choice like a navigation menue.I have a list of links where each link has an unique attribute which carries the desired content for the DIV - clicking the link shall transfer the attribute-content to the DIV without reloading any external content.

Body:
this topic is often to find but I needed a small twitch and couldn't get it to work, maybe someone has an idea?

A query from a DB generates a clickable list where each entry has class "listDetail" and with content named in columns like "A", "B" and "C". The next entry will have same structure but of course different content. The query also delivers a value for a column "D" which shall not be seen in the list (big text part). Content "A" will be clickable (link) with a href="#". I want to catch the action "click" on any of the links of the list and show content "D" for the clicked row then in a separate Div-Container.

Idea:

Make a JS like:

$(document).on('click', '.listDetailA', function(){
$('.separateDiv').text($(this).getAttribute(beamAttrib));
});

I was hoping that I just can "beam" the content of column D then to the separate container e.g. like adding an attribute to the anchor-tag with the content for "D".

So when I click on the link the content "D" of that row shall then be seen here:

But for now I end that the content of "D" is sudden visible beside the image although its an attribute and that the beam-transfer doesnt work.

Any links to a helpful resource or a hint maybe?

Thank you,
Balael

EDIT: Thanks for reviewing and closing but this is not a duplicate to the topic "How to update the html content of a single div?" as I do not want to load ready-made HTML-pages based on a user choice like a navigation menue.I have a list of links where each link has an unique attribute which carries the desired content for the DIV - clicking the link shall transfer the attribute-content to the DIV without reloading any external content.


问:
Why is my compiled Rust application so large?
I get a very large size of my compiled Rust application, when I compile it in release mode the target directory grows to a size of 0.5 GB. My source code is 32 KB so I think it is my dependencies that create the large size but when I check the size of the packages on cargo.io it doesn't add up close to 500 MB. Can I somehow find the cause of the size? Here is my cargo.toml:

[package]
name = "communcation_service"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde_json = "1.0"
serde = "1.0"
lapin = "2.1.1" # Kinda big
futures-lite = "1.12.0"
tracing = "0.1.37"
tracing-subscriber = "0.3.16" # Kinda big
dotenv = "0.15.0"
base64 = "0.13.1"
async-trait = "0.1.58"
web-push = "0.9.3"
sentry = "0.23.0"
lettre = { version = "0.10.0-beta.2", default-features = false, features = ["smtp-transport", "tokio1-rustls-tls", "hostname", "r2d2", "builder"] }
```


问:
Undefined error in httr call. httr output: Failed to connect to localhost port 14415 after 0 ms: Connection refused
After updating to RStudio Version 2022.12.0+353 (2022.12.0+353), I am unable to find a freeport using netstat.

I have never had this problem before. How do I fix this?

```<code>library(RSelenium)
library(netstat)
remote_driver <- rsDriver(browser = 'firefox',
                          verbose = F,
                          port = free_port())
Error message:
Could not open firefox browser.
Client error message:
Undefined error in httr call. httr output: Failed to connect to localhost port 14415 after 0 ms: Connection refused
Check server log for further details.
Warning message:
In rsDriver(browser = "firefox", verbose = F, netstat::free_port()) :
  Could not determine server status.
</code>```

I have tried:

netstat::free_port() which failed.

I've switched the browser to chrome with no success.

Docker has never worked with my macbook.

Body:
After updating to RStudio Version 2022.12.0+353 (2022.12.0+353), I am unable to find a freeport using netstat.

I have never had this problem before. How do I fix this?

library(RSelenium)
library(netstat)
remote_driver <- rsDriver(browser = 'firefox',
                          verbose = F,
                          port = free_port())
Error message:
Could not open firefox browser.
Client error message:
Undefined error in httr call. httr output: Failed to connect to localhost port 14415 after 0 ms: Connection refused
Check server log for further details.
Warning message:
In rsDriver(browser = "firefox", verbose = F, netstat::free_port()) :
  Could not determine server status.

I have tried:

netstat::free_port() which failed.

I've switched the browser to chrome with no success.

Docker has never worked with my macbook.


问:
How do I use a refresh token in SuiteCRM?
I'm using SuiteCRM and I've been able to successfully request a refresh token, however I have no idea where to send it. The docs show how get an access token but not how to refresh one: https://docs.suitecrm.com/developer/api/developer-setup-guide/configure-authentication/</p>


问:
Access rpy2 ListVector as result of lm()?
I use the rpy2 python package to execute lm() in R.
As a result, I got a ListVector and this object doesn't behave like a usual python object.

I know how the lm() result looks in R itself.

I don't know how to extract that information from the ListVector result object. How can I investigate such an object?

```<code>rr = robjects.r['lm'](
    formula,
    data = df)
)
</code>```

Body:
I use the rpy2 python package to execute lm() in R.
As a result, I got a ListVector and this object doesn't behave like a usual python object.

I know how the lm() result looks in R itself.

I don't know how to extract that information from the ListVector result object. How can I investigate such an object?

rr = robjects.r['lm'](
    formula,
    data = df)
)


问:
How Innfinite scroll with pagination works?
https://developers.google.com/search/blog/2014/02/infinite-scroll-search-friendly

https://scrollsample.appspot.com/items

Trying to figure out how this is done.
Anyone have an idea?

Been searching on google and in different places now for a week :(


问:
bcrypt encryption to encrypt passwords in txt file
I am geting an error when trying to check a password using the bcrypt library. The issue seems to be that the hashed  variable should be a plain string without "quotation marks". I've attempted to remove the quotation marks multiple times but the error persists. I am seeking assistance in removing the quotation marks from the "hashed" variable in order to make the bcrypt checkpw function work properly.

#----------------------------------------------------------------
#----------------------------------------------------------------
# import module to dencrypt password
#----------------------------------------------------------------
#----------------------------------------------------------------

import bcrypt

def Log_in():
    # Print separator line
    print("-"*70)

    # Prompt user for email or username and password
    msg0 = "Enter your username or your email address"
    msg1 = "Enter your password"
    user_input = input(f"{msg0:45}| ")
    user_pasword = input(f"{msg1:45}| ")
    print("-"*70)

    # Open and read the text file where the user database is stored
    db = open("database.txt",'r')
    contant = db.readlines()
    email_list = []
    username_list = []
    password_list=[]

    # Check if there's content in the database
    if contant == None:
        pass
    else:
        # Split each line of the content by '| ' and append the parts to their corresponding lists
        for i in contant:
            a, b, c, d = i.split("| ")
            email_list.append(a.strip())
            username_list.append(b.strip())
            password_list.append(d.strip())

    # Close the file
    db.close()

    # Check if the entered email or username exists in the email_list or username_list
    if user_input in username_list or user_input in email_list:
        x = None
        y = None

        # Try to get the index of the entered email or username in the email_list and username_list
        try:
            x = username_list.index(user_input)
        except:
            pass
        try:
            y = email_list.index(user_input)
        except:
            pass

        if x != None and y == None:
            # If the entered username exists in the username_list
            # Strip the 'b' character, encode the string to utf-8 and compare it with the entered password
            hashed = password_list[x].strip('b')
            # hashed = hashed.replace("'","")
            hashed = hashed.encode('utf-8')
            if bcrypt.checkpw(user_pasword.encode('utf-8'), hashed):
                print("Welcome")
            else:
                print("incorrect password")

                Log_in()

        elif y != None or x == None:
            # If the entered email exists in the email_list
            # Remove the double quotes and compare it with the entered password
            hashed = password_list[y][:-1]
            hashed = hashed.replace('"','')
            # hashed1 = hashed.replace(b"\n", b"")

            if bcrypt.checkpw((user_pasword.encode("utf-8")),hashed): #error happening here
                print("Welcome")
            else:
                print("incorrect password")
                Log_in()

        else:
            print("incorrect password")
            Log_in()
    else:
        # If the entered email or username doesn't exist in the email_list or username_list
            print("This username or the email does not exist")
        Log_in()

# main function
if __name__ == "__main__":
    Log_in()
```


问:
Applying Black formatter on symlink directory
I have the following folder structure:

```<code>- etl
    - raw
        - raw.py
        - etl (symlink)
            - raw
                - raw.py
                - etl (symlink)
                    ... (infinite paths)
- config.py
</code>```

I've created a symlink from the etl folder. I'm using symlink so that I can have absolute imports from raw.py into config.py. For example, in raw.py I have the following import: from etl.config import MY_CONSTANT. This absolute import is made possible due to the symlink.

However, when I try to run Black, as in poetry run black ${INCLUDE_FILES} and INCLUDE_FILES = ./etl I run into a infinite loop, as Black tryies to enter in the symlinks and keep going forever. This infinite loop doesn't happen with, for example, Pylint and Flake8.

I could try running Black on every single specific .py file. However, as I have many files, that'd be time consuming.

Is there a way to make Black ignore the symlinks? Or is there another workaround for my situation?

Body:
I have the following folder structure:

- etl
    - raw
        - raw.py
        - etl (symlink)
            - raw
                - raw.py
                - etl (symlink)
                    ... (infinite paths)
- config.py

I've created a symlink from the etl folder. I'm using symlink so that I can have absolute imports from raw.py into config.py. For example, in raw.py I have the following import: from etl.config import MY_CONSTANT. This absolute import is made possible due to the symlink.

However, when I try to run Black, as in poetry run black ${INCLUDE_FILES} and INCLUDE_FILES = ./etl I run into a infinite loop, as Black tryies to enter in the symlinks and keep going forever. This infinite loop doesn't happen with, for example, Pylint and Flake8.

I could try running Black on every single specific .py file. However, as I have many files, that'd be time consuming.

Is there a way to make Black ignore the symlinks? Or is there another workaround for my situation?


问:
Shutdown a nameserver in Pyro4 without manual interruption
I know the current development is in Pyro5 but I am using another package (Pyomo) that is still dependent on Pyro 4. For some reason I am not being able to terminate the name server while submitting a slurm request. I have a nameserver as one process, dispatch server as another process, and there are a few more processes for solver server. I can get the result and everything is working fine for me. However, it is annoying that all of the solver servers and dispatch server gets terminated at the end but nameserver does not. This is okay if I run it via terminal where I can force the nameserver shutdown using Ctrl + C but how to enforce this when submitting a job request via slurm?

Dispatch server can be terminated using: proxy.shutdown() where proxy = Pyro.proxy("uri of dispatch server") followed by proxy._pyroRelease(). However, the same process does not work for nameserver and the job halts at that point until I cancel the job using scancel. This is hindering me from submitted multiple job arrays as the nameserver is not terminated without manual interruption.

Is there a way to handle this?

I tried the following:

```<code>ns = Pyro.locateNS()
uri = ns.lookup("Pyro.NameServer")
proxy = Pyro.Proxy(uri)

proxy.shutdown() # also tried proxy._shutdown() and proxy._pyroshutdown()
proxy._pyroRelease()
</code>```

But the error pops up as I figured out proxy does not have any of those methods to shutdown a server.

Body:
I know the current development is in Pyro5 but I am using another package (Pyomo) that is still dependent on Pyro 4. For some reason I am not being able to terminate the name server while submitting a slurm request. I have a nameserver as one process, dispatch server as another process, and there are a few more processes for solver server. I can get the result and everything is working fine for me. However, it is annoying that all of the solver servers and dispatch server gets terminated at the end but nameserver does not. This is okay if I run it via terminal where I can force the nameserver shutdown using Ctrl + C but how to enforce this when submitting a job request via slurm?

Dispatch server can be terminated using: proxy.shutdown() where proxy = Pyro.proxy("uri of dispatch server") followed by proxy._pyroRelease(). However, the same process does not work for nameserver and the job halts at that point until I cancel the job using scancel. This is hindering me from submitted multiple job arrays as the nameserver is not terminated without manual interruption.

Is there a way to handle this?

I tried the following:

ns = Pyro.locateNS()
uri = ns.lookup("Pyro.NameServer")
proxy = Pyro.Proxy(uri)

proxy.shutdown() # also tried proxy._shutdown() and proxy._pyroshutdown()
proxy._pyroRelease()

But the error pops up as I figured out proxy does not have any of those methods to shutdown a server.


问:
Nest JS - About passing parameters to Decorators
I'm working on the cache mechanism.
I need a dynamic cache key. (Module - Method Name - Some Request Parameters)
Like this:  usersModule_getUserById_5

@CacheKey('userModule_getUserById' +request.body.id)
```
<p><strong>Is it possible pass parameters this decorator ?</strong></p>
<p>I will use clear cache with module name or method name or user id on user data changes.</p>
<p>I have specified exactly where I want the sample code below.</p>
<pre class="lang-js prettyprint-override"><code>import {
  CacheInterceptor,
  CacheKey,
  CacheTTL,
  Controller,
  Get,
  Req,
  UseInterceptors,
} from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @UseInterceptors(CacheInterceptor)
  @CacheTTL(3600)
  @CacheKey('userModule_getUserById.....') // ----> I need a dynamic request parameters on this decorator.
  @Get()
  async getHello(@Req() req: Request): Promise<string> {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve('Hello World!');
      }, 3000);
    });
  }
}
</code>```

Body:
I'm working on the cache mechanism.
I need a dynamic cache key. (Module - Method Name - Some Request Parameters)
Like this:  usersModule_getUserById_5

@CacheKey('userModule_getUserById' +request.body.id)

Is it possible pass parameters this decorator ?

I will use clear cache with module name or method name or user id on user data changes.

I have specified exactly where I want the sample code below.

import {
  CacheInterceptor,
  CacheKey,
  CacheTTL,
  Controller,
  Get,
  Req,
  UseInterceptors,
} from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @UseInterceptors(CacheInterceptor)
  @CacheTTL(3600)
  @CacheKey('userModule_getUserById.....') // ----> I need a dynamic request parameters on this decorator.
  @Get()
  async getHello(@Req() req: Request): Promise<string> {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve('Hello World!');
      }, 3000);
    });
  }
}


问:
# before name value in usemap
why to put # before the name value in usemap attribute?
like this:

```<code>    <img src="workplace.jpg" alt="Workplace" usemap="#workmap">
    <map name="workmap">
    </map>

</code>```

i know i have to use the # before referencing and id in href attribute i dont know exactly why but i thought it's just the special sign of id

I'm still learning so can someone clear this for me please?

i tried using name without the # before it but it didn't work

Title: # before name value in usemap

Body:
why to put # before the name value in usemap attribute?
like this:

    <map name="workmap">
    </map>

i know i have to use the # before referencing and id in href attribute i dont know exactly why but i thought it's just the special sign of id

I'm still learning so can someone clear this for me please?

i tried using name without the # before it but it didn't work


问:
Unhandled Runtime Error Error: Cannot read properties of null (reading 'data')
lib/sortNewsByImage.ts (2:29) @ data

1 | export default function sortNewsByImage(news: NewsResponse) {

2 | const newsWithImage = news.data.filter((item) => item.image !== null);
|                           ^
3 | const newsWithoutImage = news.data.filer((item) => item.image === null);
4 |
5 | const sortedNewsResponse = {


问:
select a next element with a specific class in JS
Well, I have n elements with the class "class_one"
and certain other elements with the class "class_two".

These elements are nested and in some cases there are other elements in that nest, what I need is to select the next element with a specific class.

let class_one = document.querySelectorAll('.class_one');

class_one.forEach(element => {
    element.addEventListener('click',()=>{
        console.log("From this element, the next one containing the class class_two");
    })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="class_one">
click 1
</div>

<div class="class_two">elemento 1</div>

<div class="class_one">
click 2
</div>

<div class="class_four"></div>
<div class="class_two">elemento 2</div>

<div class="class_one">
click 3
</div>

<div class="class_six"></div>
<div class="class_two">elemento 3</div>

<div class="class_one">
click 4
</div>

<div class="class_five">click 5</div>

<div class="class_two">elemento 4</div>

<div class="class_one">
click 6
</div>
 <div class="class_two"></div></code>```

Personally, I would like an answer without using Jquery, but all are welcome.

Body:
Well, I have n elements with the class "class_one"
and certain other elements with the class "class_two".

These elements are nested and in some cases there are other elements in that nest, what I need is to select the next element with a specific class.

let class_one = document.querySelectorAll('.class_one');

class_one.forEach(element => {
    element.addEventListener('click',()=>{
        console.log("From this element, the next one containing the class class_two");
    })
});

click 1

elemento 1

click 2

elemento 2

click 3

elemento 3

click 4

click 5

elemento 4

click 6

Personally, I would like an answer without using Jquery, but all are welcome.


问:
Reduce Heap Memory usage
I have a class to store Range of dates and is extensively used in my project in a lot of places. I tried to check the heap usage and this is carrying the highest of all the types in my project by a huge gap, sometimes maxing at 5GB. Is there a better way to optimize this ?

```<code>@Value
public class Range {

    protected static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @NonNull
    @JsonSerialize(using = Serializer.class)
    @JsonDeserialize(using = Deserializer.class)
    LocalDate startDate;

    @NonNull
    @JsonSerialize(using = Serializer.class)
    @JsonDeserialize(using = Deserializer.class)
    LocalDate endDate;

    @NonNull
    Double value;

    private static class Serializer extends JsonSerializer<LocalDate> {

        @Override
        public void serialize(final LocalDate date,
                              final JsonGenerator jsonGenerator) throws IOException {
            jsonGenerator.writeString(date.format(FORMAT));
        }
    }

    private static class Deserializer extends JsonDeserializer<LocalDate> {

        @Override
        public LocalDate deserialize(final JsonParser jsonParser) throws IOException {
            String date = jsonParser.getText();
            return LocalDate.parse(date, FORMAT);
        }
    }
}

</code>```

All the data I have is that this object is using most of the heap space when the traffic is high. So, not sure what my next steps should be.

Title: Reduce Heap Memory usage

Body:
I have a class to store Range of dates and is extensively used in my project in a lot of places. I tried to check the heap usage and this is carrying the highest of all the types in my project by a huge gap, sometimes maxing at 5GB. Is there a better way to optimize this ?

@Value
public class Range {

    protected static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @NonNull
    @JsonSerialize(using = Serializer.class)
    @JsonDeserialize(using = Deserializer.class)
    LocalDate startDate;

    @NonNull
    @JsonSerialize(using = Serializer.class)
    @JsonDeserialize(using = Deserializer.class)
    LocalDate endDate;

    @NonNull
    Double value;

    private static class Serializer extends JsonSerializer<LocalDate> {

        @Override
        public void serialize(final LocalDate date,
                              final JsonGenerator jsonGenerator) throws IOException {
            jsonGenerator.writeString(date.format(FORMAT));
        }
    }

    private static class Deserializer extends JsonDeserializer<LocalDate> {

        @Override
        public LocalDate deserialize(final JsonParser jsonParser) throws IOException {
            String date = jsonParser.getText();
            return LocalDate.parse(date, FORMAT);
        }
    }
}

All the data I have is that this object is using most of the heap space when the traffic is high. So, not sure what my next steps should be.


问:
What's a simple way of having a polymorphic @ViewChildren selector in Angular?
A part of a small Angular app of mine has a set of UI elements that I want to query with @ViewChildren. They would not the same component or directive, but share some common traits (e.g. a common function to call).

The code I've got does work, but it grew a bit with my attempts. So right now my set of Gadgets alls have the same IGadget interface, derive from the same AbstractGadget class and then are configured to use provides: { provide: AbstractGadget, useExisting: ThisGadget }. Apparently the latter is really needed by the @ViewChildren implementation, as it doesn't know of any kind of language level polymorphism.

Sample code on https://stackblitz.com/edit/angular-ivy-hktbci?file=src/app/gadgets.component.ts

Pertinent part:

@Component({
  selector: 'first-gadget',
  providers: [{ provide: AbstractGadget, useExisting: FirstGadget }],
})
class FirstGadget extends AbstractGadget implements IGadget
```

I'm not using the result in the same manner as in the sample code, by the way. The question here is just about getting the verbosity of the @ViewChildren part down, so the UI usage there is just for illustrative purposes. My production system uses Angular 12 right now, but upgrading wouldn't be an issue if it would help here.

I was looking at some really old github issues, and at least back then it was because the DI that's used for the ViewChildren tokens doesn't know about inheritance. Partly because the Dart implementation of Angular couldn't use that.
But all that was a few years ago, and both TypeScript and Angular changed a bit since then, so maybe there's a better way.

Body:
A part of a small Angular app of mine has a set of UI elements that I want to query with @ViewChildren. They would not the same component or directive, but share some common traits (e.g. a common function to call).

The code I've got does work, but it grew a bit with my attempts. So right now my set of Gadgets alls have the same IGadget interface, derive from the same AbstractGadget class and then are configured to use provides: { provide: AbstractGadget, useExisting: ThisGadget }. Apparently the latter is really needed by the @ViewChildren implementation, as it doesn't know of any kind of language level polymorphism.

Sample code on https://stackblitz.com/edit/angular-ivy-hktbci?file=src/app/gadgets.component.ts

Pertinent part:

@Component({
  selector: 'first-gadget',
  providers: [{ provide: AbstractGadget, useExisting: FirstGadget }],
})
class FirstGadget extends AbstractGadget implements IGadget

I'm not using the result in the same manner as in the sample code, by the way. The question here is just about getting the verbosity of the @ViewChildren part down, so the UI usage there is just for illustrative purposes. My production system uses Angular 12 right now, but upgrading wouldn't be an issue if it would help here.

I was looking at some really old github issues, and at least back then it was because the DI that's used for the ViewChildren tokens doesn't know about inheritance. Partly because the Dart implementation of Angular couldn't use that.
But all that was a few years ago, and both TypeScript and Angular changed a bit since then, so maybe there's a better way.


问:
Json string array without attributes transform XSLT
As the tittle says, I need some help to figure out how to transform JSON array without attributes to XSL.

(1)Input:

```<code>{
  "Body": {
    "name": "jhon",
    "ids": ["a", "b"]
  }
}
</code>```

(2) The expected output should have this structure.

```<code>{
  "name": "jhon",
  "ids": ["a", "b"]
}
</code>```

I have tried to transform it like this.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:strip-space elements="*"/>
    <xsl:output method="text"/>
    <xsl:variable name="path" select="*/Body"/>
    <xsl:template match="/">{
        "name" : "<xsl:value-of select="$path/name"/>",
        "ids" : "<xsl:value-of select="$path/ids"/>"
    }
</xsl:template>
</xsl:stylesheet>
</code>```

But the Datapower is not able to transform the json array [ids], instead it returns this message "An error occurred when processing the message" and this output (3):

```<code>{
  "Body": {
    "Fault": {
      "faultcode": "",
      "faultactor": "",
      "detail": {
        "IntegrationError": ""
      }
    }
  }
}
</code>```

If I remove "ids" field from request and transform XSL, it works ok. That's why I believe that I'm not transforming the array correctly.

Body:
As the tittle says, I need some help to figure out how to transform JSON array without attributes to XSL.

(1)Input:

{
  "Body": {
    "name": "jhon",
    "ids": ["a", "b"]
  }
}

(2) The expected output should have this structure.

{
  "name": "jhon",
  "ids": ["a", "b"]
}

I have tried to transform it like this.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:strip-space elements="*"/>
    <xsl:output method="text"/>
    <xsl:variable name="path" select="*/Body"/>
    <xsl:template match="/">{
        "name" : "<xsl:value-of select="$path/name"/>",
        "ids" : "<xsl:value-of select="$path/ids"/>"
    }
</xsl:template>
</xsl:stylesheet>

But the Datapower is not able to transform the json array [ids], instead it returns this message "An error occurred when processing the message" and this output (3):

{
  "Body": {
    "Fault": {
      "faultcode": "",
      "faultactor": "",
      "detail": {
        "IntegrationError": ""
      }
    }
  }
}

If I remove "ids" field from request and transform XSL, it works ok. That's why I believe that I'm not transforming the array correctly.


问:
Functionality to auto pick up the call using expo react native
As part of a project I'm developing an application for the care of people with cognitive disorders, it may happen that such a person forgets where he put his phone. Therefore, it needs functionality that will allow the phone to be automatically answered when a trusted number calls. I don't know what I could use to create such functionality.

I create the application using expo-react-native. I tried to use the expo-phone-call library, but I can't install it because it shows an error that such a library doesn't exist. On the other hand, when trying to use react-native-phone-call, I kept getting errors with importing things.


问:
Reaching IAP secured Cloud Run app (working as an API) through Postman
I am having a hard time making a Cloud Run app that would serve as an internal API for employees (no frontend).
This would have endpoints like: POST api.mydomain.com/post-some-data where i want to pass some body parameters.

After IAP is setup and applied through a Load Balancer, I can enter the url in a browser and a consent screen appears. I log in with an account that has permissions and the relevant code runs as expected.

BUT

When trying with Postman, having the OAuth2 set as Authentication, setting all the token configurations etc - I get a consent screen in the browser as expected. After authentication I get a Access Token back to Postman in the format ya28.a0 ... w0123. When clicking "SEND" it returns

```<code>Invalid IAP credentials: Unable to parse JWT
</code>```

My question

What is required to reach the endpoint (code/app) with the given OAuth header after consent? It works from the browser directly but not through Postman after getting the Access Token from browser consent. The endpoint/app is not reached at all from my understanding. So I cant break down the header in the endpoint-code as far as I know.

The goal is to be able to pass body parameters and having a nice shared API collection in postman. And that cant be done in the same way directly through a browser.

Thanks,

I've set up all the necessary steps in GCP for a Cloud Run app secured by IAP.
I've made sure a simple endpoint works as expected directly through a browser + consent screen.
I've successfully made Postman OAuth2 go through my consent in GCP and ask for auth.
I've got an Access Token back to Postman before sending the request.

Body:
I am having a hard time making a Cloud Run app that would serve as an internal API for employees (no frontend).
This would have endpoints like: POST api.mydomain.com/post-some-data where i want to pass some body parameters.

After IAP is setup and applied through a Load Balancer, I can enter the url in a browser and a consent screen appears. I log in with an account that has permissions and the relevant code runs as expected.

BUT

When trying with Postman, having the OAuth2 set as Authentication, setting all the token configurations etc - I get a consent screen in the browser as expected. After authentication I get a Access Token back to Postman in the format ya28.a0 ... w0123. When clicking "SEND" it returns

Invalid IAP credentials: Unable to parse JWT

My question

What is required to reach the endpoint (code/app) with the given OAuth header after consent? It works from the browser directly but not through Postman after getting the Access Token from browser consent. The endpoint/app is not reached at all from my understanding. So I cant break down the header in the endpoint-code as far as I know.

The goal is to be able to pass body parameters and having a nice shared API collection in postman. And that cant be done in the same way directly through a browser.

Thanks,

I've set up all the necessary steps in GCP for a Cloud Run app secured by IAP.
I've made sure a simple endpoint works as expected directly through a browser + consent screen.
I've successfully made Postman OAuth2 go through my consent in GCP and ask for auth.
I've got an Access Token back to Postman before sending the request.


问:
how to encode an exported csv file to display special characters?
I have a script that will export a dataset from an API to a csv file, however some of the text within the csv files contains special characters, ie romanian lettering.

How would I encode the exported csv files...i think to UTF-8, so that all the special characters are displayed correctly.

Thanks in advance

```<code># -*- coding: utf-8 -*-
"""
Created on Sat Dec 17 21:32:54 2022

@author: Dan
"""

import requests
import pandas as pd
import json
import csv

file = open('datapath.csv', encoding='UTF-8')

type(file)

csvreader = csv.reader(file)

header = []
header = next(csvreader)
header

rows = []
for row in csvreader:
        rows.append(row)
rows

for row in rows:
    url = row[0]

    headers = {'Accept': 'application/json',
            'Content-Type': 'application/json'
            }

    response = requests.request("GET", url, headers=headers, data={})
    myjson = response.json()
    myjson_data = myjson['data']

    data_csv = pd.DataFrame(myjson_data)
    data_csv.to_csv(row[1] + '.csv')

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

This being my script so far.

Body:
I have a script that will export a dataset from an API to a csv file, however some of the text within the csv files contains special characters, ie romanian lettering.

How would I encode the exported csv files...i think to UTF-8, so that all the special characters are displayed correctly.

Thanks in advance

# -*- coding: utf-8 -*-
"""
Created on Sat Dec 17 21:32:54 2022

@author: Dan
"""

import requests
import pandas as pd
import json
import csv

file = open('datapath.csv', encoding='UTF-8')

type(file)

csvreader = csv.reader(file)

header = []
header = next(csvreader)
header

rows = []
for row in csvreader:
        rows.append(row)
rows

for row in rows:
    url = row[0]

    headers = {'Accept': 'application/json',
            'Content-Type': 'application/json'
            }

    response = requests.request("GET", url, headers=headers, data={})
    myjson = response.json()
    myjson_data = myjson['data']

    data_csv = pd.DataFrame(myjson_data)
    data_csv.to_csv(row[1] + '.csv')

file.close()

This being my script so far.


问:
How to handle Nas in Lme4
I am using lme4 R package, but I have NA values in data.
I am running the command given below (where, Rtot contains some NaN values.)

 event_lme <- lmer(Rtot ~1 + (1 |EQID))
```

Rtot contains some NaN values.

When I run this it gives me this error :

Error in KhatriRao(sm, t(mm)) : (p <- ncol(X)) == ncol(Y) is not TRUE

I don't want to drop NA values. Ultimately I am looking for ranef(event_lme) which will have NA values at appropriate places.

Here is a subset of my data

Rtot
EQID

NA
127

NA
30

0.058011
151

NA
127

0.5780
1135

0.3306
127

First
1135

0.208
1039

0.057
30

Please advise how to resolve this.

Thanks

Title: How to handle Nas in Lme4

Body:
I am using lme4 R package, but I have NA values in data.
I am running the command given below (where, Rtot contains some NaN values.)

 event_lme <- lmer(Rtot ~1 + (1 |EQID))

Rtot contains some NaN values.

When I run this it gives me this error :

Error in KhatriRao(sm, t(mm)) : (p <- ncol(X)) == ncol(Y) is not TRUE

I don't want to drop NA values. Ultimately I am looking for ranef(event_lme) which will have NA values at appropriate places.

Here is a subset of my data

Rtot
EQID

NA
127

NA
30

0.058011
151

NA
127

0.5780
1135

0.3306
127

First
1135

0.208
1039

0.057
30

Please advise how to resolve this.

Thanks


问:
Not able to properly display Card inside of grid
I am having a bit of an issue displaying a card properly inside a grid.
I am using material UI.

This is the code snip that is causing issues:

```<code><mat-grid-list cols="5" rowHeight="1:1">
  <mat-grid-tile *ngFor="let review of reviews">
    <mat-card class="card-container" >
      <mat-card-title>
        <app-stars rating="{{ review.rating }}"></app-stars>
      </mat-card-title>

      <mat-card-content>{{
        review.text.length > 150
          ? (review.text | slice : 0 : 150) + "..."
          : review.text
      }}</mat-card-content>
      <mat-card-footer>
        <p>- {{ review.user.name }}</p>
        <p>- source: {{ review.source }} || {{ review.time_created | date }}</p>
      </mat-card-footer>
    </mat-card>
  </mat-grid-tile>
</mat-grid-list>
</code>```

here is a video explaining the issue: https://youtu.be/ZO-tCmTiH5g

Now that I am writing this, maybe I have to set the number of columns to display when the viewport gets below some minimum? I just tried this and it kinda works. Not sure that this is the correct way to do it, though.

Is there a way to do this better?

I would like to make it look something like this :: https://preview.themeforest.net/item/archi-interior-design-wordpress-theme/full_screen_preview/12649286?_ga=2.32530814.1141413166.1671312829-1736831966.1665092146

this is where all my code lives ::  https://github.com/casas1010/angular-website

I didn't see a similar StackOverflow question

Body:
I am having a bit of an issue displaying a card properly inside a grid.
I am using material UI.

This is the code snip that is causing issues:

<mat-grid-list cols="5" rowHeight="1:1">
  <mat-grid-tile *ngFor="let review of reviews">
    <mat-card class="card-container" >
      <mat-card-title>
        <app-stars rating="{{ review.rating }}"></app-stars>
      </mat-card-title>

      <mat-card-content>{{
        review.text.length > 150
          ? (review.text | slice : 0 : 150) + "..."
          : review.text
      }}</mat-card-content>
      <mat-card-footer>

- {{ review.user.name }}

- source: {{ review.source }} || {{ review.time_created | date }}

      </mat-card-footer>
    </mat-card>
  </mat-grid-tile>
</mat-grid-list>

here is a video explaining the issue: https://youtu.be/ZO-tCmTiH5g

Now that I am writing this, maybe I have to set the number of columns to display when the viewport gets below some minimum? I just tried this and it kinda works. Not sure that this is the correct way to do it, though.

Is there a way to do this better?

I would like to make it look something like this :: https://preview.themeforest.net/item/archi-interior-design-wordpress-theme/full_screen_preview/12649286?_ga=2.32530814.1141413166.1671312829-1736831966.1665092146

this is where all my code lives ::  https://github.com/casas1010/angular-website

I didn't see a similar StackOverflow question